repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.getIsUnPublishScheduled
public function getIsUnPublishScheduled() { if (!$this->owner->UnPublishOnDate) { return false; } $now = DBDatetime::now()->getTimestamp(); $unpublish = $this->owner->dbObject('UnPublishOnDate')->getTimestamp(); return $now < $unpublish; }
php
public function getIsUnPublishScheduled() { if (!$this->owner->UnPublishOnDate) { return false; } $now = DBDatetime::now()->getTimestamp(); $unpublish = $this->owner->dbObject('UnPublishOnDate')->getTimestamp(); return $now < $unpublish; }
[ "public", "function", "getIsUnPublishScheduled", "(", ")", "{", "if", "(", "!", "$", "this", "->", "owner", "->", "UnPublishOnDate", ")", "{", "return", "false", ";", "}", "$", "now", "=", "DBDatetime", "::", "now", "(", ")", "->", "getTimestamp", "(", ...
Returns whether an unpublishing date has been set and is after the current date @return bool
[ "Returns", "whether", "an", "unpublishing", "date", "has", "been", "set", "and", "is", "after", "the", "current", "date" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L528-L537
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowEmbargoExpiryExtension.php
WorkflowEmbargoExpiryExtension.canEdit
public function canEdit($member) { if (!Permission::check('EDIT_EMBARGOED_WORKFLOW') && // not given global/override permission to edit !$this->owner->AllowEmbargoedEditing) { // item flagged as not editable $publishTime = $this->owner->dbObject('PublishOnDate'); if ($publishTime && $publishTime->InFuture() || // when scheduled publish date is in the future // when there isn't a publish date, but a Job is in place (publish immediately, but queued jobs is // waiting) (!$publishTime && $this->owner->PublishJobID != 0) ) { return false; } } }
php
public function canEdit($member) { if (!Permission::check('EDIT_EMBARGOED_WORKFLOW') && // not given global/override permission to edit !$this->owner->AllowEmbargoedEditing) { // item flagged as not editable $publishTime = $this->owner->dbObject('PublishOnDate'); if ($publishTime && $publishTime->InFuture() || // when scheduled publish date is in the future // when there isn't a publish date, but a Job is in place (publish immediately, but queued jobs is // waiting) (!$publishTime && $this->owner->PublishJobID != 0) ) { return false; } } }
[ "public", "function", "canEdit", "(", "$", "member", ")", "{", "if", "(", "!", "Permission", "::", "check", "(", "'EDIT_EMBARGOED_WORKFLOW'", ")", "&&", "// not given global/override permission to edit", "!", "$", "this", "->", "owner", "->", "AllowEmbargoedEditing"...
Add edit check for when publishing has been scheduled and if any workflow definitions want the item to be disabled. @param Member $member @return bool|null
[ "Add", "edit", "check", "for", "when", "publishing", "has", "been", "scheduled", "and", "if", "any", "workflow", "definitions", "want", "the", "item", "to", "be", "disabled", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowEmbargoExpiryExtension.php#L546-L560
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.getEditForm
public function getEditForm($id = null, $fields = null) { $form = parent::getEditForm($id, $fields); $definitionGridFieldName = $this->sanitiseClassName(WorkflowDefinition::class); // Show items submitted into a workflow for current user to action $fieldName = 'PendingObjects'; $pending = $this->userObjects(Security::getCurrentUser(), $fieldName); if ($this->config()->fieldOverrides) { $displayFields = $this->config()->fieldOverrides; } else { $displayFields = array( 'Title' => _t('AdvancedWorkflowAdmin.Title', 'Title'), 'LastEdited' => _t('AdvancedWorkflowAdmin.LastEdited', 'Changed'), 'WorkflowTitle' => _t('AdvancedWorkflowAdmin.WorkflowTitle', 'Effective workflow'), 'WorkflowStatus' => _t('AdvancedWorkflowAdmin.WorkflowStatus', 'Current action'), ); } // Pending/Submitted items GridField Config $config = new GridFieldConfig_Base(); $config->addComponent(new GridFieldEditButton()); $config->addComponent(new GridFieldDetailForm()); $config->getComponentByType(GridFieldPaginator::class)->setItemsPerPage(5); $columns = $config->getComponentByType(GridFieldDataColumns::class); $columns->setFieldFormatting($this->setFieldFormatting($config)); if ($pending->count()) { $formFieldTop = GridField::create( $fieldName, $this->isAdminUser(Security::getCurrentUser()) ? _t( 'AdvancedWorkflowAdmin.GridFieldTitleAssignedAll', 'All pending items' ): _t( 'AdvancedWorkflowAdmin.GridFieldTitleAssignedYour', 'Your pending items' ), $pending, $config ); $dataColumns = $formFieldTop->getConfig()->getComponentByType(GridFieldDataColumns::class); $dataColumns->setDisplayFields($displayFields); $formFieldTop->setForm($form); $form->Fields()->insertBefore($definitionGridFieldName, $formFieldTop); } // Show items submitted into a workflow by current user $fieldName = 'SubmittedObjects'; $submitted = $this->userObjects(Security::getCurrentUser(), $fieldName); if ($submitted->count()) { $formFieldBottom = GridField::create( $fieldName, $this->isAdminUser(Security::getCurrentUser()) ? _t( 'AdvancedWorkflowAdmin.GridFieldTitleSubmittedAll', 'All submitted items' ): _t( 'AdvancedWorkflowAdmin.GridFieldTitleSubmittedYour', 'Your submitted items' ), $submitted, $config ); $dataColumns = $formFieldBottom->getConfig()->getComponentByType(GridFieldDataColumns::class); $dataColumns->setDisplayFields($displayFields); $formFieldBottom->setForm($form); $formFieldBottom->getConfig()->removeComponentsByType(GridFieldEditButton::class); $formFieldBottom->getConfig()->addComponent(new GridFieldWorkflowRestrictedEditButton()); $form->Fields()->insertBefore($definitionGridFieldName, $formFieldBottom); } $grid = $form->Fields()->fieldByName($definitionGridFieldName); if ($grid) { $grid->getConfig()->getComponentByType(GridFieldDetailForm::class) ->setItemEditFormCallback(function ($form) { $record = $form->getRecord(); if ($record) { $record->updateAdminActions($form->Actions()); } }); $grid->getConfig()->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(WorkflowDefinitionItemRequestClass::class); $grid->getConfig()->addComponent(new GridFieldExportAction()); $grid->getConfig()->removeComponentsByType(GridFieldExportButton::class); $grid->getConfig()->removeComponentsByType(GridFieldImportButton::class); } $this->extend('updateEditFormAfter', $form); return $form; }
php
public function getEditForm($id = null, $fields = null) { $form = parent::getEditForm($id, $fields); $definitionGridFieldName = $this->sanitiseClassName(WorkflowDefinition::class); // Show items submitted into a workflow for current user to action $fieldName = 'PendingObjects'; $pending = $this->userObjects(Security::getCurrentUser(), $fieldName); if ($this->config()->fieldOverrides) { $displayFields = $this->config()->fieldOverrides; } else { $displayFields = array( 'Title' => _t('AdvancedWorkflowAdmin.Title', 'Title'), 'LastEdited' => _t('AdvancedWorkflowAdmin.LastEdited', 'Changed'), 'WorkflowTitle' => _t('AdvancedWorkflowAdmin.WorkflowTitle', 'Effective workflow'), 'WorkflowStatus' => _t('AdvancedWorkflowAdmin.WorkflowStatus', 'Current action'), ); } // Pending/Submitted items GridField Config $config = new GridFieldConfig_Base(); $config->addComponent(new GridFieldEditButton()); $config->addComponent(new GridFieldDetailForm()); $config->getComponentByType(GridFieldPaginator::class)->setItemsPerPage(5); $columns = $config->getComponentByType(GridFieldDataColumns::class); $columns->setFieldFormatting($this->setFieldFormatting($config)); if ($pending->count()) { $formFieldTop = GridField::create( $fieldName, $this->isAdminUser(Security::getCurrentUser()) ? _t( 'AdvancedWorkflowAdmin.GridFieldTitleAssignedAll', 'All pending items' ): _t( 'AdvancedWorkflowAdmin.GridFieldTitleAssignedYour', 'Your pending items' ), $pending, $config ); $dataColumns = $formFieldTop->getConfig()->getComponentByType(GridFieldDataColumns::class); $dataColumns->setDisplayFields($displayFields); $formFieldTop->setForm($form); $form->Fields()->insertBefore($definitionGridFieldName, $formFieldTop); } // Show items submitted into a workflow by current user $fieldName = 'SubmittedObjects'; $submitted = $this->userObjects(Security::getCurrentUser(), $fieldName); if ($submitted->count()) { $formFieldBottom = GridField::create( $fieldName, $this->isAdminUser(Security::getCurrentUser()) ? _t( 'AdvancedWorkflowAdmin.GridFieldTitleSubmittedAll', 'All submitted items' ): _t( 'AdvancedWorkflowAdmin.GridFieldTitleSubmittedYour', 'Your submitted items' ), $submitted, $config ); $dataColumns = $formFieldBottom->getConfig()->getComponentByType(GridFieldDataColumns::class); $dataColumns->setDisplayFields($displayFields); $formFieldBottom->setForm($form); $formFieldBottom->getConfig()->removeComponentsByType(GridFieldEditButton::class); $formFieldBottom->getConfig()->addComponent(new GridFieldWorkflowRestrictedEditButton()); $form->Fields()->insertBefore($definitionGridFieldName, $formFieldBottom); } $grid = $form->Fields()->fieldByName($definitionGridFieldName); if ($grid) { $grid->getConfig()->getComponentByType(GridFieldDetailForm::class) ->setItemEditFormCallback(function ($form) { $record = $form->getRecord(); if ($record) { $record->updateAdminActions($form->Actions()); } }); $grid->getConfig()->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(WorkflowDefinitionItemRequestClass::class); $grid->getConfig()->addComponent(new GridFieldExportAction()); $grid->getConfig()->removeComponentsByType(GridFieldExportButton::class); $grid->getConfig()->removeComponentsByType(GridFieldImportButton::class); } $this->extend('updateEditFormAfter', $form); return $form; }
[ "public", "function", "getEditForm", "(", "$", "id", "=", "null", ",", "$", "fields", "=", "null", ")", "{", "$", "form", "=", "parent", "::", "getEditForm", "(", "$", "id", ",", "$", "fields", ")", ";", "$", "definitionGridFieldName", "=", "$", "thi...
/* Shows up to x2 GridFields for Pending and Submitted items, dependent upon the current CMS user and that user's permissions on the objects showing in each field.
[ "/", "*", "Shows", "up", "to", "x2", "GridFields", "for", "Pending", "and", "Submitted", "items", "dependent", "upon", "the", "current", "CMS", "user", "and", "that", "user", "s", "permissions", "on", "the", "objects", "showing", "in", "each", "field", "."...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L100-L200
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.columns
public function columns() { $fields = array( 'Title' => array( 'link' => function ($value, $item) { $pageAdminLink = singleton(CMSPageEditController::class)->Link('show'); return sprintf('<a href="%s/%s">%s</a>', $pageAdminLink, $item->Link, $value); } ), 'WorkflowStatus' => array( 'text' => function ($value, $item) { return $item->WorkflowCurrentAction; } ) ); return $fields; }
php
public function columns() { $fields = array( 'Title' => array( 'link' => function ($value, $item) { $pageAdminLink = singleton(CMSPageEditController::class)->Link('show'); return sprintf('<a href="%s/%s">%s</a>', $pageAdminLink, $item->Link, $value); } ), 'WorkflowStatus' => array( 'text' => function ($value, $item) { return $item->WorkflowCurrentAction; } ) ); return $fields; }
[ "public", "function", "columns", "(", ")", "{", "$", "fields", "=", "array", "(", "'Title'", "=>", "array", "(", "'link'", "=>", "function", "(", "$", "value", ",", "$", "item", ")", "{", "$", "pageAdminLink", "=", "singleton", "(", "CMSPageEditControlle...
/* By default, we implement GridField_ColumnProvider to allow users to click through to the PagesAdmin. We would also like a "Quick View", that allows users to quickly make a decision on a given workflow-bound content-object
[ "/", "*", "By", "default", "we", "implement", "GridField_ColumnProvider", "to", "allow", "users", "to", "click", "through", "to", "the", "PagesAdmin", ".", "We", "would", "also", "like", "a", "Quick", "View", "that", "allows", "users", "to", "quickly", "make...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L219-L235
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.setFieldFormatting
public function setFieldFormatting(&$config) { $fieldFormatting = array(); // Parse the column information foreach ($this->columns() as $source => $info) { if (isset($info['link']) && $info['link']) { $fieldFormatting[$source] = '<a href=\"$ObjectRecordLink\">$value</a>'; } if (isset($info['text']) && $info['text']) { $fieldFormatting[$source] = $info['text']; } } return $fieldFormatting; }
php
public function setFieldFormatting(&$config) { $fieldFormatting = array(); // Parse the column information foreach ($this->columns() as $source => $info) { if (isset($info['link']) && $info['link']) { $fieldFormatting[$source] = '<a href=\"$ObjectRecordLink\">$value</a>'; } if (isset($info['text']) && $info['text']) { $fieldFormatting[$source] = $info['text']; } } return $fieldFormatting; }
[ "public", "function", "setFieldFormatting", "(", "&", "$", "config", ")", "{", "$", "fieldFormatting", "=", "array", "(", ")", ";", "// Parse the column information", "foreach", "(", "$", "this", "->", "columns", "(", ")", "as", "$", "source", "=>", "$", "...
/* Discreet method used by both intro gridfields to format the target object's links and clickable text @param GridFieldConfig $config @return array $fieldFormatting
[ "/", "*", "Discreet", "method", "used", "by", "both", "intro", "gridfields", "to", "format", "the", "target", "object", "s", "links", "and", "clickable", "text" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L243-L256
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.userObjects
public function userObjects(Member $user, $fieldName) { $list = new ArrayList(); $userWorkflowInstances = $this->getFieldDependentData($user, $fieldName); foreach ($userWorkflowInstances as $instance) { if (!$instance->TargetID || !$instance->DefinitionID) { continue; } // @todo can we use $this->getDefinitionFor() to fetch the "Parent" definition of $instance? Maybe // define $this->workflowParent() $effectiveWorkflow = DataObject::get_by_id(WorkflowDefinition::class, $instance->DefinitionID); $target = $instance->getTarget(); if (!is_object($effectiveWorkflow) || !$target) { continue; } $instance->setField('WorkflowTitle', $effectiveWorkflow->getField('Title')); $instance->setField('WorkflowCurrentAction', $instance->getCurrentAction()); // Note the order of property-setting here, somehow $instance->Title is overwritten by the Target // Title property.. $instance->setField('Title', $target->getField('Title')); $instance->setField('LastEdited', $target->getField('LastEdited')); if (method_exists($target, 'CMSEditLink')) { $instance->setField('ObjectRecordLink', $target->CMSEditLink()); } $list->push($instance); } return $list; }
php
public function userObjects(Member $user, $fieldName) { $list = new ArrayList(); $userWorkflowInstances = $this->getFieldDependentData($user, $fieldName); foreach ($userWorkflowInstances as $instance) { if (!$instance->TargetID || !$instance->DefinitionID) { continue; } // @todo can we use $this->getDefinitionFor() to fetch the "Parent" definition of $instance? Maybe // define $this->workflowParent() $effectiveWorkflow = DataObject::get_by_id(WorkflowDefinition::class, $instance->DefinitionID); $target = $instance->getTarget(); if (!is_object($effectiveWorkflow) || !$target) { continue; } $instance->setField('WorkflowTitle', $effectiveWorkflow->getField('Title')); $instance->setField('WorkflowCurrentAction', $instance->getCurrentAction()); // Note the order of property-setting here, somehow $instance->Title is overwritten by the Target // Title property.. $instance->setField('Title', $target->getField('Title')); $instance->setField('LastEdited', $target->getField('LastEdited')); if (method_exists($target, 'CMSEditLink')) { $instance->setField('ObjectRecordLink', $target->CMSEditLink()); } $list->push($instance); } return $list; }
[ "public", "function", "userObjects", "(", "Member", "$", "user", ",", "$", "fieldName", ")", "{", "$", "list", "=", "new", "ArrayList", "(", ")", ";", "$", "userWorkflowInstances", "=", "$", "this", "->", "getFieldDependentData", "(", "$", "user", ",", "...
Get WorkflowInstance Target objects to show for users in initial gridfield(s) @param Member $member @param string $fieldName The name of the gridfield that determines which dataset to return @return DataList @todo Add the ability to see embargo/expiry dates in report-gridfields at-a-glance if QueuedJobs module installed
[ "Get", "WorkflowInstance", "Target", "objects", "to", "show", "for", "users", "in", "initial", "gridfield", "(", "s", ")" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L266-L294
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.getFieldDependentData
public function getFieldDependentData(Member $user, $fieldName) { if ($fieldName == 'PendingObjects') { return $this->getWorkflowService()->userPendingItems($user); } if ($fieldName == 'SubmittedObjects') { return $this->getWorkflowService()->userSubmittedItems($user); } }
php
public function getFieldDependentData(Member $user, $fieldName) { if ($fieldName == 'PendingObjects') { return $this->getWorkflowService()->userPendingItems($user); } if ($fieldName == 'SubmittedObjects') { return $this->getWorkflowService()->userSubmittedItems($user); } }
[ "public", "function", "getFieldDependentData", "(", "Member", "$", "user", ",", "$", "fieldName", ")", "{", "if", "(", "$", "fieldName", "==", "'PendingObjects'", ")", "{", "return", "$", "this", "->", "getWorkflowService", "(", ")", "->", "userPendingItems", ...
/* Return content-object data depending on which gridfeld is calling for it @param Member $user @param string $fieldName
[ "/", "*", "Return", "content", "-", "object", "data", "depending", "on", "which", "gridfeld", "is", "calling", "for", "it" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L302-L310
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.export
public function export(HTTPRequest $request) { $url = explode('/', $request->getURL()); $definitionID = end($url); if ($definitionID && is_numeric($definitionID)) { $exporter = new WorkflowDefinitionExporter($definitionID); $exportFilename = WorkflowDefinitionExporter::config() ->get('export_filename_prefix') . '-' . $definitionID . '.yml'; $exportBody = $exporter->export(); $fileData = array( 'name' => $exportFilename, 'mime' => 'text/x-yaml', 'body' => $exportBody, 'size' => $exporter->getExportSize($exportBody) ); return $exporter->sendFile($fileData); } }
php
public function export(HTTPRequest $request) { $url = explode('/', $request->getURL()); $definitionID = end($url); if ($definitionID && is_numeric($definitionID)) { $exporter = new WorkflowDefinitionExporter($definitionID); $exportFilename = WorkflowDefinitionExporter::config() ->get('export_filename_prefix') . '-' . $definitionID . '.yml'; $exportBody = $exporter->export(); $fileData = array( 'name' => $exportFilename, 'mime' => 'text/x-yaml', 'body' => $exportBody, 'size' => $exporter->getExportSize($exportBody) ); return $exporter->sendFile($fileData); } }
[ "public", "function", "export", "(", "HTTPRequest", "$", "request", ")", "{", "$", "url", "=", "explode", "(", "'/'", ",", "$", "request", "->", "getURL", "(", ")", ")", ";", "$", "definitionID", "=", "end", "(", "$", "url", ")", ";", "if", "(", ...
Spits out an exported version of the selected WorkflowDefinition for download. @param HTTPRequest $request @return HTTPResponse
[ "Spits", "out", "an", "exported", "version", "of", "the", "selected", "WorkflowDefinition", "for", "download", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L318-L335
symbiote/silverstripe-advancedworkflow
src/Admin/AdvancedWorkflowAdmin.php
AdvancedWorkflowAdmin.ImportForm
public function ImportForm() { $form = parent::ImportForm(); if (!$form) { return; } $form->unsetAllActions(); $newActionList = new FieldList(array( new FormAction('import', _t('AdvancedWorkflowAdmin.IMPORT', 'Import workflow')) )); $form->Fields()->fieldByName('_CsvFile')->getValidator()->setAllowedExtensions(array('yml', 'yaml')); $form->Fields()->removeByName('EmptyBeforeImport'); $form->setActions($newActionList); return $form; }
php
public function ImportForm() { $form = parent::ImportForm(); if (!$form) { return; } $form->unsetAllActions(); $newActionList = new FieldList(array( new FormAction('import', _t('AdvancedWorkflowAdmin.IMPORT', 'Import workflow')) )); $form->Fields()->fieldByName('_CsvFile')->getValidator()->setAllowedExtensions(array('yml', 'yaml')); $form->Fields()->removeByName('EmptyBeforeImport'); $form->setActions($newActionList); return $form; }
[ "public", "function", "ImportForm", "(", ")", "{", "$", "form", "=", "parent", "::", "ImportForm", "(", ")", ";", "if", "(", "!", "$", "form", ")", "{", "return", ";", "}", "$", "form", "->", "unsetAllActions", "(", ")", ";", "$", "newActionList", ...
Required so we can simply change the visible label of the "Import" button and lose some redundant form-fields. @return Form
[ "Required", "so", "we", "can", "simply", "change", "the", "visible", "label", "of", "the", "Import", "button", "and", "lose", "some", "redundant", "form", "-", "fields", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/AdvancedWorkflowAdmin.php#L342-L358
symbiote/silverstripe-advancedworkflow
src/Forms/gridfield/GridFieldWorkflowRestrictedEditButton.php
GridFieldWorkflowRestrictedEditButton.getColumnAttributes
public function getColumnAttributes($gridField, $record, $columnName) { $defaultAtts = array('class' => 'col-buttons'); if ($record instanceof WorkflowInstance) { $isAdmin = Permission::check('ADMIN'); $isAssigned = $record->getAssignedMembers()->find('ID', Security::getCurrentUser()->ID); if (!$isAdmin && !$isAssigned) { $atts['class'] = $defaultAtts['class'].' disabled'; return $atts; } return $defaultAtts; } return $defaultAtts; }
php
public function getColumnAttributes($gridField, $record, $columnName) { $defaultAtts = array('class' => 'col-buttons'); if ($record instanceof WorkflowInstance) { $isAdmin = Permission::check('ADMIN'); $isAssigned = $record->getAssignedMembers()->find('ID', Security::getCurrentUser()->ID); if (!$isAdmin && !$isAssigned) { $atts['class'] = $defaultAtts['class'].' disabled'; return $atts; } return $defaultAtts; } return $defaultAtts; }
[ "public", "function", "getColumnAttributes", "(", "$", "gridField", ",", "$", "record", ",", "$", "columnName", ")", "{", "$", "defaultAtts", "=", "array", "(", "'class'", "=>", "'col-buttons'", ")", ";", "if", "(", "$", "record", "instanceof", "WorkflowInst...
Append a 'disabled' CSS class to GridField rows whose WorkflowInstance records are not viewable/editable by the current user. This is used to visually "grey out" records and it's leveraged in some overriding JavaScript, to maintain an ability to click the target object's hyperlink. @param GridField $gridField @param DataObject $record @param string $columnName @return array
[ "Append", "a", "disabled", "CSS", "class", "to", "GridField", "rows", "whose", "WorkflowInstance", "records", "are", "not", "viewable", "/", "editable", "by", "the", "current", "user", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Forms/gridfield/GridFieldWorkflowRestrictedEditButton.php#L44-L57
symbiote/silverstripe-advancedworkflow
src/Forms/gridfield/GridFieldWorkflowRestrictedEditButton.php
GridFieldWorkflowRestrictedEditButton.getColumnContent
public function getColumnContent($gridField, $record, $columnName) { $data = new ArrayData(array( 'Link' => Controller::join_links($gridField->Link('item'), $record->ID, 'edit') )); return $data->renderWith(GridFieldEditButton::class); }
php
public function getColumnContent($gridField, $record, $columnName) { $data = new ArrayData(array( 'Link' => Controller::join_links($gridField->Link('item'), $record->ID, 'edit') )); return $data->renderWith(GridFieldEditButton::class); }
[ "public", "function", "getColumnContent", "(", "$", "gridField", ",", "$", "record", ",", "$", "columnName", ")", "{", "$", "data", "=", "new", "ArrayData", "(", "array", "(", "'Link'", "=>", "Controller", "::", "join_links", "(", "$", "gridField", "->", ...
@param GridField $gridField @param DataObject $record @param string $columnName @return string - the HTML for the column
[ "@param", "GridField", "$gridField", "@param", "DataObject", "$record", "@param", "string", "$columnName" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Forms/gridfield/GridFieldWorkflowRestrictedEditButton.php#L91-L97
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.updateWorkflowFields
public function updateWorkflowFields($fields) { $fieldDiff = $this->Workflow()->getTargetDiff(); foreach ($fieldDiff as $field) { $display = ReadonlyField::create( 'workflow-' . $field->Name, $field->Title, DBField::create_field('HTMLText', $field->Diff) ) ->addExtraClass('workflow-field-diff'); $fields->push($display); } if ($this->BaseAction()->AllowCommenting) { $fields->push(new TextareaField('Comment', _t('WorkflowAction.COMMENT', 'Comment'))); } }
php
public function updateWorkflowFields($fields) { $fieldDiff = $this->Workflow()->getTargetDiff(); foreach ($fieldDiff as $field) { $display = ReadonlyField::create( 'workflow-' . $field->Name, $field->Title, DBField::create_field('HTMLText', $field->Diff) ) ->addExtraClass('workflow-field-diff'); $fields->push($display); } if ($this->BaseAction()->AllowCommenting) { $fields->push(new TextareaField('Comment', _t('WorkflowAction.COMMENT', 'Comment'))); } }
[ "public", "function", "updateWorkflowFields", "(", "$", "fields", ")", "{", "$", "fieldDiff", "=", "$", "this", "->", "Workflow", "(", ")", "->", "getTargetDiff", "(", ")", ";", "foreach", "(", "$", "fieldDiff", "as", "$", "field", ")", "{", "$", "disp...
Gets fields for when this is part of an active workflow
[ "Gets", "fields", "for", "when", "this", "is", "part", "of", "an", "active", "workflow" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L62-L79
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.getFrontEndDataObject
public function getFrontEndDataObject() { $obj = null; $ba = $this->BaseAction(); if ($ba->hasMethod('getFrontEndDataObject')) { $obj = $ba->getFrontEndDataObject(); } else { $obj = $this->Workflow()->getTarget(); } return $obj; }
php
public function getFrontEndDataObject() { $obj = null; $ba = $this->BaseAction(); if ($ba->hasMethod('getFrontEndDataObject')) { $obj = $ba->getFrontEndDataObject(); } else { $obj = $this->Workflow()->getTarget(); } return $obj; }
[ "public", "function", "getFrontEndDataObject", "(", ")", "{", "$", "obj", "=", "null", ";", "$", "ba", "=", "$", "this", "->", "BaseAction", "(", ")", ";", "if", "(", "$", "ba", "->", "hasMethod", "(", "'getFrontEndDataObject'", ")", ")", "{", "$", "...
Gets Front-End DataObject Use the DataObject as defined in the WorkflowAction, otherwise fall back to the context object. Useful for situations where front end workflow deals with multiple data objects @return DataObject
[ "Gets", "Front", "-", "End", "DataObject" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L104-L116
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.getValidTransitions
public function getValidTransitions() { $available = $this->BaseAction()->Transitions(); $valid = new ArrayList(); // iterate through the transitions and see if they're valid for the current state of the item being // workflowed if ($available) { foreach ($available as $transition) { if ($transition->isValid($this->Workflow())) { $valid->push($transition); } } } $this->extend('updateValidTransitions', $valid); return $valid; }
php
public function getValidTransitions() { $available = $this->BaseAction()->Transitions(); $valid = new ArrayList(); // iterate through the transitions and see if they're valid for the current state of the item being // workflowed if ($available) { foreach ($available as $transition) { if ($transition->isValid($this->Workflow())) { $valid->push($transition); } } } $this->extend('updateValidTransitions', $valid); return $valid; }
[ "public", "function", "getValidTransitions", "(", ")", "{", "$", "available", "=", "$", "this", "->", "BaseAction", "(", ")", "->", "Transitions", "(", ")", ";", "$", "valid", "=", "new", "ArrayList", "(", ")", ";", "// iterate through the transitions and see ...
Returns all the valid transitions that lead out from this action. This is called if this action has finished, and the workflow engine wants to run the next action. If this action returns only one valid transition it will be immediately followed; otherwise the user will decide which transition to follow. @return ArrayList
[ "Returns", "all", "the", "valid", "transitions", "that", "lead", "out", "from", "this", "action", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L184-L202
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.actionComplete
public function actionComplete(WorkflowTransition $transition) { $this->MemberID = Member::currentUserID(); $this->write(); $this->extend('onActionComplete', $transition); }
php
public function actionComplete(WorkflowTransition $transition) { $this->MemberID = Member::currentUserID(); $this->write(); $this->extend('onActionComplete', $transition); }
[ "public", "function", "actionComplete", "(", "WorkflowTransition", "$", "transition", ")", "{", "$", "this", "->", "MemberID", "=", "Member", "::", "currentUserID", "(", ")", ";", "$", "this", "->", "write", "(", ")", ";", "$", "this", "->", "extend", "(...
Called when this action has been completed within the workflow
[ "Called", "when", "this", "action", "has", "been", "completed", "within", "the", "workflow" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L215-L220
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.canEditTarget
public function canEditTarget(DataObject $target) { $absolute = $this->BaseAction()->canEditTarget($target); if (!is_null($absolute)) { return $absolute; } switch ($this->BaseAction()->AllowEditing) { case 'By Assignees': return $this->Workflow()->canEdit(); case 'No': return false; case 'Content Settings': default: return null; } }
php
public function canEditTarget(DataObject $target) { $absolute = $this->BaseAction()->canEditTarget($target); if (!is_null($absolute)) { return $absolute; } switch ($this->BaseAction()->AllowEditing) { case 'By Assignees': return $this->Workflow()->canEdit(); case 'No': return false; case 'Content Settings': default: return null; } }
[ "public", "function", "canEditTarget", "(", "DataObject", "$", "target", ")", "{", "$", "absolute", "=", "$", "this", "->", "BaseAction", "(", ")", "->", "canEditTarget", "(", "$", "target", ")", ";", "if", "(", "!", "is_null", "(", "$", "absolute", ")...
Can documents in the current workflow state be edited? @param DataObject $target @return bool
[ "Can", "documents", "in", "the", "current", "workflow", "state", "be", "edited?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L229-L244
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowActionInstance.php
WorkflowActionInstance.canPublishTarget
public function canPublishTarget(DataObject $target) { $absolute = $this->BaseAction()->canPublishTarget($target); if (!is_null($absolute)) { return $absolute; } return false; }
php
public function canPublishTarget(DataObject $target) { $absolute = $this->BaseAction()->canPublishTarget($target); if (!is_null($absolute)) { return $absolute; } return false; }
[ "public", "function", "canPublishTarget", "(", "DataObject", "$", "target", ")", "{", "$", "absolute", "=", "$", "this", "->", "BaseAction", "(", ")", "->", "canPublishTarget", "(", "$", "target", ")", ";", "if", "(", "!", "is_null", "(", "$", "absolute"...
Does this action restrict the publishing of a document? @param DataObject $target @return bool
[ "Does", "this", "action", "restrict", "the", "publishing", "of", "a", "document?" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowActionInstance.php#L263-L270
symbiote/silverstripe-advancedworkflow
src/Actions/NotifyUsersWorkflowAction.php
NotifyUsersWorkflowAction.getMemberFields
public function getMemberFields(Member $member = null) { if (!$member) { $member = Security::getCurrentUser(); } $result = array(); if ($member) { foreach ($member->summaryFields() as $field => $title) { $result[$field] = $member->$field; } } if ($member && !array_key_exists('Name', $result)) { $result['Name'] = $member->getName(); } return $result; }
php
public function getMemberFields(Member $member = null) { if (!$member) { $member = Security::getCurrentUser(); } $result = array(); if ($member) { foreach ($member->summaryFields() as $field => $title) { $result[$field] = $member->$field; } } if ($member && !array_key_exists('Name', $result)) { $result['Name'] = $member->getName(); } return $result; }
[ "public", "function", "getMemberFields", "(", "Member", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Security", "::", "getCurrentUser", "(", ")", ";", "}", "$", "result", "=", "array", "(", ")", ...
Builds an array with the member information @param Member $member An optional member to use. If null, will use the current logged in member @return array
[ "Builds", "an", "array", "with", "the", "member", "information" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Actions/NotifyUsersWorkflowAction.php#L210-L228
symbiote/silverstripe-advancedworkflow
src/Actions/NotifyUsersWorkflowAction.php
NotifyUsersWorkflowAction.getFormattingHelp
public function getFormattingHelp() { $note = _t( 'NotifyUsersWorkflowAction.FORMATTINGNOTE', 'Notification emails can contain HTML formatting. The following special variables are replaced with their respective values in the email subject, email from and template/body.' ); $member = _t( 'NotifyUsersWorkflowAction.MEMBERNOTE', 'These fields will be populated from the member that initiates the notification action. For example, {$Member.FirstName}.' ); $initiator = _t( 'NotifyUsersWorkflowAction.INITIATORNOTE', 'These fields will be populated from the member that initiates the workflow request. For example, {$Initiator.Email}.' ); $context = _t( 'NotifyUsersWorkflowAction.CONTEXTNOTE', 'Any summary fields from the workflow target will be available. For example, {$Context.Title}. Additionally, the {$Context.AbsoluteEditLink} variable will contain a link to edit the workflow target in the CMS (if it is a Page), and {$Context.AbsoluteLink} the frontend link. The {$Context.LinkToPendingItems} variable will generate a link to the CMS workflow admin, useful for allowing users to enact workflow transitions, directly from emails.' ); $fieldName = _t('NotifyUsersWorkflowAction.FIELDNAME', 'Field name'); $commentHistory = _t('NotifyUsersWorkflowAction.COMMENTHISTORY', 'Comment history up to this notification.'); $memberFields = implode(', ', array_keys($this->getMemberFields())); return "<p>$note</p> <p><strong>{\$Member.($memberFields)}</strong><br>$member</p> <p><strong>{\$Initiator.($memberFields)}</strong><br>$initiator</p> <p><strong>{\$Context.($fieldName)}</strong><br>$context</p> <p><strong>{\$CommentHistory}</strong><br>$commentHistory</p>"; }
php
public function getFormattingHelp() { $note = _t( 'NotifyUsersWorkflowAction.FORMATTINGNOTE', 'Notification emails can contain HTML formatting. The following special variables are replaced with their respective values in the email subject, email from and template/body.' ); $member = _t( 'NotifyUsersWorkflowAction.MEMBERNOTE', 'These fields will be populated from the member that initiates the notification action. For example, {$Member.FirstName}.' ); $initiator = _t( 'NotifyUsersWorkflowAction.INITIATORNOTE', 'These fields will be populated from the member that initiates the workflow request. For example, {$Initiator.Email}.' ); $context = _t( 'NotifyUsersWorkflowAction.CONTEXTNOTE', 'Any summary fields from the workflow target will be available. For example, {$Context.Title}. Additionally, the {$Context.AbsoluteEditLink} variable will contain a link to edit the workflow target in the CMS (if it is a Page), and {$Context.AbsoluteLink} the frontend link. The {$Context.LinkToPendingItems} variable will generate a link to the CMS workflow admin, useful for allowing users to enact workflow transitions, directly from emails.' ); $fieldName = _t('NotifyUsersWorkflowAction.FIELDNAME', 'Field name'); $commentHistory = _t('NotifyUsersWorkflowAction.COMMENTHISTORY', 'Comment history up to this notification.'); $memberFields = implode(', ', array_keys($this->getMemberFields())); return "<p>$note</p> <p><strong>{\$Member.($memberFields)}</strong><br>$member</p> <p><strong>{\$Initiator.($memberFields)}</strong><br>$initiator</p> <p><strong>{\$Context.($fieldName)}</strong><br>$context</p> <p><strong>{\$CommentHistory}</strong><br>$commentHistory</p>"; }
[ "public", "function", "getFormattingHelp", "(", ")", "{", "$", "note", "=", "_t", "(", "'NotifyUsersWorkflowAction.FORMATTINGNOTE'", ",", "'Notification emails can contain HTML formatting. The following special variables are replaced with their\n\t\t\trespective values in the email subject...
Returns a basic set of instructions on how email templates are populated with variables. @return string
[ "Returns", "a", "basic", "set", "of", "instructions", "on", "how", "email", "templates", "are", "populated", "with", "variables", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Actions/NotifyUsersWorkflowAction.php#L236-L271
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.AbsoluteEditLink
public function AbsoluteEditLink() { $CMSEditLink = null; if ($this->owner instanceof CMSPreviewable) { $CMSEditLink = $this->owner->CMSEditLink(); } elseif ($this->owner->hasMethod('WorkflowLink')) { $CMSEditLink = $this->owner->WorkflowLink(); } if ($CMSEditLink === null) { return null; } return Controller::join_links(Director::absoluteBaseURL(), $CMSEditLink); }
php
public function AbsoluteEditLink() { $CMSEditLink = null; if ($this->owner instanceof CMSPreviewable) { $CMSEditLink = $this->owner->CMSEditLink(); } elseif ($this->owner->hasMethod('WorkflowLink')) { $CMSEditLink = $this->owner->WorkflowLink(); } if ($CMSEditLink === null) { return null; } return Controller::join_links(Director::absoluteBaseURL(), $CMSEditLink); }
[ "public", "function", "AbsoluteEditLink", "(", ")", "{", "$", "CMSEditLink", "=", "null", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "CMSPreviewable", ")", "{", "$", "CMSEditLink", "=", "$", "this", "->", "owner", "->", "CMSEditLink", "(", ...
Included in CMS-generated email templates for a NotifyUsersWorkflowAction. Returns an absolute link to the CMS UI for a Page object @return string|null
[ "Included", "in", "CMS", "-", "generated", "email", "templates", "for", "a", "NotifyUsersWorkflowAction", ".", "Returns", "an", "absolute", "link", "to", "the", "CMS", "UI", "for", "a", "Page", "object" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L287-L302
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.LinkToPendingItems
public function LinkToPendingItems() { $urlBase = Director::absoluteBaseURL(); $urlFrag = 'admin/workflows/WorkflowDefinition/EditForm/field'; $urlInst = $this->getWorkflowInstance(); return Controller::join_links($urlBase, $urlFrag, 'PendingObjects', 'item', $urlInst->ID, 'edit'); }
php
public function LinkToPendingItems() { $urlBase = Director::absoluteBaseURL(); $urlFrag = 'admin/workflows/WorkflowDefinition/EditForm/field'; $urlInst = $this->getWorkflowInstance(); return Controller::join_links($urlBase, $urlFrag, 'PendingObjects', 'item', $urlInst->ID, 'edit'); }
[ "public", "function", "LinkToPendingItems", "(", ")", "{", "$", "urlBase", "=", "Director", "::", "absoluteBaseURL", "(", ")", ";", "$", "urlFrag", "=", "'admin/workflows/WorkflowDefinition/EditForm/field'", ";", "$", "urlInst", "=", "$", "this", "->", "getWorkflo...
Included in CMS-generated email templates for a NotifyUsersWorkflowAction. Allows users to select a link in an email for direct access to the transition-selection dropdown in the CMS UI. @return string
[ "Included", "in", "CMS", "-", "generated", "email", "templates", "for", "a", "NotifyUsersWorkflowAction", ".", "Allows", "users", "to", "select", "a", "link", "in", "an", "email", "for", "direct", "access", "to", "the", "transition", "-", "selection", "dropdow...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L310-L316
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.onAfterWrite
public function onAfterWrite() { $instance = $this->getWorkflowInstance(); if ($instance && $instance->CurrentActionID) { $action = $instance->CurrentAction()->BaseAction()->targetUpdated($instance); } }
php
public function onAfterWrite() { $instance = $this->getWorkflowInstance(); if ($instance && $instance->CurrentActionID) { $action = $instance->CurrentAction()->BaseAction()->targetUpdated($instance); } }
[ "public", "function", "onAfterWrite", "(", ")", "{", "$", "instance", "=", "$", "this", "->", "getWorkflowInstance", "(", ")", ";", "if", "(", "$", "instance", "&&", "$", "instance", "->", "CurrentActionID", ")", "{", "$", "action", "=", "$", "instance",...
After a workflow item is written, we notify the workflow so that it can take action if needbe
[ "After", "a", "workflow", "item", "is", "written", "we", "notify", "the", "workflow", "so", "that", "it", "can", "take", "action", "if", "needbe" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L322-L328
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.getWorkflowInstance
public function getWorkflowInstance() { if (!$this->currentInstance) { $this->currentInstance = $this->getWorkflowService()->getWorkflowFor($this->owner); } return $this->currentInstance; }
php
public function getWorkflowInstance() { if (!$this->currentInstance) { $this->currentInstance = $this->getWorkflowService()->getWorkflowFor($this->owner); } return $this->currentInstance; }
[ "public", "function", "getWorkflowInstance", "(", ")", "{", "if", "(", "!", "$", "this", "->", "currentInstance", ")", "{", "$", "this", "->", "currentInstance", "=", "$", "this", "->", "getWorkflowService", "(", ")", "->", "getWorkflowFor", "(", "$", "thi...
Gets the current instance of workflow @return WorkflowInstance
[ "Gets", "the", "current", "instance", "of", "workflow" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L343-L350
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.RecentWorkflowComment
public function RecentWorkflowComment($limit = 10) { if ($actions = $this->getWorkflowHistory($limit)) { foreach ($actions as $action) { if ($action->Comment != '') { return $action; } } } }
php
public function RecentWorkflowComment($limit = 10) { if ($actions = $this->getWorkflowHistory($limit)) { foreach ($actions as $action) { if ($action->Comment != '') { return $action; } } } }
[ "public", "function", "RecentWorkflowComment", "(", "$", "limit", "=", "10", ")", "{", "if", "(", "$", "actions", "=", "$", "this", "->", "getWorkflowHistory", "(", "$", "limit", ")", ")", "{", "foreach", "(", "$", "actions", "as", "$", "action", ")", ...
Check all recent WorkflowActionIntances and return the most recent one with a Comment @param int $limit @return WorkflowActionInstance|null
[ "Check", "all", "recent", "WorkflowActionIntances", "and", "return", "the", "most", "recent", "one", "with", "a", "Comment" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L369-L378
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.canPublish
public function canPublish() { // Override any default behaviour, to allow queuedjobs to complete if ($this->isPublishJobRunning()) { return true; } if ($active = $this->getWorkflowInstance()) { $publish = $active->canPublishTarget($this->owner); if (!is_null($publish)) { return $publish; } } // use definition to determine if publishing directly is allowed $definition = $this->getWorkflowService()->getDefinitionFor($this->owner); if ($definition) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); $canPublish = $definition->canWorkflowPublish($member, $this->owner); return $canPublish; } }
php
public function canPublish() { // Override any default behaviour, to allow queuedjobs to complete if ($this->isPublishJobRunning()) { return true; } if ($active = $this->getWorkflowInstance()) { $publish = $active->canPublishTarget($this->owner); if (!is_null($publish)) { return $publish; } } // use definition to determine if publishing directly is allowed $definition = $this->getWorkflowService()->getDefinitionFor($this->owner); if ($definition) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); $canPublish = $definition->canWorkflowPublish($member, $this->owner); return $canPublish; } }
[ "public", "function", "canPublish", "(", ")", "{", "// Override any default behaviour, to allow queuedjobs to complete", "if", "(", "$", "this", "->", "isPublishJobRunning", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "active", "=", "$", "thi...
Content can never be directly publishable if there's a workflow applied. If there's an active instance, then it 'might' be publishable
[ "Content", "can", "never", "be", "directly", "publishable", "if", "there", "s", "a", "workflow", "applied", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L385-L412
symbiote/silverstripe-advancedworkflow
src/Extensions/WorkflowApplicable.php
WorkflowApplicable.canEdit
public function canEdit($member) { // Override any default behaviour, to allow queuedjobs to complete if ($this->isPublishJobRunning()) { return true; } if ($active = $this->getWorkflowInstance()) { return $active->canEditTarget(); } }
php
public function canEdit($member) { // Override any default behaviour, to allow queuedjobs to complete if ($this->isPublishJobRunning()) { return true; } if ($active = $this->getWorkflowInstance()) { return $active->canEditTarget(); } }
[ "public", "function", "canEdit", "(", "$", "member", ")", "{", "// Override any default behaviour, to allow queuedjobs to complete", "if", "(", "$", "this", "->", "isPublishJobRunning", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "active", "=...
Can only edit content that's NOT in another person's content changeset @return bool
[ "Can", "only", "edit", "content", "that", "s", "NOT", "in", "another", "person", "s", "content", "changeset" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Extensions/WorkflowApplicable.php#L419-L429
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionImporter.php
WorkflowDefinitionImporter.getImportedWorkflows
public function getImportedWorkflows($name = null) { $imports = DataObject::get(ImportedWorkflowTemplate::class); $importedDefs = array(); foreach ($imports as $import) { if (!$import->Content) { continue; } $structure = unserialize($import->Content); $struct = $structure[Injector::class]['ExportedWorkflow']; $template = Injector::inst()->createWithArgs(WorkflowTemplate::class, $struct['constructor']); $template->setStructure($struct['properties']['structure']); if ($name) { if ($struct['constructor'][0] == trim($name)) { return $template; } continue; } $importedDefs[] = $template; } return $importedDefs; }
php
public function getImportedWorkflows($name = null) { $imports = DataObject::get(ImportedWorkflowTemplate::class); $importedDefs = array(); foreach ($imports as $import) { if (!$import->Content) { continue; } $structure = unserialize($import->Content); $struct = $structure[Injector::class]['ExportedWorkflow']; $template = Injector::inst()->createWithArgs(WorkflowTemplate::class, $struct['constructor']); $template->setStructure($struct['properties']['structure']); if ($name) { if ($struct['constructor'][0] == trim($name)) { return $template; } continue; } $importedDefs[] = $template; } return $importedDefs; }
[ "public", "function", "getImportedWorkflows", "(", "$", "name", "=", "null", ")", "{", "$", "imports", "=", "DataObject", "::", "get", "(", "ImportedWorkflowTemplate", "::", "class", ")", ";", "$", "importedDefs", "=", "array", "(", ")", ";", "foreach", "(...
Generates an array of WorkflowTemplate Objects of all uploaded workflows. @param string $name. If set, a single-value array comprising a WorkflowTemplate object who's first constructor param matches $name is returned. @return WorkflowTemplate|WorkflowTemplate[]
[ "Generates", "an", "array", "of", "WorkflowTemplate", "Objects", "of", "all", "uploaded", "workflows", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionImporter.php#L29-L50
symbiote/silverstripe-advancedworkflow
src/Admin/WorkflowDefinitionImporter.php
WorkflowDefinitionImporter.parseYAMLImport
public function parseYAMLImport($source) { if (is_file($source)) { $source = file_get_contents($source); } // Make sure the linefeeds are all converted to \n, PCRE '$' will not match anything else. $convertLF = str_replace(array("\r\n", "\r"), "\n", $source); /* * Remove illegal colons from Transition/Action titles, otherwise sfYamlParser will barf on them * Note: The regex relies on there being single quotes wrapped around these in the export .ss template */ $converted = preg_replace("#('[^:\n][^']+)(:)([^']+')#", "$1;$3", $convertLF); $parts = preg_split('#^---$#m', $converted, -1, PREG_SPLIT_NO_EMPTY); // If we got an odd number of parts the config, file doesn't have a header. // We know in advance the number of blocks imported content will have so we settle for a count()==2 check. if (count($parts) != 2) { $msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_HEADER', 'Invalid YAML format.'); throw new ValidationException($msg); } try { $parsed = Yaml::parse($parts[1]); return $parsed; } catch (Exception $e) { $msg = _t( 'WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_PARSE', 'Invalid YAML format. Unable to parse.' ); throw new ValidationException($msg); } }
php
public function parseYAMLImport($source) { if (is_file($source)) { $source = file_get_contents($source); } // Make sure the linefeeds are all converted to \n, PCRE '$' will not match anything else. $convertLF = str_replace(array("\r\n", "\r"), "\n", $source); /* * Remove illegal colons from Transition/Action titles, otherwise sfYamlParser will barf on them * Note: The regex relies on there being single quotes wrapped around these in the export .ss template */ $converted = preg_replace("#('[^:\n][^']+)(:)([^']+')#", "$1;$3", $convertLF); $parts = preg_split('#^---$#m', $converted, -1, PREG_SPLIT_NO_EMPTY); // If we got an odd number of parts the config, file doesn't have a header. // We know in advance the number of blocks imported content will have so we settle for a count()==2 check. if (count($parts) != 2) { $msg = _t('WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_HEADER', 'Invalid YAML format.'); throw new ValidationException($msg); } try { $parsed = Yaml::parse($parts[1]); return $parsed; } catch (Exception $e) { $msg = _t( 'WorkflowDefinitionImporter.INVALID_YML_FORMAT_NO_PARSE', 'Invalid YAML format. Unable to parse.' ); throw new ValidationException($msg); } }
[ "public", "function", "parseYAMLImport", "(", "$", "source", ")", "{", "if", "(", "is_file", "(", "$", "source", ")", ")", "{", "$", "source", "=", "file_get_contents", "(", "$", "source", ")", ";", "}", "// Make sure the linefeeds are all converted to \\n, PCRE...
Handles finding and parsing YAML input as a string or from the contents of a file. @see addYAMLConfigFile() on {@link SS_ConfigManifest} from where this logic was taken and adapted. @param string $source YAML as a string or a filename @return array
[ "Handles", "finding", "and", "parsing", "YAML", "input", "as", "a", "string", "or", "from", "the", "contents", "of", "a", "file", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Admin/WorkflowDefinitionImporter.php#L59-L91
symbiote/silverstripe-advancedworkflow
src/Dev/WorkflowBulkLoader.php
WorkflowBulkLoader.createImport
protected function createImport($name, $filename, $record) { // This is needed to feed WorkflowService#getNamedTemplate() $import = ImportedWorkflowTemplate::create(); $import->Name = $name; $import->Filename = $filename; $import->Content = serialize($record); $import->write(); return $import; }
php
protected function createImport($name, $filename, $record) { // This is needed to feed WorkflowService#getNamedTemplate() $import = ImportedWorkflowTemplate::create(); $import->Name = $name; $import->Filename = $filename; $import->Content = serialize($record); $import->write(); return $import; }
[ "protected", "function", "createImport", "(", "$", "name", ",", "$", "filename", ",", "$", "record", ")", "{", "// This is needed to feed WorkflowService#getNamedTemplate()", "$", "import", "=", "ImportedWorkflowTemplate", "::", "create", "(", ")", ";", "$", "import...
Create the ImportedWorkflowTemplate record for the uploaded YML file. @param string $name @param string $filename @param array $record @return ImportedWorkflowTemplate $import
[ "Create", "the", "ImportedWorkflowTemplate", "record", "for", "the", "uploaded", "YML", "file", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/Dev/WorkflowBulkLoader.php#L97-L107
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.onBeforeWrite
public function onBeforeWrite() { if (!$this->Sort) { $this->Sort = DB::query('SELECT MAX("Sort") + 1 FROM "WorkflowDefinition"')->value(); } if (!$this->ID && !$this->Title) { $this->Title = $this->getDefaultWorkflowTitle(); } parent::onBeforeWrite(); }
php
public function onBeforeWrite() { if (!$this->Sort) { $this->Sort = DB::query('SELECT MAX("Sort") + 1 FROM "WorkflowDefinition"')->value(); } if (!$this->ID && !$this->Title) { $this->Title = $this->getDefaultWorkflowTitle(); } parent::onBeforeWrite(); }
[ "public", "function", "onBeforeWrite", "(", ")", "{", "if", "(", "!", "$", "this", "->", "Sort", ")", "{", "$", "this", "->", "Sort", "=", "DB", "::", "query", "(", "'SELECT MAX(\"Sort\") + 1 FROM \"WorkflowDefinition\"'", ")", "->", "value", "(", ")", ";"...
Ensure a sort value is set and we get a useable initial workflow title.
[ "Ensure", "a", "sort", "value", "is", "set", "and", "we", "get", "a", "useable", "initial", "workflow", "title", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L117-L127
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.onAfterWrite
public function onAfterWrite() { parent::onAfterWrite(); // Request via ImportForm where TemplateVersion is already set, so unset it $posted = Controller::curr()->getRequest()->postVars(); if (isset($posted['_CsvFile']) && $this->TemplateVersion) { $this->TemplateVersion = null; } if ($this->numChildren() == 0 && $this->Template && !$this->TemplateVersion) { $this->getWorkflowService()->defineFromTemplate($this, $this->Template); } }
php
public function onAfterWrite() { parent::onAfterWrite(); // Request via ImportForm where TemplateVersion is already set, so unset it $posted = Controller::curr()->getRequest()->postVars(); if (isset($posted['_CsvFile']) && $this->TemplateVersion) { $this->TemplateVersion = null; } if ($this->numChildren() == 0 && $this->Template && !$this->TemplateVersion) { $this->getWorkflowService()->defineFromTemplate($this, $this->Template); } }
[ "public", "function", "onAfterWrite", "(", ")", "{", "parent", "::", "onAfterWrite", "(", ")", ";", "// Request via ImportForm where TemplateVersion is already set, so unset it", "$", "posted", "=", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", ...
After we've been written, check whether we've got a template and to then create the relevant actions etc.
[ "After", "we", "ve", "been", "written", "check", "whether", "we", "ve", "got", "a", "template", "and", "to", "then", "create", "the", "relevant", "actions", "etc", "." ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L133-L145
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.removeRelatedHasLists
private function removeRelatedHasLists() { $this->Users()->removeAll(); $this->Groups()->removeAll(); $this->Actions()->each(function ($action) { if ($orphan = DataObject::get_by_id(WorkflowAction::class, $action->ID)) { $orphan->delete(); } }); }
php
private function removeRelatedHasLists() { $this->Users()->removeAll(); $this->Groups()->removeAll(); $this->Actions()->each(function ($action) { if ($orphan = DataObject::get_by_id(WorkflowAction::class, $action->ID)) { $orphan->delete(); } }); }
[ "private", "function", "removeRelatedHasLists", "(", ")", "{", "$", "this", "->", "Users", "(", ")", "->", "removeAll", "(", ")", ";", "$", "this", "->", "Groups", "(", ")", "->", "removeAll", "(", ")", ";", "$", "this", "->", "Actions", "(", ")", ...
Removes User+Group relations from this object as well as WorkflowAction relations. When a WorkflowAction is deleted, its own relations are also removed: - WorkflowInstance - WorkflowTransition @see WorkflowAction::onAfterDelete() @return void
[ "Removes", "User", "+", "Group", "relations", "from", "this", "object", "as", "well", "as", "WorkflowAction", "relations", ".", "When", "a", "WorkflowAction", "is", "deleted", "its", "own", "relations", "are", "also", "removed", ":", "-", "WorkflowInstance", "...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L174-L183
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.getDefaultWorkflowTitle
public function getDefaultWorkflowTitle() { // Where is the title coming from that we wish to test? $incomingTitle = $this->incomingTitle(); $defs = WorkflowDefinition::get()->map()->toArray(); $tmp = []; foreach ($defs as $def) { $parts = preg_split("#\s#", $def, -1, PREG_SPLIT_NO_EMPTY); $lastPart = array_pop($parts); $match = implode(' ', $parts); // @todo do all this in one preg_match_all() call if (preg_match("#$match#", $incomingTitle)) { // @todo use a simple incrementer?? if ($incomingTitle.' '.$lastPart == $def) { array_push($tmp, $lastPart); } } } $incr = 1; if (count($tmp)) { sort($tmp, SORT_NUMERIC); $incr = (int)end($tmp)+1; } return $incomingTitle.' '.$incr; }
php
public function getDefaultWorkflowTitle() { // Where is the title coming from that we wish to test? $incomingTitle = $this->incomingTitle(); $defs = WorkflowDefinition::get()->map()->toArray(); $tmp = []; foreach ($defs as $def) { $parts = preg_split("#\s#", $def, -1, PREG_SPLIT_NO_EMPTY); $lastPart = array_pop($parts); $match = implode(' ', $parts); // @todo do all this in one preg_match_all() call if (preg_match("#$match#", $incomingTitle)) { // @todo use a simple incrementer?? if ($incomingTitle.' '.$lastPart == $def) { array_push($tmp, $lastPart); } } } $incr = 1; if (count($tmp)) { sort($tmp, SORT_NUMERIC); $incr = (int)end($tmp)+1; } return $incomingTitle.' '.$incr; }
[ "public", "function", "getDefaultWorkflowTitle", "(", ")", "{", "// Where is the title coming from that we wish to test?", "$", "incomingTitle", "=", "$", "this", "->", "incomingTitle", "(", ")", ";", "$", "defs", "=", "WorkflowDefinition", "::", "get", "(", ")", "-...
If a workflow-title doesn't already exist, we automatically create a suitable default title when users attempt to create title-less workflow definitions or upload/create Workflows that would otherwise have the same name. @return string @todo Filter query on current-user's workflows. Avoids confusion when other users may already have 'My Workflow 1' and user sees 'My Workflow 2'
[ "If", "a", "workflow", "-", "title", "doesn", "t", "already", "exist", "we", "automatically", "create", "a", "suitable", "default", "title", "when", "users", "attempt", "to", "create", "title", "-", "less", "workflow", "definitions", "or", "upload", "/", "cr...
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L425-L451
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.incomingTitle
public function incomingTitle() { $req = Controller::curr()->getRequest(); if (isset($req['_CsvFile']['name']) && !empty($req['_CsvFile']['name'])) { $import = ImportedWorkflowTemplate::get()->filter('Filename', $req['_CsvFile']['name'])->first(); $incomingTitle = $import->Name; } elseif (isset($req['Template']) && !empty($req['Template'])) { $incomingTitle = $req['Template']; } elseif (isset($req['Title']) && !empty($req['Title'])) { $incomingTitle = $req['Title']; } else { $incomingTitle = self::$default_workflow_title_base; } return $incomingTitle; }
php
public function incomingTitle() { $req = Controller::curr()->getRequest(); if (isset($req['_CsvFile']['name']) && !empty($req['_CsvFile']['name'])) { $import = ImportedWorkflowTemplate::get()->filter('Filename', $req['_CsvFile']['name'])->first(); $incomingTitle = $import->Name; } elseif (isset($req['Template']) && !empty($req['Template'])) { $incomingTitle = $req['Template']; } elseif (isset($req['Title']) && !empty($req['Title'])) { $incomingTitle = $req['Title']; } else { $incomingTitle = self::$default_workflow_title_base; } return $incomingTitle; }
[ "public", "function", "incomingTitle", "(", ")", "{", "$", "req", "=", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", ";", "if", "(", "isset", "(", "$", "req", "[", "'_CsvFile'", "]", "[", "'name'", "]", ")", "&&", "!", "empty"...
Return the workflow definition title according to the source @return string
[ "Return", "the", "workflow", "definition", "title", "according", "to", "the", "source" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L458-L472
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.canWorkflowPublish
public function canWorkflowPublish($member, $target) { $publish = $this->extendedCan('canWorkflowPublish', $member, $target); if (is_null($publish)) { $publish = Permission::checkMember($member, 'ADMIN'); } return $publish; }
php
public function canWorkflowPublish($member, $target) { $publish = $this->extendedCan('canWorkflowPublish', $member, $target); if (is_null($publish)) { $publish = Permission::checkMember($member, 'ADMIN'); } return $publish; }
[ "public", "function", "canWorkflowPublish", "(", "$", "member", ",", "$", "target", ")", "{", "$", "publish", "=", "$", "this", "->", "extendedCan", "(", "'canWorkflowPublish'", ",", "$", "member", ",", "$", "target", ")", ";", "if", "(", "is_null", "(",...
Determines if target can be published directly when no workflow has started yet Opens extension hook to allow an extension to determine if this is allowed as well By default returns false @param $member @param $target @return Boolean
[ "Determines", "if", "target", "can", "be", "published", "directly", "when", "no", "workflow", "has", "started", "yet", "Opens", "extension", "hook", "to", "allow", "an", "extension", "to", "determine", "if", "this", "is", "allowed", "as", "well" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L484-L491
symbiote/silverstripe-advancedworkflow
src/DataObjects/WorkflowDefinition.php
WorkflowDefinition.userHasAccess
protected function userHasAccess($member) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "VIEW_ACTIVE_WORKFLOWS")) { return true; } }
php
protected function userHasAccess($member) { if (!$member) { if (!Security::getCurrentUser()) { return false; } $member = Security::getCurrentUser(); } if (Permission::checkMember($member, "VIEW_ACTIVE_WORKFLOWS")) { return true; } }
[ "protected", "function", "userHasAccess", "(", "$", "member", ")", "{", "if", "(", "!", "$", "member", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "false", ";", "}", "$", "member", "=", "Security", "::"...
Checks whether the passed user is able to view this ModelAdmin @param Member $member @return bool
[ "Checks", "whether", "the", "passed", "user", "is", "able", "to", "view", "this", "ModelAdmin" ]
train
https://github.com/symbiote/silverstripe-advancedworkflow/blob/a71f7ca1a04cd03597fafda3ad052413f259f967/src/DataObjects/WorkflowDefinition.php#L563-L575
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.createDriver
protected function createDriver($name) { $config = Arr::get($this->app['config']['hashid.connections'], $name, []); return $this->createForConnection($name, $config) ?: $this->createForDriver(Arr::pull($config, 'driver', $name), $config); }
php
protected function createDriver($name) { $config = Arr::get($this->app['config']['hashid.connections'], $name, []); return $this->createForConnection($name, $config) ?: $this->createForDriver(Arr::pull($config, 'driver', $name), $config); }
[ "protected", "function", "createDriver", "(", "$", "name", ")", "{", "$", "config", "=", "Arr", "::", "get", "(", "$", "this", "->", "app", "[", "'config'", "]", "[", "'hashid.connections'", "]", ",", "$", "name", ",", "[", "]", ")", ";", "return", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L66-L72
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.createForConnection
protected function createForConnection($name, array $config = []) { if (isset($this->customCreators[$name])) { return $this->callCustom($name, compact('config')); } }
php
protected function createForConnection($name, array $config = []) { if (isset($this->customCreators[$name])) { return $this->callCustom($name, compact('config')); } }
[ "protected", "function", "createForConnection", "(", "$", "name", ",", "array", "$", "config", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "customCreators", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", ...
Create a new driver instance for the given connection. @param string $name @param array $config @return mixed
[ "Create", "a", "new", "driver", "instance", "for", "the", "given", "connection", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L81-L86
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.createForDriver
protected function createForDriver($driver, array $config = []) { if (isset($this->customCreators[$driver])) { return $this->callCustom($driver, compact('config')); } if ($binding = $this->getBindingKeyForDriver($driver)) { return $this->resolveBinding($binding, compact('config')); } throw new InvalidArgumentException("Unsupported driver [$driver]"); }
php
protected function createForDriver($driver, array $config = []) { if (isset($this->customCreators[$driver])) { return $this->callCustom($driver, compact('config')); } if ($binding = $this->getBindingKeyForDriver($driver)) { return $this->resolveBinding($binding, compact('config')); } throw new InvalidArgumentException("Unsupported driver [$driver]"); }
[ "protected", "function", "createForDriver", "(", "$", "driver", ",", "array", "$", "config", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "customCreators", "[", "$", "driver", "]", ")", ")", "{", "return", "$", "this", "->", ...
Create a new driver instance for the given driver. We will check to see if a creator method exists for the given driver, and will call the Closure if so, which allows us to have a more generic resolver for the drivers themselves which applies to all connections. @param string $driver @param array $config @return mixed @throws \InvalidArgumentException
[ "Create", "a", "new", "driver", "instance", "for", "the", "given", "driver", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L101-L112
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.callCustom
protected function callCustom($key, array $parameters = []) { return $this->app->call($this->customCreators[$key], $parameters); }
php
protected function callCustom($key, array $parameters = []) { return $this->app->call($this->customCreators[$key], $parameters); }
[ "protected", "function", "callCustom", "(", "$", "key", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "return", "$", "this", "->", "app", "->", "call", "(", "$", "this", "->", "customCreators", "[", "$", "key", "]", ",", "$", "parameters"...
Call a custom creator. @param string $key @param array $parameters @return mixed
[ "Call", "a", "custom", "creator", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L121-L124
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.getBindingKeyForDriver
protected function getBindingKeyForDriver($driver) { if (class_exists($driver)) { return $driver; } if ($this->app->bound($key = "hashid.driver.$driver")) { return $key; } }
php
protected function getBindingKeyForDriver($driver) { if (class_exists($driver)) { return $driver; } if ($this->app->bound($key = "hashid.driver.$driver")) { return $key; } }
[ "protected", "function", "getBindingKeyForDriver", "(", "$", "driver", ")", "{", "if", "(", "class_exists", "(", "$", "driver", ")", ")", "{", "return", "$", "driver", ";", "}", "if", "(", "$", "this", "->", "app", "->", "bound", "(", "$", "key", "="...
Get the binding key for the driver. @param string $driver @return string|null
[ "Get", "the", "binding", "key", "for", "the", "driver", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L132-L141
ElfSundae/laravel-hashid
src/HashidManager.php
HashidManager.resolveBinding
protected function resolveBinding($key, array $parameters = []) { if ($this->app->isShared($key)) { return $this->app->make($key); } $makeWith = method_exists($this->app, 'makeWith') ? 'makeWith' : 'make'; return $this->app->$makeWith($key, $parameters); }
php
protected function resolveBinding($key, array $parameters = []) { if ($this->app->isShared($key)) { return $this->app->make($key); } $makeWith = method_exists($this->app, 'makeWith') ? 'makeWith' : 'make'; return $this->app->$makeWith($key, $parameters); }
[ "protected", "function", "resolveBinding", "(", "$", "key", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "app", "->", "isShared", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "app", "->", ...
Resolve the given binding from the container. NOTE: `Container::make($abstract, $parameters)` which can pass additional parameters to the constructor was removed in Laravel 5.4 (https://github.com/laravel/internals/issues/391), but then re-added as `makeWith()` in v5.4.16 (https://github.com/laravel/framework/pull/18271). And in L55 the `makeWith()` is just an alias to `make()`. @param string $key @param array $parameters @return mixed
[ "Resolve", "the", "given", "binding", "from", "the", "container", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidManager.php#L157-L166
ElfSundae/laravel-hashid
src/Base64IntegerDriver.php
Base64IntegerDriver.decode
public function decode($data) { $int = (int) ($decoded = parent::decode($data)); return (string) $int === $decoded ? $int : 0; }
php
public function decode($data) { $int = (int) ($decoded = parent::decode($data)); return (string) $int === $decoded ? $int : 0; }
[ "public", "function", "decode", "(", "$", "data", ")", "{", "$", "int", "=", "(", "int", ")", "(", "$", "decoded", "=", "parent", "::", "decode", "(", "$", "data", ")", ")", ";", "return", "(", "string", ")", "$", "int", "===", "$", "decoded", ...
Decode the data. @param mixed $data @return int
[ "Decode", "the", "data", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/Base64IntegerDriver.php#L13-L18
ElfSundae/laravel-hashid
src/Console/OptimusGenerateCommand.php
OptimusGenerateCommand.handle
public function handle() { $numbers = $this->generateOptimusNumbers( $this->getTimes(), (int) $this->option('prime') ); $this->table(['prime', 'inverse', 'random'], $numbers); }
php
public function handle() { $numbers = $this->generateOptimusNumbers( $this->getTimes(), (int) $this->option('prime') ); $this->table(['prime', 'inverse', 'random'], $numbers); }
[ "public", "function", "handle", "(", ")", "{", "$", "numbers", "=", "$", "this", "->", "generateOptimusNumbers", "(", "$", "this", "->", "getTimes", "(", ")", ",", "(", "int", ")", "$", "this", "->", "option", "(", "'prime'", ")", ")", ";", "$", "t...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/Console/OptimusGenerateCommand.php#L30-L38
ElfSundae/laravel-hashid
src/Console/OptimusGenerateCommand.php
OptimusGenerateCommand.generateOptimusNumbers
protected function generateOptimusNumbers($times = 1, $prime = null) { $prime = $prime ?: null; $result = []; for ($i = 0; $i < $times; $i++) { $result[] = Energon::generate($prime); } return $result; }
php
protected function generateOptimusNumbers($times = 1, $prime = null) { $prime = $prime ?: null; $result = []; for ($i = 0; $i < $times; $i++) { $result[] = Energon::generate($prime); } return $result; }
[ "protected", "function", "generateOptimusNumbers", "(", "$", "times", "=", "1", ",", "$", "prime", "=", "null", ")", "{", "$", "prime", "=", "$", "prime", "?", ":", "null", ";", "$", "result", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ...
Generate Optimus numbers. @param int $times @param int $prime @return array
[ "Generate", "Optimus", "numbers", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/Console/OptimusGenerateCommand.php#L57-L67
ElfSundae/laravel-hashid
src/HashidsIntegerDriver.php
HashidsIntegerDriver.decode
public function decode($data) { $decoded = parent::decode($data); return 1 === count($decoded) ? reset($decoded) : 0; }
php
public function decode($data) { $decoded = parent::decode($data); return 1 === count($decoded) ? reset($decoded) : 0; }
[ "public", "function", "decode", "(", "$", "data", ")", "{", "$", "decoded", "=", "parent", "::", "decode", "(", "$", "data", ")", ";", "return", "1", "===", "count", "(", "$", "decoded", ")", "?", "reset", "(", "$", "decoded", ")", ":", "0", ";",...
Decode the data. @param mixed $data @return int
[ "Decode", "the", "data", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidsIntegerDriver.php#L13-L18
ElfSundae/laravel-hashid
src/Console/AlphabetGenerateCommand.php
AlphabetGenerateCommand.handle
public function handle() { $alphabets = $this->generateRandomAlphabets( $this->getTimes(), (string) $this->option('characters') ); $this->comment(implode(PHP_EOL, $alphabets)); }
php
public function handle() { $alphabets = $this->generateRandomAlphabets( $this->getTimes(), (string) $this->option('characters') ); $this->comment(implode(PHP_EOL, $alphabets)); }
[ "public", "function", "handle", "(", ")", "{", "$", "alphabets", "=", "$", "this", "->", "generateRandomAlphabets", "(", "$", "this", "->", "getTimes", "(", ")", ",", "(", "string", ")", "$", "this", "->", "option", "(", "'characters'", ")", ")", ";", ...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/Console/AlphabetGenerateCommand.php#L36-L44
ElfSundae/laravel-hashid
src/Console/AlphabetGenerateCommand.php
AlphabetGenerateCommand.generateRandomAlphabets
protected function generateRandomAlphabets($times = 1, $characters = null) { $characters = $characters ?: $this->defaultCharacters; $result = []; for ($i = 0; $i < $times; $i++) { $result[] = str_shuffle(count_chars($characters, 3)); } return $result; }
php
protected function generateRandomAlphabets($times = 1, $characters = null) { $characters = $characters ?: $this->defaultCharacters; $result = []; for ($i = 0; $i < $times; $i++) { $result[] = str_shuffle(count_chars($characters, 3)); } return $result; }
[ "protected", "function", "generateRandomAlphabets", "(", "$", "times", "=", "1", ",", "$", "characters", "=", "null", ")", "{", "$", "characters", "=", "$", "characters", "?", ":", "$", "this", "->", "defaultCharacters", ";", "$", "result", "=", "[", "]"...
Generate random alphabets. @param int $times @param string $characters @return array
[ "Generate", "random", "alphabets", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/Console/AlphabetGenerateCommand.php#L63-L73
ElfSundae/laravel-hashid
src/HashidServiceProvider.php
HashidServiceProvider.setupAssets
protected function setupAssets() { if ($this->app instanceof LumenApplication) { $this->app->configure('hashid'); // @codeCoverageIgnore } $this->mergeConfigFrom($config = __DIR__.'/../config/hashid.php', 'hashid'); if ($this->app->runningInConsole()) { $this->publishes([$config => base_path('config/hashid.php')], 'hashid'); } }
php
protected function setupAssets() { if ($this->app instanceof LumenApplication) { $this->app->configure('hashid'); // @codeCoverageIgnore } $this->mergeConfigFrom($config = __DIR__.'/../config/hashid.php', 'hashid'); if ($this->app->runningInConsole()) { $this->publishes([$config => base_path('config/hashid.php')], 'hashid'); } }
[ "protected", "function", "setupAssets", "(", ")", "{", "if", "(", "$", "this", "->", "app", "instanceof", "LumenApplication", ")", "{", "$", "this", "->", "app", "->", "configure", "(", "'hashid'", ")", ";", "// @codeCoverageIgnore", "}", "$", "this", "->"...
Setup package assets. @return void
[ "Setup", "package", "assets", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidServiceProvider.php#L29-L40
ElfSundae/laravel-hashid
src/HashidServiceProvider.php
HashidServiceProvider.registerServices
protected function registerServices() { $this->app->singleton('hashid', function ($app) { return new HashidManager($app); }); $this->app->alias('hashid', HashidManager::class); foreach ($this->getSingletonDrivers() as $class) { $this->app->singleton( $key = $this->getBindingKeyForDriver($class), function () use ($class) { return new $class; } ); $this->app->alias($key, $class); } foreach ($this->getNonSingletonDrivers() as $class) { $this->app->bind($this->getBindingKeyForDriver($class), $class); } }
php
protected function registerServices() { $this->app->singleton('hashid', function ($app) { return new HashidManager($app); }); $this->app->alias('hashid', HashidManager::class); foreach ($this->getSingletonDrivers() as $class) { $this->app->singleton( $key = $this->getBindingKeyForDriver($class), function () use ($class) { return new $class; } ); $this->app->alias($key, $class); } foreach ($this->getNonSingletonDrivers() as $class) { $this->app->bind($this->getBindingKeyForDriver($class), $class); } }
[ "protected", "function", "registerServices", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'hashid'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "HashidManager", "(", "$", "app", ")", ";", "}", ")", ";", "$", "th...
Register service bindings. @return void
[ "Register", "service", "bindings", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidServiceProvider.php#L47-L67
ElfSundae/laravel-hashid
src/HashidServiceProvider.php
HashidServiceProvider.registerCommands
protected function registerCommands() { if ($this->app->runningInConsole()) { $this->commands([ Console\AlphabetGenerateCommand::class, Console\OptimusGenerateCommand::class, ]); } }
php
protected function registerCommands() { if ($this->app->runningInConsole()) { $this->commands([ Console\AlphabetGenerateCommand::class, Console\OptimusGenerateCommand::class, ]); } }
[ "protected", "function", "registerCommands", "(", ")", "{", "if", "(", "$", "this", "->", "app", "->", "runningInConsole", "(", ")", ")", "{", "$", "this", "->", "commands", "(", "[", "Console", "\\", "AlphabetGenerateCommand", "::", "class", ",", "Console...
Register console commands. @return void
[ "Register", "console", "commands", "." ]
train
https://github.com/ElfSundae/laravel-hashid/blob/226d90c9dece8787e73a1da378886fe0936876e0/src/HashidServiceProvider.php#L120-L128
dapphp/securimage
WavFile.php
WavFile.unpackSample
public static function unpackSample($sampleBinary, $bitDepth = null) { if ($bitDepth === null) { $bitDepth = strlen($sampleBinary) * 8; } switch ($bitDepth) { case 8: // unsigned char return ord($sampleBinary); case 16: // signed short, little endian $data = unpack('v', $sampleBinary); $sample = $data[1]; if ($sample >= 0x8000) { $sample -= 0x10000; } return $sample; case 24: // 3 byte packed signed integer, little endian $data = unpack('C3', $sampleBinary); $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16); if ($sample >= 0x800000) { $sample -= 0x1000000; } return $sample; case 32: // 32-bit float $data = unpack('f', $sampleBinary); return $data[1]; default: return null; } }
php
public static function unpackSample($sampleBinary, $bitDepth = null) { if ($bitDepth === null) { $bitDepth = strlen($sampleBinary) * 8; } switch ($bitDepth) { case 8: // unsigned char return ord($sampleBinary); case 16: // signed short, little endian $data = unpack('v', $sampleBinary); $sample = $data[1]; if ($sample >= 0x8000) { $sample -= 0x10000; } return $sample; case 24: // 3 byte packed signed integer, little endian $data = unpack('C3', $sampleBinary); $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16); if ($sample >= 0x800000) { $sample -= 0x1000000; } return $sample; case 32: // 32-bit float $data = unpack('f', $sampleBinary); return $data[1]; default: return null; } }
[ "public", "static", "function", "unpackSample", "(", "$", "sampleBinary", ",", "$", "bitDepth", "=", "null", ")", "{", "if", "(", "$", "bitDepth", "===", "null", ")", "{", "$", "bitDepth", "=", "strlen", "(", "$", "sampleBinary", ")", "*", "8", ";", ...
Unpacks a single binary sample to numeric value. @param string $sampleBinary (Required) The sample to decode. @param int $bitDepth (Optional) The bits per sample to decode. If omitted, derives it from the length of $sampleBinary. @return int|float|null The numeric sample value. Float for 32-bit samples. Returns null for unsupported bit depths.
[ "Unpacks", "a", "single", "binary", "sample", "to", "numeric", "value", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L301-L338
dapphp/securimage
WavFile.php
WavFile.packSample
public static function packSample($sample, $bitDepth) { switch ($bitDepth) { case 8: // unsigned char return chr($sample); case 16: // signed short, little endian if ($sample < 0) { $sample += 0x10000; } return pack('v', $sample); case 24: // 3 byte packed signed integer, little endian if ($sample < 0) { $sample += 0x1000000; } return pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff); case 32: // 32-bit float return pack('f', $sample); default: return null; } }
php
public static function packSample($sample, $bitDepth) { switch ($bitDepth) { case 8: // unsigned char return chr($sample); case 16: // signed short, little endian if ($sample < 0) { $sample += 0x10000; } return pack('v', $sample); case 24: // 3 byte packed signed integer, little endian if ($sample < 0) { $sample += 0x1000000; } return pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff); case 32: // 32-bit float return pack('f', $sample); default: return null; } }
[ "public", "static", "function", "packSample", "(", "$", "sample", ",", "$", "bitDepth", ")", "{", "switch", "(", "$", "bitDepth", ")", "{", "case", "8", ":", "// unsigned char", "return", "chr", "(", "$", "sample", ")", ";", "case", "16", ":", "// sign...
Packs a single numeric sample to binary. @param int|float $sample (Required) The sample to encode. Has to be within valid range for $bitDepth. Float values only for 32 bits. @param int $bitDepth (Required) The bits per sample to encode with. @return string|null The encoded binary sample. Returns null for unsupported bit depths.
[ "Packs", "a", "single", "numeric", "sample", "to", "binary", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L347-L375
dapphp/securimage
WavFile.php
WavFile.unpackSampleBlock
public static function unpackSampleBlock($sampleBlock, $bitDepth, $numChannels = null) { $sampleBytes = $bitDepth / 8; if ($numChannels === null) { $numChannels = strlen($sampleBlock) / $sampleBytes; } $samples = array(); for ($i = 0; $i < $numChannels; $i++) { $sampleBinary = substr($sampleBlock, $i * $sampleBytes, $sampleBytes); $samples[$i + 1] = self::unpackSample($sampleBinary, $bitDepth); } return $samples; }
php
public static function unpackSampleBlock($sampleBlock, $bitDepth, $numChannels = null) { $sampleBytes = $bitDepth / 8; if ($numChannels === null) { $numChannels = strlen($sampleBlock) / $sampleBytes; } $samples = array(); for ($i = 0; $i < $numChannels; $i++) { $sampleBinary = substr($sampleBlock, $i * $sampleBytes, $sampleBytes); $samples[$i + 1] = self::unpackSample($sampleBinary, $bitDepth); } return $samples; }
[ "public", "static", "function", "unpackSampleBlock", "(", "$", "sampleBlock", ",", "$", "bitDepth", ",", "$", "numChannels", "=", "null", ")", "{", "$", "sampleBytes", "=", "$", "bitDepth", "/", "8", ";", "if", "(", "$", "numChannels", "===", "null", ")"...
Unpacks a binary sample block to numeric values. @param string $sampleBlock (Required) The binary sample block (all channels). @param int $bitDepth (Required) The bits per sample to decode. @param int $numChannels (Optional) The number of channels to decode. If omitted, derives it from the length of $sampleBlock and $bitDepth. @return array The sample values as an array of integers of floats for 32 bits. First channel is array index 1.
[ "Unpacks", "a", "binary", "sample", "block", "to", "numeric", "values", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L385-L398
dapphp/securimage
WavFile.php
WavFile.packSampleBlock
public static function packSampleBlock($samples, $bitDepth) { $sampleBlock = ''; foreach($samples as $sample) { $sampleBlock .= self::packSample($sample, $bitDepth); } return $sampleBlock; }
php
public static function packSampleBlock($samples, $bitDepth) { $sampleBlock = ''; foreach($samples as $sample) { $sampleBlock .= self::packSample($sample, $bitDepth); } return $sampleBlock; }
[ "public", "static", "function", "packSampleBlock", "(", "$", "samples", ",", "$", "bitDepth", ")", "{", "$", "sampleBlock", "=", "''", ";", "foreach", "(", "$", "samples", "as", "$", "sample", ")", "{", "$", "sampleBlock", ".=", "self", "::", "packSample...
Packs an array of numeric channel samples to a binary sample block. @param array $samples (Required) The array of channel sample values. Expects float values for 32 bits and integer otherwise. @param int $bitDepth (Required) The bits per sample to encode with. @return string The encoded binary sample block.
[ "Packs", "an", "array", "of", "numeric", "channel", "samples", "to", "a", "binary", "sample", "block", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L407-L414
dapphp/securimage
WavFile.php
WavFile.normalizeSample
public static function normalizeSample($sampleFloat, $threshold) { // apply positive gain if ($threshold >= 1) { return $sampleFloat * $threshold; } // apply negative gain if ($threshold <= -1) { return $sampleFloat / -$threshold; } $sign = $sampleFloat < 0 ? -1 : 1; $sampleAbs = abs($sampleFloat); // logarithmic compression if ($threshold >= 0 && $threshold < 1 && $sampleAbs > $threshold) { $loga = self::$LOOKUP_LOGBASE[(int)($threshold * 20)]; // log base modifier return $sign * ($threshold + (1 - $threshold) * log(1 + $loga * ($sampleAbs - $threshold) / (2 - $threshold)) / log(1 + $loga)); } // linear compression $thresholdAbs = abs($threshold); if ($threshold > -1 && $threshold < 0 && $sampleAbs > $thresholdAbs) { return $sign * ($thresholdAbs + (1 - $thresholdAbs) / (2 - $thresholdAbs) * ($sampleAbs - $thresholdAbs)); } // else ? return $sampleFloat; }
php
public static function normalizeSample($sampleFloat, $threshold) { // apply positive gain if ($threshold >= 1) { return $sampleFloat * $threshold; } // apply negative gain if ($threshold <= -1) { return $sampleFloat / -$threshold; } $sign = $sampleFloat < 0 ? -1 : 1; $sampleAbs = abs($sampleFloat); // logarithmic compression if ($threshold >= 0 && $threshold < 1 && $sampleAbs > $threshold) { $loga = self::$LOOKUP_LOGBASE[(int)($threshold * 20)]; // log base modifier return $sign * ($threshold + (1 - $threshold) * log(1 + $loga * ($sampleAbs - $threshold) / (2 - $threshold)) / log(1 + $loga)); } // linear compression $thresholdAbs = abs($threshold); if ($threshold > -1 && $threshold < 0 && $sampleAbs > $thresholdAbs) { return $sign * ($thresholdAbs + (1 - $thresholdAbs) / (2 - $thresholdAbs) * ($sampleAbs - $thresholdAbs)); } // else ? return $sampleFloat; }
[ "public", "static", "function", "normalizeSample", "(", "$", "sampleFloat", ",", "$", "threshold", ")", "{", "// apply positive gain", "if", "(", "$", "threshold", ">=", "1", ")", "{", "return", "$", "sampleFloat", "*", "$", "threshold", ";", "}", "// apply ...
Normalizes a float audio sample. Maximum input range assumed for compression is [-2, 2]. See http://www.voegler.eu/pub/audio/ for more information. @param float $sampleFloat (Required) The float sample to normalize. @param float $threshold (Required) The threshold or gain factor for normalizing the amplitude. <ul> <li> >= 1 - Normalize by multiplying by the threshold (boost - positive gain). <br /> A value of 1 in effect means no normalization (and results in clipping). </li> <li> <= -1 - Normalize by dividing by the the absolute value of threshold (attenuate - negative gain). <br /> A factor of 2 (-2) is about 6dB reduction in volume.</li> <li> [0, 1) - (open inverval - not including 1) - The threshold above which amplitudes are comressed logarithmically. <br /> e.g. 0.6 to leave amplitudes up to 60% "as is" and compress above. </li> <li> (-1, 0) - (open inverval - not including -1 and 0) - The threshold above which amplitudes are comressed linearly. <br /> e.g. -0.6 to leave amplitudes up to 60% "as is" and compress above. </li></ul> @return float The normalized sample.
[ "Normalizes", "a", "float", "audio", "sample", ".", "Maximum", "input", "range", "assumed", "for", "compression", "is", "[", "-", "2", "2", "]", ".", "See", "http", ":", "//", "www", ".", "voegler", ".", "eu", "/", "pub", "/", "audio", "/", "for", ...
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L434-L462
dapphp/securimage
WavFile.php
WavFile.makeHeader
public function makeHeader() { // reset and recalculate $this->setAudioFormat(); // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset() $this->setNumBlocks(); // RIFF header $header = pack('N', 0x52494646); // ChunkID - "RIFF" $header .= pack('V', $this->getChunkSize()); // ChunkSize $header .= pack('N', 0x57415645); // Format - "WAVE" // "fmt " subchunk $header .= pack('N', 0x666d7420); // SubchunkID - "fmt " $header .= pack('V', $this->getFmtChunkSize()); // SubchunkSize $header .= pack('v', $this->getAudioFormat()); // AudioFormat $header .= pack('v', $this->getNumChannels()); // NumChannels $header .= pack('V', $this->getSampleRate()); // SampleRate $header .= pack('V', $this->getByteRate()); // ByteRate $header .= pack('v', $this->getBlockAlign()); // BlockAlign $header .= pack('v', $this->getBitsPerSample()); // BitsPerSample if($this->getFmtExtendedSize() == 24) { $header .= pack('v', 22); // extension size = 24 bytes, cbSize: 24 - 2 = 22 bytes $header .= pack('v', $this->getValidBitsPerSample()); // ValidBitsPerSample $header .= pack('V', $this->getChannelMask()); // ChannelMask $header .= pack('H32', $this->getAudioSubFormat()); // SubFormat } elseif ($this->getFmtExtendedSize() == 2) { $header .= pack('v', 0); // extension size = 2 bytes, cbSize: 2 - 2 = 0 bytes } // "fact" subchunk if ($this->getFactChunkSize() == 4) { $header .= pack('N', 0x66616374); // SubchunkID - "fact" $header .= pack('V', 4); // SubchunkSize $header .= pack('V', $this->getNumBlocks()); // SampleLength (per channel) } return $header; }
php
public function makeHeader() { // reset and recalculate $this->setAudioFormat(); // implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset() $this->setNumBlocks(); // RIFF header $header = pack('N', 0x52494646); // ChunkID - "RIFF" $header .= pack('V', $this->getChunkSize()); // ChunkSize $header .= pack('N', 0x57415645); // Format - "WAVE" // "fmt " subchunk $header .= pack('N', 0x666d7420); // SubchunkID - "fmt " $header .= pack('V', $this->getFmtChunkSize()); // SubchunkSize $header .= pack('v', $this->getAudioFormat()); // AudioFormat $header .= pack('v', $this->getNumChannels()); // NumChannels $header .= pack('V', $this->getSampleRate()); // SampleRate $header .= pack('V', $this->getByteRate()); // ByteRate $header .= pack('v', $this->getBlockAlign()); // BlockAlign $header .= pack('v', $this->getBitsPerSample()); // BitsPerSample if($this->getFmtExtendedSize() == 24) { $header .= pack('v', 22); // extension size = 24 bytes, cbSize: 24 - 2 = 22 bytes $header .= pack('v', $this->getValidBitsPerSample()); // ValidBitsPerSample $header .= pack('V', $this->getChannelMask()); // ChannelMask $header .= pack('H32', $this->getAudioSubFormat()); // SubFormat } elseif ($this->getFmtExtendedSize() == 2) { $header .= pack('v', 0); // extension size = 2 bytes, cbSize: 2 - 2 = 0 bytes } // "fact" subchunk if ($this->getFactChunkSize() == 4) { $header .= pack('N', 0x66616374); // SubchunkID - "fact" $header .= pack('V', 4); // SubchunkSize $header .= pack('V', $this->getNumBlocks()); // SampleLength (per channel) } return $header; }
[ "public", "function", "makeHeader", "(", ")", "{", "// reset and recalculate", "$", "this", "->", "setAudioFormat", "(", ")", ";", "// implicit setAudioSubFormat(), setFactChunkSize(), setFmtExtendedSize(), setFmtChunkSize(), setSize(), setActualSize(), setDataOffset()", "$", "this",...
Construct a wav header from this object. Includes "fact" chunk if necessary. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html @return string The RIFF header data.
[ "Construct", "a", "wav", "header", "from", "this", "object", ".", "Includes", "fact", "chunk", "if", "necessary", ".", "http", ":", "//", "www", "-", "mmsp", ".", "ece", ".", "mcgill", ".", "ca", "/", "documents", "/", "audioformats", "/", "wave", "/",...
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L879-L916
dapphp/securimage
WavFile.php
WavFile.getDataSubchunk
public function getDataSubchunk() { // check preconditions if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } // create subchunk return pack('N', 0x64617461) . // SubchunkID - "data" pack('V', $this->getDataSize()) . // SubchunkSize $this->_samples . // Subchunk data ($this->getDataSize() & 1 ? chr(0) : ''); // padding byte }
php
public function getDataSubchunk() { // check preconditions if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } // create subchunk return pack('N', 0x64617461) . // SubchunkID - "data" pack('V', $this->getDataSize()) . // SubchunkSize $this->_samples . // Subchunk data ($this->getDataSize() & 1 ? chr(0) : ''); // padding byte }
[ "public", "function", "getDataSubchunk", "(", ")", "{", "// check preconditions", "if", "(", "!", "$", "this", "->", "_dataSize_valid", ")", "{", "$", "this", "->", "setDataSize", "(", ")", ";", "// implicit setSize(), setActualSize(), setNumBlocks()", "}", "// crea...
Construct wav DATA chunk. @return string The DATA header and chunk.
[ "Construct", "wav", "DATA", "chunk", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L923-L936
dapphp/securimage
WavFile.php
WavFile.save
public function save($filename) { $fp = @fopen($filename, 'w+b'); if (!is_resource($fp)) { throw new WavFileException('Failed to open "' . $filename . '" for writing.'); } fwrite($fp, $this->makeHeader()); fwrite($fp, $this->getDataSubchunk()); fclose($fp); return $this; }
php
public function save($filename) { $fp = @fopen($filename, 'w+b'); if (!is_resource($fp)) { throw new WavFileException('Failed to open "' . $filename . '" for writing.'); } fwrite($fp, $this->makeHeader()); fwrite($fp, $this->getDataSubchunk()); fclose($fp); return $this; }
[ "public", "function", "save", "(", "$", "filename", ")", "{", "$", "fp", "=", "@", "fopen", "(", "$", "filename", ",", "'w+b'", ")", ";", "if", "(", "!", "is_resource", "(", "$", "fp", ")", ")", "{", "throw", "new", "WavFileException", "(", "'Faile...
Save the wav data to a file. @param string $filename (Required) The file path to save the wav to. @throws WavFileException
[ "Save", "the", "wav", "data", "to", "a", "file", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L944-L956
dapphp/securimage
WavFile.php
WavFile.openWav
public function openWav($filename, $readData = true) { // check preconditions if (!file_exists($filename)) { throw new WavFileException('Failed to open "' . $filename . '". File not found.'); } elseif (!is_readable($filename)) { throw new WavFileException('Failed to open "' . $filename . '". File is not readable.'); } elseif (is_resource($this->_fp)) { $this->closeWav(); } // open the file $this->_fp = @fopen($filename, 'rb'); if (!is_resource($this->_fp)) { throw new WavFileException('Failed to open "' . $filename . '".'); } // read the file return $this->readWav($readData); }
php
public function openWav($filename, $readData = true) { // check preconditions if (!file_exists($filename)) { throw new WavFileException('Failed to open "' . $filename . '". File not found.'); } elseif (!is_readable($filename)) { throw new WavFileException('Failed to open "' . $filename . '". File is not readable.'); } elseif (is_resource($this->_fp)) { $this->closeWav(); } // open the file $this->_fp = @fopen($filename, 'rb'); if (!is_resource($this->_fp)) { throw new WavFileException('Failed to open "' . $filename . '".'); } // read the file return $this->readWav($readData); }
[ "public", "function", "openWav", "(", "$", "filename", ",", "$", "readData", "=", "true", ")", "{", "// check preconditions", "if", "(", "!", "file_exists", "(", "$", "filename", ")", ")", "{", "throw", "new", "WavFileException", "(", "'Failed to open \"'", ...
Reads a wav header and data from a file. @param string $filename (Required) The path to the wav file to read. @param bool $readData (Optional) If true, also read the data chunk. @throws WavFormatException @throws WavFileException
[ "Reads", "a", "wav", "header", "and", "data", "from", "a", "file", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L966-L986
dapphp/securimage
WavFile.php
WavFile.setWavData
public function setWavData(&$data, $free = true) { // check preconditions if (is_resource($this->_fp)) $this->closeWav(); // open temporary stream in memory $this->_fp = @fopen('php://memory', 'w+b'); if (!is_resource($this->_fp)) { throw new WavFileException('Failed to open memory stream to write wav data. Use openWav() instead.'); } // prepare stream fwrite($this->_fp, $data); rewind($this->_fp); // free the passed data if ($free) $data = null; // read the stream like a file return $this->readWav(true); }
php
public function setWavData(&$data, $free = true) { // check preconditions if (is_resource($this->_fp)) $this->closeWav(); // open temporary stream in memory $this->_fp = @fopen('php://memory', 'w+b'); if (!is_resource($this->_fp)) { throw new WavFileException('Failed to open memory stream to write wav data. Use openWav() instead.'); } // prepare stream fwrite($this->_fp, $data); rewind($this->_fp); // free the passed data if ($free) $data = null; // read the stream like a file return $this->readWav(true); }
[ "public", "function", "setWavData", "(", "&", "$", "data", ",", "$", "free", "=", "true", ")", "{", "// check preconditions", "if", "(", "is_resource", "(", "$", "this", "->", "_fp", ")", ")", "$", "this", "->", "closeWav", "(", ")", ";", "// open temp...
Set the wav file data and properties from a wav file in a string. @param string $data (Required) The wav file data. Passed by reference. @param bool $free (Optional) True to free the passed $data after copying. @throws WavFormatException @throws WavFileException
[ "Set", "the", "wav", "file", "data", "and", "properties", "from", "a", "wav", "file", "in", "a", "string", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1006-L1027
dapphp/securimage
WavFile.php
WavFile.readWav
protected function readWav($readData = true) { if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } try { $this->readWavHeader(); } catch (WavFileException $ex) { $this->closeWav(); throw $ex; } if ($readData) return $this->readWavData(); return $this; }
php
protected function readWav($readData = true) { if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } try { $this->readWavHeader(); } catch (WavFileException $ex) { $this->closeWav(); throw $ex; } if ($readData) return $this->readWavData(); return $this; }
[ "protected", "function", "readWav", "(", "$", "readData", "=", "true", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "_fp", ")", ")", "{", "throw", "new", "WavFileException", "(", "'No wav file open. Use openWav() first.'", ")", ";", "}", ...
Read wav file from a stream. @param bool $readData (Optional) If true, also read the data chunk. @throws WavFormatException @throws WavFileException
[ "Read", "wav", "file", "from", "a", "stream", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1036-L1052
dapphp/securimage
WavFile.php
WavFile.readWavHeader
protected function readWavHeader() { if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } // get actual file size $stat = fstat($this->_fp); $actualSize = $stat['size']; $this->_actualSize = $actualSize; // read the common header $header = fread($this->_fp, 36); // minimum size of the wav header if (strlen($header) < 36) { throw new WavFormatException('Not wav format. Header too short.', 1); } // check "RIFF" header $RIFF = unpack('NChunkID/VChunkSize/NFormat', $header); if ($RIFF['ChunkID'] != 0x52494646) { // "RIFF" throw new WavFormatException('Not wav format. "RIFF" signature missing.', 2); } if ($this->getIgnoreChunkSizes()) { $RIFF['ChunkSize'] = $actualSize - 8; } else if ($actualSize - 8 < $RIFF['ChunkSize']) { trigger_error('"RIFF" chunk size does not match actual file size. Found ' . $RIFF['ChunkSize'] . ', expected ' . ($actualSize - 8) . '.', E_USER_NOTICE); $RIFF['ChunkSize'] = $actualSize - 8; } if ($RIFF['Format'] != 0x57415645) { // "WAVE" throw new WavFormatException('Not wav format. "RIFF" chunk format is not "WAVE".', 4); } $this->_chunkSize = $RIFF['ChunkSize']; // check common "fmt " subchunk $fmt = unpack('NSubchunkID/VSubchunkSize/vAudioFormat/vNumChannels/' .'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', substr($header, 12)); if ($fmt['SubchunkID'] != 0x666d7420) { // "fmt " throw new WavFormatException('Bad wav header. Expected "fmt " subchunk.', 11); } if ($fmt['SubchunkSize'] < 16) { throw new WavFormatException('Bad "fmt " subchunk size.', 12); } if ( $fmt['AudioFormat'] != self::WAVE_FORMAT_PCM && $fmt['AudioFormat'] != self::WAVE_FORMAT_IEEE_FLOAT && $fmt['AudioFormat'] != self::WAVE_FORMAT_EXTENSIBLE) { throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13); } if ($fmt['NumChannels'] < 1 || $fmt['NumChannels'] > self::MAX_CHANNEL) { throw new WavFormatException('Invalid number of channels in "fmt " subchunk.', 14); } if ($fmt['SampleRate'] < 1 || $fmt['SampleRate'] > self::MAX_SAMPLERATE) { throw new WavFormatException('Invalid sample rate in "fmt " subchunk.', 15); } if ( ($fmt['AudioFormat'] == self::WAVE_FORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24))) || ($fmt['AudioFormat'] == self::WAVE_FORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32) || ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE && !in_array($fmt['BitsPerSample'], array(8, 16, 24, 32)))) { throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16); } $blockAlign = $fmt['NumChannels'] * $fmt['BitsPerSample'] / 8; if ($blockAlign != $fmt['BlockAlign']) { trigger_error('Invalid block align in "fmt " subchunk. Found ' . $fmt['BlockAlign'] . ', expected ' . $blockAlign . '.', E_USER_NOTICE); $fmt['BlockAlign'] = $blockAlign; } $byteRate = $fmt['SampleRate'] * $blockAlign; if ($byteRate != $fmt['ByteRate']) { trigger_error('Invalid average byte rate in "fmt " subchunk. Found ' . $fmt['ByteRate'] . ', expected ' . $byteRate . '.', E_USER_NOTICE); $fmt['ByteRate'] = $byteRate; } $this->_fmtChunkSize = $fmt['SubchunkSize']; $this->_audioFormat = $fmt['AudioFormat']; $this->_numChannels = $fmt['NumChannels']; $this->_sampleRate = $fmt['SampleRate']; $this->_byteRate = $fmt['ByteRate']; $this->_blockAlign = $fmt['BlockAlign']; $this->_bitsPerSample = $fmt['BitsPerSample']; // read extended "fmt " subchunk data $extendedFmt = ''; if ($fmt['SubchunkSize'] > 16) { // possibly handle malformed subchunk without a padding byte $extendedFmt = fread($this->_fp, $fmt['SubchunkSize'] - 16 + ($fmt['SubchunkSize'] & 1)); // also read padding byte if (strlen($extendedFmt) < $fmt['SubchunkSize'] - 16) { throw new WavFormatException('Not wav format. Header too short.', 1); } } // check extended "fmt " for EXTENSIBLE Audio Format if ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE) { if (strlen($extendedFmt) < 24) { throw new WavFormatException('Invalid EXTENSIBLE "fmt " subchunk size. Found ' . $fmt['SubchunkSize'] . ', expected at least 40.', 19); } $extensibleFmt = unpack('vSize/vValidBitsPerSample/VChannelMask/H32SubFormat', substr($extendedFmt, 0, 24)); if ( $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_PCM && $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_IEEE_FLOAT) { throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13); } if ( ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24))) || ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32)) { throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16); } if ($extensibleFmt['Size'] != 22) { trigger_error('Invaid extension size in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE); $extensibleFmt['Size'] = 22; } if ($extensibleFmt['ValidBitsPerSample'] != $fmt['BitsPerSample']) { trigger_error('Invaid or unsupported valid bits per sample in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE); $extensibleFmt['ValidBitsPerSample'] = $fmt['BitsPerSample']; } if ($extensibleFmt['ChannelMask'] != 0) { // count number of set bits - Hamming weight $c = (int)$extensibleFmt['ChannelMask']; $n = 0; while ($c > 0) { $n += $c & 1; $c >>= 1; } if ($n != $fmt['NumChannels'] || (((int)$extensibleFmt['ChannelMask'] | self::SPEAKER_ALL) != self::SPEAKER_ALL)) { trigger_error('Invalid channel mask in EXTENSIBLE "fmt " subchunk. The number of channels does not match the number of locations in the mask.', E_USER_NOTICE); $extensibleFmt['ChannelMask'] = 0; } } $this->_fmtExtendedSize = strlen($extendedFmt); $this->_validBitsPerSample = $extensibleFmt['ValidBitsPerSample']; $this->_channelMask = $extensibleFmt['ChannelMask']; $this->_audioSubFormat = $extensibleFmt['SubFormat']; } else { $this->_fmtExtendedSize = strlen($extendedFmt); $this->_validBitsPerSample = $fmt['BitsPerSample']; $this->_channelMask = 0; $this->_audioSubFormat = null; } // read additional subchunks until "data" subchunk is found $factSubchunk = array(); $dataSubchunk = array(); while (!feof($this->_fp)) { $subchunkHeader = fread($this->_fp, 8); if (strlen($subchunkHeader) < 8) { throw new WavFormatException('Missing "data" subchunk.', 101); } $subchunk = unpack('NSubchunkID/VSubchunkSize', $subchunkHeader); if ($subchunk['SubchunkID'] == 0x66616374) { // "fact" // possibly handle malformed subchunk without a padding byte $subchunkData = fread($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1)); // also read padding byte if (strlen($subchunkData) < 4) { throw new WavFormatException('Invalid "fact" subchunk.', 102); } $factParams = unpack('VSampleLength', substr($subchunkData, 0, 4)); $factSubchunk = array_merge($subchunk, $factParams); } elseif ($subchunk['SubchunkID'] == 0x64617461) { // "data" $dataSubchunk = $subchunk; break; } elseif ($subchunk['SubchunkID'] == 0x7761766C) { // "wavl" throw new WavFormatException('Wave List Chunk ("wavl" subchunk) is not supported.', 106); } else { // skip all other (unknown) subchunks // possibly handle malformed subchunk without a padding byte if ( $subchunk['SubchunkSize'] < 0 || fseek($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1), SEEK_CUR) !== 0) { // also skip padding byte throw new WavFormatException('Invalid subchunk (0x' . dechex($subchunk['SubchunkID']) . ') encountered.', 103); } } } if (empty($dataSubchunk)) { throw new WavFormatException('Missing "data" subchunk.', 101); } // check "data" subchunk $dataOffset = ftell($this->_fp); if ($this->getIgnoreChunkSizes()) { $dataSubchunk['SubchunkSize'] = $actualSize - $dataOffset; } elseif ($dataSubchunk['SubchunkSize'] < 0 || $actualSize - $dataOffset < $dataSubchunk['SubchunkSize']) { trigger_error("Invalid \"data\" subchunk size (found {$dataSubchunk['SubchunkSize']}.", E_USER_NOTICE); $dataSubchunk['SubchunkSize'] = $actualSize - $dataOffset; } $this->_dataOffset = $dataOffset; $this->_dataSize = $dataSubchunk['SubchunkSize']; $this->_dataSize_fp = $dataSubchunk['SubchunkSize']; $this->_dataSize_valid = false; $this->_samples = ''; // check "fact" subchunk $numBlocks = (int)($dataSubchunk['SubchunkSize'] / $fmt['BlockAlign']); if (empty($factSubchunk)) { // construct fake "fact" subchunk $factSubchunk = array('SubchunkSize' => 0, 'SampleLength' => $numBlocks); } if ($factSubchunk['SampleLength'] != $numBlocks) { trigger_error('Invalid sample length in "fact" subchunk.', E_USER_NOTICE); $factSubchunk['SampleLength'] = $numBlocks; } $this->_factChunkSize = $factSubchunk['SubchunkSize']; $this->_numBlocks = $factSubchunk['SampleLength']; return $this; }
php
protected function readWavHeader() { if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } // get actual file size $stat = fstat($this->_fp); $actualSize = $stat['size']; $this->_actualSize = $actualSize; // read the common header $header = fread($this->_fp, 36); // minimum size of the wav header if (strlen($header) < 36) { throw new WavFormatException('Not wav format. Header too short.', 1); } // check "RIFF" header $RIFF = unpack('NChunkID/VChunkSize/NFormat', $header); if ($RIFF['ChunkID'] != 0x52494646) { // "RIFF" throw new WavFormatException('Not wav format. "RIFF" signature missing.', 2); } if ($this->getIgnoreChunkSizes()) { $RIFF['ChunkSize'] = $actualSize - 8; } else if ($actualSize - 8 < $RIFF['ChunkSize']) { trigger_error('"RIFF" chunk size does not match actual file size. Found ' . $RIFF['ChunkSize'] . ', expected ' . ($actualSize - 8) . '.', E_USER_NOTICE); $RIFF['ChunkSize'] = $actualSize - 8; } if ($RIFF['Format'] != 0x57415645) { // "WAVE" throw new WavFormatException('Not wav format. "RIFF" chunk format is not "WAVE".', 4); } $this->_chunkSize = $RIFF['ChunkSize']; // check common "fmt " subchunk $fmt = unpack('NSubchunkID/VSubchunkSize/vAudioFormat/vNumChannels/' .'VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', substr($header, 12)); if ($fmt['SubchunkID'] != 0x666d7420) { // "fmt " throw new WavFormatException('Bad wav header. Expected "fmt " subchunk.', 11); } if ($fmt['SubchunkSize'] < 16) { throw new WavFormatException('Bad "fmt " subchunk size.', 12); } if ( $fmt['AudioFormat'] != self::WAVE_FORMAT_PCM && $fmt['AudioFormat'] != self::WAVE_FORMAT_IEEE_FLOAT && $fmt['AudioFormat'] != self::WAVE_FORMAT_EXTENSIBLE) { throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13); } if ($fmt['NumChannels'] < 1 || $fmt['NumChannels'] > self::MAX_CHANNEL) { throw new WavFormatException('Invalid number of channels in "fmt " subchunk.', 14); } if ($fmt['SampleRate'] < 1 || $fmt['SampleRate'] > self::MAX_SAMPLERATE) { throw new WavFormatException('Invalid sample rate in "fmt " subchunk.', 15); } if ( ($fmt['AudioFormat'] == self::WAVE_FORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24))) || ($fmt['AudioFormat'] == self::WAVE_FORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32) || ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE && !in_array($fmt['BitsPerSample'], array(8, 16, 24, 32)))) { throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16); } $blockAlign = $fmt['NumChannels'] * $fmt['BitsPerSample'] / 8; if ($blockAlign != $fmt['BlockAlign']) { trigger_error('Invalid block align in "fmt " subchunk. Found ' . $fmt['BlockAlign'] . ', expected ' . $blockAlign . '.', E_USER_NOTICE); $fmt['BlockAlign'] = $blockAlign; } $byteRate = $fmt['SampleRate'] * $blockAlign; if ($byteRate != $fmt['ByteRate']) { trigger_error('Invalid average byte rate in "fmt " subchunk. Found ' . $fmt['ByteRate'] . ', expected ' . $byteRate . '.', E_USER_NOTICE); $fmt['ByteRate'] = $byteRate; } $this->_fmtChunkSize = $fmt['SubchunkSize']; $this->_audioFormat = $fmt['AudioFormat']; $this->_numChannels = $fmt['NumChannels']; $this->_sampleRate = $fmt['SampleRate']; $this->_byteRate = $fmt['ByteRate']; $this->_blockAlign = $fmt['BlockAlign']; $this->_bitsPerSample = $fmt['BitsPerSample']; // read extended "fmt " subchunk data $extendedFmt = ''; if ($fmt['SubchunkSize'] > 16) { // possibly handle malformed subchunk without a padding byte $extendedFmt = fread($this->_fp, $fmt['SubchunkSize'] - 16 + ($fmt['SubchunkSize'] & 1)); // also read padding byte if (strlen($extendedFmt) < $fmt['SubchunkSize'] - 16) { throw new WavFormatException('Not wav format. Header too short.', 1); } } // check extended "fmt " for EXTENSIBLE Audio Format if ($fmt['AudioFormat'] == self::WAVE_FORMAT_EXTENSIBLE) { if (strlen($extendedFmt) < 24) { throw new WavFormatException('Invalid EXTENSIBLE "fmt " subchunk size. Found ' . $fmt['SubchunkSize'] . ', expected at least 40.', 19); } $extensibleFmt = unpack('vSize/vValidBitsPerSample/VChannelMask/H32SubFormat', substr($extendedFmt, 0, 24)); if ( $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_PCM && $extensibleFmt['SubFormat'] != self::WAVE_SUBFORMAT_IEEE_FLOAT) { throw new WavFormatException('Unsupported audio format. Only PCM or IEEE FLOAT (EXTENSIBLE) audio is supported.', 13); } if ( ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_PCM && !in_array($fmt['BitsPerSample'], array(8, 16, 24))) || ($extensibleFmt['SubFormat'] == self::WAVE_SUBFORMAT_IEEE_FLOAT && $fmt['BitsPerSample'] != 32)) { throw new WavFormatException('Only 8, 16 and 24-bit PCM and 32-bit IEEE FLOAT (EXTENSIBLE) audio is supported.', 16); } if ($extensibleFmt['Size'] != 22) { trigger_error('Invaid extension size in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE); $extensibleFmt['Size'] = 22; } if ($extensibleFmt['ValidBitsPerSample'] != $fmt['BitsPerSample']) { trigger_error('Invaid or unsupported valid bits per sample in EXTENSIBLE "fmt " subchunk.', E_USER_NOTICE); $extensibleFmt['ValidBitsPerSample'] = $fmt['BitsPerSample']; } if ($extensibleFmt['ChannelMask'] != 0) { // count number of set bits - Hamming weight $c = (int)$extensibleFmt['ChannelMask']; $n = 0; while ($c > 0) { $n += $c & 1; $c >>= 1; } if ($n != $fmt['NumChannels'] || (((int)$extensibleFmt['ChannelMask'] | self::SPEAKER_ALL) != self::SPEAKER_ALL)) { trigger_error('Invalid channel mask in EXTENSIBLE "fmt " subchunk. The number of channels does not match the number of locations in the mask.', E_USER_NOTICE); $extensibleFmt['ChannelMask'] = 0; } } $this->_fmtExtendedSize = strlen($extendedFmt); $this->_validBitsPerSample = $extensibleFmt['ValidBitsPerSample']; $this->_channelMask = $extensibleFmt['ChannelMask']; $this->_audioSubFormat = $extensibleFmt['SubFormat']; } else { $this->_fmtExtendedSize = strlen($extendedFmt); $this->_validBitsPerSample = $fmt['BitsPerSample']; $this->_channelMask = 0; $this->_audioSubFormat = null; } // read additional subchunks until "data" subchunk is found $factSubchunk = array(); $dataSubchunk = array(); while (!feof($this->_fp)) { $subchunkHeader = fread($this->_fp, 8); if (strlen($subchunkHeader) < 8) { throw new WavFormatException('Missing "data" subchunk.', 101); } $subchunk = unpack('NSubchunkID/VSubchunkSize', $subchunkHeader); if ($subchunk['SubchunkID'] == 0x66616374) { // "fact" // possibly handle malformed subchunk without a padding byte $subchunkData = fread($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1)); // also read padding byte if (strlen($subchunkData) < 4) { throw new WavFormatException('Invalid "fact" subchunk.', 102); } $factParams = unpack('VSampleLength', substr($subchunkData, 0, 4)); $factSubchunk = array_merge($subchunk, $factParams); } elseif ($subchunk['SubchunkID'] == 0x64617461) { // "data" $dataSubchunk = $subchunk; break; } elseif ($subchunk['SubchunkID'] == 0x7761766C) { // "wavl" throw new WavFormatException('Wave List Chunk ("wavl" subchunk) is not supported.', 106); } else { // skip all other (unknown) subchunks // possibly handle malformed subchunk without a padding byte if ( $subchunk['SubchunkSize'] < 0 || fseek($this->_fp, $subchunk['SubchunkSize'] + ($subchunk['SubchunkSize'] & 1), SEEK_CUR) !== 0) { // also skip padding byte throw new WavFormatException('Invalid subchunk (0x' . dechex($subchunk['SubchunkID']) . ') encountered.', 103); } } } if (empty($dataSubchunk)) { throw new WavFormatException('Missing "data" subchunk.', 101); } // check "data" subchunk $dataOffset = ftell($this->_fp); if ($this->getIgnoreChunkSizes()) { $dataSubchunk['SubchunkSize'] = $actualSize - $dataOffset; } elseif ($dataSubchunk['SubchunkSize'] < 0 || $actualSize - $dataOffset < $dataSubchunk['SubchunkSize']) { trigger_error("Invalid \"data\" subchunk size (found {$dataSubchunk['SubchunkSize']}.", E_USER_NOTICE); $dataSubchunk['SubchunkSize'] = $actualSize - $dataOffset; } $this->_dataOffset = $dataOffset; $this->_dataSize = $dataSubchunk['SubchunkSize']; $this->_dataSize_fp = $dataSubchunk['SubchunkSize']; $this->_dataSize_valid = false; $this->_samples = ''; // check "fact" subchunk $numBlocks = (int)($dataSubchunk['SubchunkSize'] / $fmt['BlockAlign']); if (empty($factSubchunk)) { // construct fake "fact" subchunk $factSubchunk = array('SubchunkSize' => 0, 'SampleLength' => $numBlocks); } if ($factSubchunk['SampleLength'] != $numBlocks) { trigger_error('Invalid sample length in "fact" subchunk.', E_USER_NOTICE); $factSubchunk['SampleLength'] = $numBlocks; } $this->_factChunkSize = $factSubchunk['SubchunkSize']; $this->_numBlocks = $factSubchunk['SampleLength']; return $this; }
[ "protected", "function", "readWavHeader", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "_fp", ")", ")", "{", "throw", "new", "WavFileException", "(", "'No wav file open. Use openWav() first.'", ")", ";", "}", "// get actual file size", "...
Parse a wav header. http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html @throws WavFormatException @throws WavFileException
[ "Parse", "a", "wav", "header", ".", "http", ":", "//", "www", "-", "mmsp", ".", "ece", ".", "mcgill", ".", "ca", "/", "documents", "/", "audioformats", "/", "wave", "/", "wave", ".", "html" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1061-L1303
dapphp/securimage
WavFile.php
WavFile.readWavData
public function readWavData($dataOffset = 0, $dataSize = null) { // check preconditions if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } if ($dataOffset < 0 || $dataOffset % $this->getBlockAlign() > 0) { throw new WavFileException('Invalid data offset. Has to be a multiple of BlockAlign.'); } if (is_null($dataSize)) { $dataSize = $this->_dataSize_fp - ($this->_dataSize_fp % $this->getBlockAlign()); // only read complete blocks } elseif ($dataSize < 0 || $dataSize % $this->getBlockAlign() > 0) { throw new WavFileException('Invalid data size to read. Has to be a multiple of BlockAlign.'); } // skip offset if ($dataOffset > 0 && fseek($this->_fp, $dataOffset, SEEK_CUR) !== 0) { throw new WavFileException('Seeking to data offset failed.'); } // read data $this->_samples .= fread($this->_fp, $dataSize); // allow appending $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() // close file or memory stream return $this->closeWav(); }
php
public function readWavData($dataOffset = 0, $dataSize = null) { // check preconditions if (!is_resource($this->_fp)) { throw new WavFileException('No wav file open. Use openWav() first.'); } if ($dataOffset < 0 || $dataOffset % $this->getBlockAlign() > 0) { throw new WavFileException('Invalid data offset. Has to be a multiple of BlockAlign.'); } if (is_null($dataSize)) { $dataSize = $this->_dataSize_fp - ($this->_dataSize_fp % $this->getBlockAlign()); // only read complete blocks } elseif ($dataSize < 0 || $dataSize % $this->getBlockAlign() > 0) { throw new WavFileException('Invalid data size to read. Has to be a multiple of BlockAlign.'); } // skip offset if ($dataOffset > 0 && fseek($this->_fp, $dataOffset, SEEK_CUR) !== 0) { throw new WavFileException('Seeking to data offset failed.'); } // read data $this->_samples .= fread($this->_fp, $dataSize); // allow appending $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() // close file or memory stream return $this->closeWav(); }
[ "public", "function", "readWavData", "(", "$", "dataOffset", "=", "0", ",", "$", "dataSize", "=", "null", ")", "{", "// check preconditions", "if", "(", "!", "is_resource", "(", "$", "this", "->", "_fp", ")", ")", "{", "throw", "new", "WavFileException", ...
Read the wav data from the file into the buffer. @param int $dataOffset (Optional) The byte offset to skip before starting to read. Must be a multiple of BlockAlign. @param int $dataSize (Optional) The size of the data to read in bytes. Must be a multiple of BlockAlign. Defaults to all data. @throws WavFileException
[ "Read", "the", "wav", "data", "from", "the", "file", "into", "the", "buffer", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1312-L1341
dapphp/securimage
WavFile.php
WavFile.getSampleBlock
public function getSampleBlock($blockNum) { // check preconditions if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $offset = $blockNum * $this->_blockAlign; if ($offset + $this->_blockAlign > $this->_dataSize || $offset < 0) { return null; } // read data return substr($this->_samples, $offset, $this->_blockAlign); }
php
public function getSampleBlock($blockNum) { // check preconditions if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $offset = $blockNum * $this->_blockAlign; if ($offset + $this->_blockAlign > $this->_dataSize || $offset < 0) { return null; } // read data return substr($this->_samples, $offset, $this->_blockAlign); }
[ "public", "function", "getSampleBlock", "(", "$", "blockNum", ")", "{", "// check preconditions", "if", "(", "!", "$", "this", "->", "_dataSize_valid", ")", "{", "$", "this", "->", "setDataSize", "(", ")", ";", "// implicit setSize(), setActualSize(), setNumBlocks()...
Return a single sample block from the file. @param int $blockNum (Required) The sample block number. Zero based. @return string|null The binary sample block (all channels). Returns null if the sample block number was out of range.
[ "Return", "a", "single", "sample", "block", "from", "the", "file", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1353-L1368
dapphp/securimage
WavFile.php
WavFile.setSampleBlock
public function setSampleBlock($sampleBlock, $blockNum) { // check preconditions $blockAlign = $this->_blockAlign; if (!isset($sampleBlock[$blockAlign - 1]) || isset($sampleBlock[$blockAlign])) { // faster than: if (strlen($sampleBlock) != $blockAlign) throw new WavFileException('Incorrect sample block size. Got ' . strlen($sampleBlock) . ', expected ' . $blockAlign . '.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $numBlocks = (int)($this->_dataSize / $blockAlign); $offset = $blockNum * $blockAlign; if ($blockNum > $numBlocks || $blockNum < 0) { // allow appending throw new WavFileException('Sample block number is out of range.'); } // replace or append data if ($blockNum == $numBlocks) { // append $this->_samples .= $sampleBlock; $this->_dataSize += $blockAlign; $this->_chunkSize += $blockAlign; $this->_actualSize += $blockAlign; $this->_numBlocks++; } else { // replace for ($i = 0; $i < $blockAlign; ++$i) { $this->_samples[$offset + $i] = $sampleBlock[$i]; } } return $this; }
php
public function setSampleBlock($sampleBlock, $blockNum) { // check preconditions $blockAlign = $this->_blockAlign; if (!isset($sampleBlock[$blockAlign - 1]) || isset($sampleBlock[$blockAlign])) { // faster than: if (strlen($sampleBlock) != $blockAlign) throw new WavFileException('Incorrect sample block size. Got ' . strlen($sampleBlock) . ', expected ' . $blockAlign . '.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $numBlocks = (int)($this->_dataSize / $blockAlign); $offset = $blockNum * $blockAlign; if ($blockNum > $numBlocks || $blockNum < 0) { // allow appending throw new WavFileException('Sample block number is out of range.'); } // replace or append data if ($blockNum == $numBlocks) { // append $this->_samples .= $sampleBlock; $this->_dataSize += $blockAlign; $this->_chunkSize += $blockAlign; $this->_actualSize += $blockAlign; $this->_numBlocks++; } else { // replace for ($i = 0; $i < $blockAlign; ++$i) { $this->_samples[$offset + $i] = $sampleBlock[$i]; } } return $this; }
[ "public", "function", "setSampleBlock", "(", "$", "sampleBlock", ",", "$", "blockNum", ")", "{", "// check preconditions", "$", "blockAlign", "=", "$", "this", "->", "_blockAlign", ";", "if", "(", "!", "isset", "(", "$", "sampleBlock", "[", "$", "blockAlign"...
Set a single sample block. <br /> Allows to append a sample block. @param string $sampleBlock (Required) The binary sample block (all channels). @param int $blockNum (Required) The sample block number. Zero based. @throws WavFileException
[ "Set", "a", "single", "sample", "block", ".", "<br", "/", ">", "Allows", "to", "append", "a", "sample", "block", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1378-L1413
dapphp/securimage
WavFile.php
WavFile.getSampleValue
public function getSampleValue($blockNum, $channelNum) { // check preconditions if ($channelNum < 1 || $channelNum > $this->_numChannels) { throw new WavFileException('Channel number is out of range.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $sampleBytes = $this->_bitsPerSample / 8; $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes; if ($offset + $sampleBytes > $this->_dataSize || $offset < 0) { return null; } // read binary value $sampleBinary = substr($this->_samples, $offset, $sampleBytes); // convert binary to value switch ($this->_bitsPerSample) { case 8: // unsigned char return (float)((ord($sampleBinary) - 0x80) / 0x80); case 16: // signed short, little endian $data = unpack('v', $sampleBinary); $sample = $data[1]; if ($sample >= 0x8000) { $sample -= 0x10000; } return (float)($sample / 0x8000); case 24: // 3 byte packed signed integer, little endian $data = unpack('C3', $sampleBinary); $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16); if ($sample >= 0x800000) { $sample -= 0x1000000; } return (float)($sample / 0x800000); case 32: // 32-bit float $data = unpack('f', $sampleBinary); return (float)$data[1]; default: return null; } }
php
public function getSampleValue($blockNum, $channelNum) { // check preconditions if ($channelNum < 1 || $channelNum > $this->_numChannels) { throw new WavFileException('Channel number is out of range.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $sampleBytes = $this->_bitsPerSample / 8; $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes; if ($offset + $sampleBytes > $this->_dataSize || $offset < 0) { return null; } // read binary value $sampleBinary = substr($this->_samples, $offset, $sampleBytes); // convert binary to value switch ($this->_bitsPerSample) { case 8: // unsigned char return (float)((ord($sampleBinary) - 0x80) / 0x80); case 16: // signed short, little endian $data = unpack('v', $sampleBinary); $sample = $data[1]; if ($sample >= 0x8000) { $sample -= 0x10000; } return (float)($sample / 0x8000); case 24: // 3 byte packed signed integer, little endian $data = unpack('C3', $sampleBinary); $sample = $data[1] | ($data[2] << 8) | ($data[3] << 16); if ($sample >= 0x800000) { $sample -= 0x1000000; } return (float)($sample / 0x800000); case 32: // 32-bit float $data = unpack('f', $sampleBinary); return (float)$data[1]; default: return null; } }
[ "public", "function", "getSampleValue", "(", "$", "blockNum", ",", "$", "channelNum", ")", "{", "// check preconditions", "if", "(", "$", "channelNum", "<", "1", "||", "$", "channelNum", ">", "$", "this", "->", "_numChannels", ")", "{", "throw", "new", "Wa...
Get a float sample value for a specific sample block and channel number. @param int $blockNum (Required) The sample block number to fetch. Zero based. @param int $channelNum (Required) The channel number within the sample block to fetch. First channel is 1. @return float|null The float sample value. Returns null if the sample block number was out of range. @throws WavFileException
[ "Get", "a", "float", "sample", "value", "for", "a", "specific", "sample", "block", "and", "channel", "number", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1423-L1475
dapphp/securimage
WavFile.php
WavFile.setSampleValue
public function setSampleValue($sampleFloat, $blockNum, $channelNum) { // check preconditions if ($channelNum < 1 || $channelNum > $this->_numChannels) { throw new WavFileException('Channel number is out of range.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $dataSize = $this->_dataSize; $bitsPerSample = $this->_bitsPerSample; $sampleBytes = $bitsPerSample / 8; $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes; if (($offset + $sampleBytes > $dataSize && $offset != $dataSize) || $offset < 0) { // allow appending throw new WavFileException('Sample block or channel number is out of range.'); } // convert to value, quantize and clip if ($bitsPerSample == 32) { $sample = $sampleFloat < -1.0 ? -1.0 : ($sampleFloat > 1.0 ? 1.0 : $sampleFloat); } else { $p = 1 << ($bitsPerSample - 1); // 2 to the power of _bitsPerSample divided by 2 // project and quantize (round) float to integer values $sample = $sampleFloat < 0 ? (int)($sampleFloat * $p - 0.5) : (int)($sampleFloat * $p + 0.5); // clip if necessary to [-$p, $p - 1] if ($sample < -$p) { $sample = -$p; } elseif ($sample > $p - 1) { $sample = $p - 1; } } // convert to binary switch ($bitsPerSample) { case 8: // unsigned char $sampleBinary = chr($sample + 0x80); break; case 16: // signed short, little endian if ($sample < 0) { $sample += 0x10000; } $sampleBinary = pack('v', $sample); break; case 24: // 3 byte packed signed integer, little endian if ($sample < 0) { $sample += 0x1000000; } $sampleBinary = pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff); break; case 32: // 32-bit float $sampleBinary = pack('f', $sample); break; default: $sampleBinary = null; $sampleBytes = 0; break; } // replace or append data if ($offset == $dataSize) { // append $this->_samples .= $sampleBinary; $this->_dataSize += $sampleBytes; $this->_chunkSize += $sampleBytes; $this->_actualSize += $sampleBytes; $this->_numBlocks = (int)($this->_dataSize / $this->_blockAlign); } else { // replace for ($i = 0; $i < $sampleBytes; ++$i) { $this->_samples{$offset + $i} = $sampleBinary{$i}; } } return $this; }
php
public function setSampleValue($sampleFloat, $blockNum, $channelNum) { // check preconditions if ($channelNum < 1 || $channelNum > $this->_numChannels) { throw new WavFileException('Channel number is out of range.'); } if (!$this->_dataSize_valid) { $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() } $dataSize = $this->_dataSize; $bitsPerSample = $this->_bitsPerSample; $sampleBytes = $bitsPerSample / 8; $offset = $blockNum * $this->_blockAlign + ($channelNum - 1) * $sampleBytes; if (($offset + $sampleBytes > $dataSize && $offset != $dataSize) || $offset < 0) { // allow appending throw new WavFileException('Sample block or channel number is out of range.'); } // convert to value, quantize and clip if ($bitsPerSample == 32) { $sample = $sampleFloat < -1.0 ? -1.0 : ($sampleFloat > 1.0 ? 1.0 : $sampleFloat); } else { $p = 1 << ($bitsPerSample - 1); // 2 to the power of _bitsPerSample divided by 2 // project and quantize (round) float to integer values $sample = $sampleFloat < 0 ? (int)($sampleFloat * $p - 0.5) : (int)($sampleFloat * $p + 0.5); // clip if necessary to [-$p, $p - 1] if ($sample < -$p) { $sample = -$p; } elseif ($sample > $p - 1) { $sample = $p - 1; } } // convert to binary switch ($bitsPerSample) { case 8: // unsigned char $sampleBinary = chr($sample + 0x80); break; case 16: // signed short, little endian if ($sample < 0) { $sample += 0x10000; } $sampleBinary = pack('v', $sample); break; case 24: // 3 byte packed signed integer, little endian if ($sample < 0) { $sample += 0x1000000; } $sampleBinary = pack('C3', $sample & 0xff, ($sample >> 8) & 0xff, ($sample >> 16) & 0xff); break; case 32: // 32-bit float $sampleBinary = pack('f', $sample); break; default: $sampleBinary = null; $sampleBytes = 0; break; } // replace or append data if ($offset == $dataSize) { // append $this->_samples .= $sampleBinary; $this->_dataSize += $sampleBytes; $this->_chunkSize += $sampleBytes; $this->_actualSize += $sampleBytes; $this->_numBlocks = (int)($this->_dataSize / $this->_blockAlign); } else { // replace for ($i = 0; $i < $sampleBytes; ++$i) { $this->_samples{$offset + $i} = $sampleBinary{$i}; } } return $this; }
[ "public", "function", "setSampleValue", "(", "$", "sampleFloat", ",", "$", "blockNum", ",", "$", "channelNum", ")", "{", "// check preconditions", "if", "(", "$", "channelNum", "<", "1", "||", "$", "channelNum", ">", "$", "this", "->", "_numChannels", ")", ...
Sets a float sample value for a specific sample block number and channel. <br /> Converts float values to appropriate integer values and clips properly. <br /> Allows to append samples (in order). @param float $sampleFloat (Required) The float sample value to set. Converts float values and clips if necessary. @param int $blockNum (Required) The sample block number to set or append. Zero based. @param int $channelNum (Required) The channel number within the sample block to set or append. First channel is 1. @throws WavFileException
[ "Sets", "a", "float", "sample", "value", "for", "a", "specific", "sample", "block", "number", "and", "channel", ".", "<br", "/", ">", "Converts", "float", "values", "to", "appropriate", "integer", "values", "and", "clips", "properly", ".", "<br", "/", ">",...
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1487-L1574
dapphp/securimage
WavFile.php
WavFile.filter
public function filter($filters, $blockOffset = 0, $numBlocks = null) { // check preconditions $totalBlocks = $this->getNumBlocks(); $numChannels = $this->getNumChannels(); if (is_null($numBlocks)) $numBlocks = $totalBlocks - $blockOffset; if (!is_array($filters) || empty($filters) || $blockOffset < 0 || $blockOffset > $totalBlocks || $numBlocks <= 0) { // nothing to do return $this; } // check filtes $filter_mix = false; if (array_key_exists(self::FILTER_MIX, $filters)) { if (!is_array($filters[self::FILTER_MIX])) { // assume the 'wav' parameter $filters[self::FILTER_MIX] = array('wav' => $filters[self::FILTER_MIX]); } $mix_wav = @$filters[self::FILTER_MIX]['wav']; if (!($mix_wav instanceof WavFile)) { throw new WavFileException("WavFile to mix is missing or invalid."); } elseif ($mix_wav->getSampleRate() != $this->getSampleRate()) { throw new WavFileException("Sample rate of WavFile to mix does not match."); } else if ($mix_wav->getNumChannels() != $this->getNumChannels()) { throw new WavFileException("Number of channels of WavFile to mix does not match."); } $mix_loop = @$filters[self::FILTER_MIX]['loop']; if (is_null($mix_loop)) $mix_loop = false; $mix_blockOffset = @$filters[self::FILTER_MIX]['blockOffset']; if (is_null($mix_blockOffset)) $mix_blockOffset = 0; $mix_totalBlocks = $mix_wav->getNumBlocks(); $mix_numBlocks = @$filters[self::FILTER_MIX]['numBlocks']; if (is_null($mix_numBlocks)) $mix_numBlocks = $mix_loop ? $mix_totalBlocks : $mix_totalBlocks - $mix_blockOffset; $mix_maxBlock = min($mix_blockOffset + $mix_numBlocks, $mix_totalBlocks); $filter_mix = true; } $filter_normalize = false; if (array_key_exists(self::FILTER_NORMALIZE, $filters)) { $normalize_threshold = @$filters[self::FILTER_NORMALIZE]; if (!is_null($normalize_threshold) && abs($normalize_threshold) != 1) $filter_normalize = true; } $filter_degrade = false; if (array_key_exists(self::FILTER_DEGRADE, $filters)) { $degrade_quality = @$filters[self::FILTER_DEGRADE]; if (is_null($degrade_quality)) $degrade_quality = 1; if ($degrade_quality >= 0 && $degrade_quality < 1) $filter_degrade = true; } $filter_vol = false; if (array_key_exists(self::FILTER_VOLUME, $filters)) { $volume_amount = @$filters[self::FILTER_VOLUME]; if (is_null($volume_amount)) $volume_amount = 1; if ($volume_amount >= 0 && $volume_amount <= 2 && $volume_amount != 1.0) { $filter_vol = true; } } // loop through all sample blocks for ($block = 0; $block < $numBlocks; ++$block) { // loop through all channels for ($channel = 1; $channel <= $numChannels; ++$channel) { // read current sample $currentBlock = $blockOffset + $block; $sampleFloat = $this->getSampleValue($currentBlock, $channel); /************* MIX FILTER ***********************/ if ($filter_mix) { if ($mix_loop) { $mixBlock = ($mix_blockOffset + ($block % $mix_numBlocks)) % $mix_totalBlocks; } else { $mixBlock = $mix_blockOffset + $block; } if ($mixBlock < $mix_maxBlock) { $sampleFloat += $mix_wav->getSampleValue($mixBlock, $channel); } } /************* NORMALIZE FILTER *******************/ if ($filter_normalize) { $sampleFloat = $this->normalizeSample($sampleFloat, $normalize_threshold); } /************* DEGRADE FILTER *******************/ if ($filter_degrade) { $sampleFloat += rand(1000000 * ($degrade_quality - 1), 1000000 * (1 - $degrade_quality)) / 1000000; } /************* VOLUME FILTER *******************/ if ($filter_vol) { $sampleFloat *= $volume_amount; } // write current sample $this->setSampleValue($sampleFloat, $currentBlock, $channel); } } return $this; }
php
public function filter($filters, $blockOffset = 0, $numBlocks = null) { // check preconditions $totalBlocks = $this->getNumBlocks(); $numChannels = $this->getNumChannels(); if (is_null($numBlocks)) $numBlocks = $totalBlocks - $blockOffset; if (!is_array($filters) || empty($filters) || $blockOffset < 0 || $blockOffset > $totalBlocks || $numBlocks <= 0) { // nothing to do return $this; } // check filtes $filter_mix = false; if (array_key_exists(self::FILTER_MIX, $filters)) { if (!is_array($filters[self::FILTER_MIX])) { // assume the 'wav' parameter $filters[self::FILTER_MIX] = array('wav' => $filters[self::FILTER_MIX]); } $mix_wav = @$filters[self::FILTER_MIX]['wav']; if (!($mix_wav instanceof WavFile)) { throw new WavFileException("WavFile to mix is missing or invalid."); } elseif ($mix_wav->getSampleRate() != $this->getSampleRate()) { throw new WavFileException("Sample rate of WavFile to mix does not match."); } else if ($mix_wav->getNumChannels() != $this->getNumChannels()) { throw new WavFileException("Number of channels of WavFile to mix does not match."); } $mix_loop = @$filters[self::FILTER_MIX]['loop']; if (is_null($mix_loop)) $mix_loop = false; $mix_blockOffset = @$filters[self::FILTER_MIX]['blockOffset']; if (is_null($mix_blockOffset)) $mix_blockOffset = 0; $mix_totalBlocks = $mix_wav->getNumBlocks(); $mix_numBlocks = @$filters[self::FILTER_MIX]['numBlocks']; if (is_null($mix_numBlocks)) $mix_numBlocks = $mix_loop ? $mix_totalBlocks : $mix_totalBlocks - $mix_blockOffset; $mix_maxBlock = min($mix_blockOffset + $mix_numBlocks, $mix_totalBlocks); $filter_mix = true; } $filter_normalize = false; if (array_key_exists(self::FILTER_NORMALIZE, $filters)) { $normalize_threshold = @$filters[self::FILTER_NORMALIZE]; if (!is_null($normalize_threshold) && abs($normalize_threshold) != 1) $filter_normalize = true; } $filter_degrade = false; if (array_key_exists(self::FILTER_DEGRADE, $filters)) { $degrade_quality = @$filters[self::FILTER_DEGRADE]; if (is_null($degrade_quality)) $degrade_quality = 1; if ($degrade_quality >= 0 && $degrade_quality < 1) $filter_degrade = true; } $filter_vol = false; if (array_key_exists(self::FILTER_VOLUME, $filters)) { $volume_amount = @$filters[self::FILTER_VOLUME]; if (is_null($volume_amount)) $volume_amount = 1; if ($volume_amount >= 0 && $volume_amount <= 2 && $volume_amount != 1.0) { $filter_vol = true; } } // loop through all sample blocks for ($block = 0; $block < $numBlocks; ++$block) { // loop through all channels for ($channel = 1; $channel <= $numChannels; ++$channel) { // read current sample $currentBlock = $blockOffset + $block; $sampleFloat = $this->getSampleValue($currentBlock, $channel); /************* MIX FILTER ***********************/ if ($filter_mix) { if ($mix_loop) { $mixBlock = ($mix_blockOffset + ($block % $mix_numBlocks)) % $mix_totalBlocks; } else { $mixBlock = $mix_blockOffset + $block; } if ($mixBlock < $mix_maxBlock) { $sampleFloat += $mix_wav->getSampleValue($mixBlock, $channel); } } /************* NORMALIZE FILTER *******************/ if ($filter_normalize) { $sampleFloat = $this->normalizeSample($sampleFloat, $normalize_threshold); } /************* DEGRADE FILTER *******************/ if ($filter_degrade) { $sampleFloat += rand(1000000 * ($degrade_quality - 1), 1000000 * (1 - $degrade_quality)) / 1000000; } /************* VOLUME FILTER *******************/ if ($filter_vol) { $sampleFloat *= $volume_amount; } // write current sample $this->setSampleValue($sampleFloat, $currentBlock, $channel); } } return $this; }
[ "public", "function", "filter", "(", "$", "filters", ",", "$", "blockOffset", "=", "0", ",", "$", "numBlocks", "=", "null", ")", "{", "// check preconditions", "$", "totalBlocks", "=", "$", "this", "->", "getNumBlocks", "(", ")", ";", "$", "numChannels", ...
Run samples through audio processing filters. <code> $wav->filter( array( WavFile::FILTER_MIX => array( // Filter for mixing 2 WavFile instances. 'wav' => $wav2, // (Required) The WavFile to mix into this WhavFile. If no optional arguments are given, can be passed without the array. 'loop' => true, // (Optional) Loop the selected portion (with warping to the beginning at the end). 'blockOffset' => 0, // (Optional) Block number to start mixing from. 'numBlocks' => null // (Optional) Number of blocks to mix in or to select for looping. Defaults to the end or all data for looping. ), WavFile::FILTER_NORMALIZE => 0.6, // (Required) Normalization of (mixed) audio samples - see threshold parameter for normalizeSample(). WavFile::FILTER_DEGRADE => 0.9 // (Required) Introduce random noise. The quality relative to the amplitude. 1 = no noise, 0 = max. noise. WavFile::FILTER_VOLUME => 1.0 // (Required) Amplify or attenuate the audio signal. Beware of clipping when amplifying. Values range from >= 0 - <= 2. 1 = no change in volume; 0.5 = 50% reduction of volume; 1.5 = 150% increase in volume. ), 0, // (Optional) The block number of this WavFile to start with. null // (Optional) The number of blocks to process. ); </code> @param array $filters (Required) An array of 1 or more audio processing filters. @param int $blockOffset (Optional) The block number to start precessing from. @param int $numBlocks (Optional) The maximum number of blocks to process. @throws WavFileException
[ "Run", "samples", "through", "audio", "processing", "filters", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1606-L1718
dapphp/securimage
WavFile.php
WavFile.appendWav
public function appendWav(WavFile $wav) { // basic checks if ($wav->getSampleRate() != $this->getSampleRate()) { throw new WavFileException("Sample rate for wav files do not match."); } else if ($wav->getBitsPerSample() != $this->getBitsPerSample()) { throw new WavFileException("Bits per sample for wav files do not match."); } else if ($wav->getNumChannels() != $this->getNumChannels()) { throw new WavFileException("Number of channels for wav files do not match."); } $this->_samples .= $wav->_samples; $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
php
public function appendWav(WavFile $wav) { // basic checks if ($wav->getSampleRate() != $this->getSampleRate()) { throw new WavFileException("Sample rate for wav files do not match."); } else if ($wav->getBitsPerSample() != $this->getBitsPerSample()) { throw new WavFileException("Bits per sample for wav files do not match."); } else if ($wav->getNumChannels() != $this->getNumChannels()) { throw new WavFileException("Number of channels for wav files do not match."); } $this->_samples .= $wav->_samples; $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
[ "public", "function", "appendWav", "(", "WavFile", "$", "wav", ")", "{", "// basic checks", "if", "(", "$", "wav", "->", "getSampleRate", "(", ")", "!=", "$", "this", "->", "getSampleRate", "(", ")", ")", "{", "throw", "new", "WavFileException", "(", "\"...
Append a wav file to the current wav. <br /> The wav files must have the same sample rate, number of bits per sample, and number of channels. @param WavFile $wav (Required) The wav file to append. @throws WavFileException
[ "Append", "a", "wav", "file", "to", "the", "current", "wav", ".", "<br", "/", ">", "The", "wav", "files", "must", "have", "the", "same", "sample", "rate", "number", "of", "bits", "per", "sample", "and", "number", "of", "channels", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1727-L1741
dapphp/securimage
WavFile.php
WavFile.mergeWav
public function mergeWav(WavFile $wav, $normalizeThreshold = null) { return $this->filter(array( WavFile::FILTER_MIX => $wav, WavFile::FILTER_NORMALIZE => $normalizeThreshold )); }
php
public function mergeWav(WavFile $wav, $normalizeThreshold = null) { return $this->filter(array( WavFile::FILTER_MIX => $wav, WavFile::FILTER_NORMALIZE => $normalizeThreshold )); }
[ "public", "function", "mergeWav", "(", "WavFile", "$", "wav", ",", "$", "normalizeThreshold", "=", "null", ")", "{", "return", "$", "this", "->", "filter", "(", "array", "(", "WavFile", "::", "FILTER_MIX", "=>", "$", "wav", ",", "WavFile", "::", "FILTER_...
Mix 2 wav files together. <br /> Both wavs must have the same sample rate and same number of channels. @param WavFile $wav (Required) The WavFile to mix. @param float $normalizeThreshold (Optional) See normalizeSample for an explanation. @throws WavFileException
[ "Mix", "2", "wav", "files", "together", ".", "<br", "/", ">", "Both", "wavs", "must", "have", "the", "same", "sample", "rate", "and", "same", "number", "of", "channels", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1751-L1756
dapphp/securimage
WavFile.php
WavFile.insertSilence
public function insertSilence($duration = 1.0) { $numSamples = (int)($this->getSampleRate() * abs($duration)); $numChannels = $this->getNumChannels(); $data = str_repeat(self::packSample($this->getZeroAmplitude(), $this->getBitsPerSample()), $numSamples * $numChannels); if ($duration >= 0) { $this->_samples .= $data; } else { $this->_samples = $data . $this->_samples; } $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
php
public function insertSilence($duration = 1.0) { $numSamples = (int)($this->getSampleRate() * abs($duration)); $numChannels = $this->getNumChannels(); $data = str_repeat(self::packSample($this->getZeroAmplitude(), $this->getBitsPerSample()), $numSamples * $numChannels); if ($duration >= 0) { $this->_samples .= $data; } else { $this->_samples = $data . $this->_samples; } $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
[ "public", "function", "insertSilence", "(", "$", "duration", "=", "1.0", ")", "{", "$", "numSamples", "=", "(", "int", ")", "(", "$", "this", "->", "getSampleRate", "(", ")", "*", "abs", "(", "$", "duration", ")", ")", ";", "$", "numChannels", "=", ...
Add silence to the wav file. @param float $duration (Optional) How many seconds of silence. If negative, add to the beginning of the file. Defaults to 1s.
[ "Add", "silence", "to", "the", "wav", "file", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1763-L1778
dapphp/securimage
WavFile.php
WavFile.generateNoise
public function generateNoise($duration = 1.0, $percent = 100) { $numChannels = $this->getNumChannels(); $numSamples = $this->getSampleRate() * $duration; $minAmp = $this->getMinAmplitude(); $maxAmp = $this->getMaxAmplitude(); $bitDepth = $this->getBitsPerSample(); for ($s = 0; $s < $numSamples; ++$s) { if ($bitDepth == 32) { $val = rand(-$percent * 10000, $percent * 10000) / 1000000; } else { $val = rand($minAmp, $maxAmp); $val = (int)($val * $percent / 100); } $this->_samples .= str_repeat(self::packSample($val, $bitDepth), $numChannels); } $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
php
public function generateNoise($duration = 1.0, $percent = 100) { $numChannels = $this->getNumChannels(); $numSamples = $this->getSampleRate() * $duration; $minAmp = $this->getMinAmplitude(); $maxAmp = $this->getMaxAmplitude(); $bitDepth = $this->getBitsPerSample(); for ($s = 0; $s < $numSamples; ++$s) { if ($bitDepth == 32) { $val = rand(-$percent * 10000, $percent * 10000) / 1000000; } else { $val = rand($minAmp, $maxAmp); $val = (int)($val * $percent / 100); } $this->_samples .= str_repeat(self::packSample($val, $bitDepth), $numChannels); } $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
[ "public", "function", "generateNoise", "(", "$", "duration", "=", "1.0", ",", "$", "percent", "=", "100", ")", "{", "$", "numChannels", "=", "$", "this", "->", "getNumChannels", "(", ")", ";", "$", "numSamples", "=", "$", "this", "->", "getSampleRate", ...
Generate noise at the end of the wav for the specified duration and volume. @param float $duration (Optional) Number of seconds of noise to generate. @param float $percent (Optional) The percentage of the maximum amplitude to use. 100 = full amplitude.
[ "Generate", "noise", "at", "the", "end", "of", "the", "wav", "for", "the", "specified", "duration", "and", "volume", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1798-L1820
dapphp/securimage
WavFile.php
WavFile.convertBitsPerSample
public function convertBitsPerSample($bitsPerSample) { if ($this->getBitsPerSample() == $bitsPerSample) { return $this; } $tempWav = new WavFile($this->getNumChannels(), $this->getSampleRate(), $bitsPerSample); $tempWav->filter( array(self::FILTER_MIX => $this), 0, $this->getNumBlocks() ); $this->setSamples() // implicit setDataSize(), setSize(), setActualSize(), setNumBlocks() ->setBitsPerSample($bitsPerSample); // implicit setValidBitsPerSample(), setAudioFormat(), setAudioSubFormat(), setFmtChunkSize(), setFactChunkSize(), setSize(), setActualSize(), setDataOffset(), setByteRate(), setBlockAlign(), setNumBlocks() $this->_samples = $tempWav->_samples; $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
php
public function convertBitsPerSample($bitsPerSample) { if ($this->getBitsPerSample() == $bitsPerSample) { return $this; } $tempWav = new WavFile($this->getNumChannels(), $this->getSampleRate(), $bitsPerSample); $tempWav->filter( array(self::FILTER_MIX => $this), 0, $this->getNumBlocks() ); $this->setSamples() // implicit setDataSize(), setSize(), setActualSize(), setNumBlocks() ->setBitsPerSample($bitsPerSample); // implicit setValidBitsPerSample(), setAudioFormat(), setAudioSubFormat(), setFmtChunkSize(), setFactChunkSize(), setSize(), setActualSize(), setDataOffset(), setByteRate(), setBlockAlign(), setNumBlocks() $this->_samples = $tempWav->_samples; $this->setDataSize(); // implicit setSize(), setActualSize(), setNumBlocks() return $this; }
[ "public", "function", "convertBitsPerSample", "(", "$", "bitsPerSample", ")", "{", "if", "(", "$", "this", "->", "getBitsPerSample", "(", ")", "==", "$", "bitsPerSample", ")", "{", "return", "$", "this", ";", "}", "$", "tempWav", "=", "new", "WavFile", "...
Convert sample data to different bits per sample. @param int $bitsPerSample (Required) The new number of bits per sample; @throws WavFileException
[ "Convert", "sample", "data", "to", "different", "bits", "per", "sample", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1828-L1846
dapphp/securimage
WavFile.php
WavFile.displayInfo
public function displayInfo() { $s = "File Size: %u\n" ."Chunk Size: %u\n" ."fmt Subchunk Size: %u\n" ."Extended fmt Size: %u\n" ."fact Subchunk Size: %u\n" ."Data Offset: %u\n" ."Data Size: %u\n" ."Audio Format: %s\n" ."Audio SubFormat: %s\n" ."Channels: %u\n" ."Channel Mask: 0x%s\n" ."Sample Rate: %u\n" ."Bits Per Sample: %u\n" ."Valid Bits Per Sample: %u\n" ."Sample Block Size: %u\n" ."Number of Sample Blocks: %u\n" ."Byte Rate: %uBps\n"; $s = sprintf($s, $this->getActualSize(), $this->getChunkSize(), $this->getFmtChunkSize(), $this->getFmtExtendedSize(), $this->getFactChunkSize(), $this->getDataOffset(), $this->getDataSize(), $this->getAudioFormat() == self::WAVE_FORMAT_PCM ? 'PCM' : ($this->getAudioFormat() == self::WAVE_FORMAT_IEEE_FLOAT ? 'IEEE FLOAT' : 'EXTENSIBLE'), $this->getAudioSubFormat() == self::WAVE_SUBFORMAT_PCM ? 'PCM' : 'IEEE FLOAT', $this->getNumChannels(), dechex($this->getChannelMask()), $this->getSampleRate(), $this->getBitsPerSample(), $this->getValidBitsPerSample(), $this->getBlockAlign(), $this->getNumBlocks(), $this->getByteRate()); if (php_sapi_name() == 'cli') { return $s; } else { return nl2br($s); } }
php
public function displayInfo() { $s = "File Size: %u\n" ."Chunk Size: %u\n" ."fmt Subchunk Size: %u\n" ."Extended fmt Size: %u\n" ."fact Subchunk Size: %u\n" ."Data Offset: %u\n" ."Data Size: %u\n" ."Audio Format: %s\n" ."Audio SubFormat: %s\n" ."Channels: %u\n" ."Channel Mask: 0x%s\n" ."Sample Rate: %u\n" ."Bits Per Sample: %u\n" ."Valid Bits Per Sample: %u\n" ."Sample Block Size: %u\n" ."Number of Sample Blocks: %u\n" ."Byte Rate: %uBps\n"; $s = sprintf($s, $this->getActualSize(), $this->getChunkSize(), $this->getFmtChunkSize(), $this->getFmtExtendedSize(), $this->getFactChunkSize(), $this->getDataOffset(), $this->getDataSize(), $this->getAudioFormat() == self::WAVE_FORMAT_PCM ? 'PCM' : ($this->getAudioFormat() == self::WAVE_FORMAT_IEEE_FLOAT ? 'IEEE FLOAT' : 'EXTENSIBLE'), $this->getAudioSubFormat() == self::WAVE_SUBFORMAT_PCM ? 'PCM' : 'IEEE FLOAT', $this->getNumChannels(), dechex($this->getChannelMask()), $this->getSampleRate(), $this->getBitsPerSample(), $this->getValidBitsPerSample(), $this->getBlockAlign(), $this->getNumBlocks(), $this->getByteRate()); if (php_sapi_name() == 'cli') { return $s; } else { return nl2br($s); } }
[ "public", "function", "displayInfo", "(", ")", "{", "$", "s", "=", "\"File Size: %u\\n\"", ".", "\"Chunk Size: %u\\n\"", ".", "\"fmt Subchunk Size: %u\\n\"", ".", "\"Extended fmt Size: %u\\n\"", ".", "\"fact Subchunk Size: %u\\n\"", ".", "\"Data Offset: %u\\n\"", ".", "\"Da...
Output information about the wav object.
[ "Output", "information", "about", "the", "wav", "object", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/WavFile.php#L1855-L1898
dapphp/securimage
securimage.php
Securimage.getCaptchaId
public static function getCaptchaId($new = true, array $options = array()) { if (is_null($new) || (bool)$new == true) { $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true)); $opts = array('no_session' => true, 'use_database' => true); if (sizeof($options) > 0) $opts = array_merge($options, $opts); $si = new self($opts); Securimage::$_captchaId = $id; $si->createCode(); return $id; } else { return Securimage::$_captchaId; } }
php
public static function getCaptchaId($new = true, array $options = array()) { if (is_null($new) || (bool)$new == true) { $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true)); $opts = array('no_session' => true, 'use_database' => true); if (sizeof($options) > 0) $opts = array_merge($options, $opts); $si = new self($opts); Securimage::$_captchaId = $id; $si->createCode(); return $id; } else { return Securimage::$_captchaId; } }
[ "public", "static", "function", "getCaptchaId", "(", "$", "new", "=", "true", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "if", "(", "is_null", "(", "$", "new", ")", "||", "(", "bool", ")", "$", "new", "==", "true", ")", "{", ...
Generate a new captcha ID or retrieve the current ID (if exists). @param bool $new If true, generates a new challenge and returns and ID. If false, the existing captcha ID is returned, or null if none exists. @param array $options Additional options to be passed to Securimage. $options must include database settings if they are not set directly in securimage.php @return null|string Returns null if no captcha id set and new was false, or the captcha ID
[ "Generate", "a", "new", "captcha", "ID", "or", "retrieve", "the", "current", "ID", "(", "if", "exists", ")", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1175-L1190
dapphp/securimage
securimage.php
Securimage.checkByCaptchaId
public static function checkByCaptchaId($id, $value, array $options = array()) { $opts = array('captchaId' => $id, 'no_session' => true, 'use_database' => true); if (sizeof($options) > 0) $opts = array_merge($options, $opts); $si = new self($opts); if ($si->openDatabase()) { $code = $si->getCodeFromDatabase(); if (is_array($code)) { $si->code = $code['code']; $si->code_display = $code['code_disp']; } if ($si->check($value)) { $si->clearCodeFromDatabase(); return true; } else { return false; } } else { return false; } }
php
public static function checkByCaptchaId($id, $value, array $options = array()) { $opts = array('captchaId' => $id, 'no_session' => true, 'use_database' => true); if (sizeof($options) > 0) $opts = array_merge($options, $opts); $si = new self($opts); if ($si->openDatabase()) { $code = $si->getCodeFromDatabase(); if (is_array($code)) { $si->code = $code['code']; $si->code_display = $code['code_disp']; } if ($si->check($value)) { $si->clearCodeFromDatabase(); return true; } else { return false; } } else { return false; } }
[ "public", "static", "function", "checkByCaptchaId", "(", "$", "id", ",", "$", "value", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "opts", "=", "array", "(", "'captchaId'", "=>", "$", "id", ",", "'no_session'", "=>", "true", ...
Validate a captcha code input against a captcha ID @param string $id The captcha ID to check @param string $value The captcha value supplied by the user @param array $options Array of options to construct Securimage with. Options must include database options if they are not set in securimage.php @see Securimage::$database_driver @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open
[ "Validate", "a", "captcha", "code", "input", "against", "a", "captcha", "ID" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1203-L1231
dapphp/securimage
securimage.php
Securimage.show
public function show($background_image = '') { set_error_handler(array(&$this, 'errorHandler')); if($background_image != '' && is_readable($background_image)) { $this->bgimg = $background_image; } $this->doImage(); }
php
public function show($background_image = '') { set_error_handler(array(&$this, 'errorHandler')); if($background_image != '' && is_readable($background_image)) { $this->bgimg = $background_image; } $this->doImage(); }
[ "public", "function", "show", "(", "$", "background_image", "=", "''", ")", "{", "set_error_handler", "(", "array", "(", "&", "$", "this", ",", "'errorHandler'", ")", ")", ";", "if", "(", "$", "background_image", "!=", "''", "&&", "is_readable", "(", "$"...
Generates a new challenge and serves a captcha image. Appropriate headers will be sent to the browser unless the *send_headers* option is false. @param string $background_image The absolute or relative path to the background image to use as the background of the captcha image. $img = new Securimage(); $img->code_length = 6; $img->num_lines = 5; $img->noise_level = 5; $img->show(); // sends the image and appropriate headers to browser exit;
[ "Generates", "a", "new", "challenge", "and", "serves", "a", "captcha", "image", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1249-L1258
dapphp/securimage
securimage.php
Securimage.check
public function check($code) { if (!is_string($code)) { trigger_error("The \$code parameter passed to Securimage::check() must be a string, " . gettype($code) . " given", E_USER_NOTICE); $code = ''; } $this->code_entered = $code; $this->validate(); return $this->correct_code; }
php
public function check($code) { if (!is_string($code)) { trigger_error("The \$code parameter passed to Securimage::check() must be a string, " . gettype($code) . " given", E_USER_NOTICE); $code = ''; } $this->code_entered = $code; $this->validate(); return $this->correct_code; }
[ "public", "function", "check", "(", "$", "code", ")", "{", "if", "(", "!", "is_string", "(", "$", "code", ")", ")", "{", "trigger_error", "(", "\"The \\$code parameter passed to Securimage::check() must be a string, \"", ".", "gettype", "(", "$", "code", ")", "....
Checks a given code against the correct value from the session and/or database. @param string $code The captcha code to check $code = $_POST['code']; $img = new Securimage(); if ($img->check($code) == true) { $captcha_valid = true; } else { $captcha_valid = false; } @return bool true if the given code was correct, false if not.
[ "Checks", "a", "given", "code", "against", "the", "correct", "value", "from", "the", "session", "and", "/", "or", "database", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1275-L1285
dapphp/securimage
securimage.php
Securimage.getCaptchaHtml
public static function getCaptchaHtml($options = array(), $parts = Securimage::HTML_ALL) { static $javascript_init = false; if (!isset($options['securimage_path'])) { $docroot = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME'])); $docroot = realpath($docroot); $sipath = dirname(__FILE__); $securimage_path = str_replace($docroot, '', $sipath); } else { $securimage_path = $options['securimage_path']; } $show_image_url = (isset($options['show_image_url'])) ? $options['show_image_url'] : null; $image_id = (isset($options['image_id'])) ? $options['image_id'] : 'captcha_image'; $image_alt = (isset($options['image_alt_text'])) ? $options['image_alt_text'] : 'CAPTCHA Image'; $show_audio_btn = (isset($options['show_audio_button'])) ? (bool)$options['show_audio_button'] : true; $disable_flash_fbk = (isset($options['disable_flash_fallback'])) ? (bool)$options['disable_flash_fallback'] : false; $show_refresh_btn = (isset($options['show_refresh_button'])) ? (bool)$options['show_refresh_button'] : true; $refresh_icon_url = (isset($options['refresh_icon_url'])) ? $options['refresh_icon_url'] : null; $audio_but_bg_col = (isset($options['audio_button_bgcol'])) ? $options['audio_button_bgcol'] : '#ffffff'; $audio_icon_url = (isset($options['audio_icon_url'])) ? $options['audio_icon_url'] : null; $loading_icon_url = (isset($options['loading_icon_url'])) ? $options['loading_icon_url'] : null; $icon_size = (isset($options['icon_size'])) ? $options['icon_size'] : 32; $audio_play_url = (isset($options['audio_play_url'])) ? $options['audio_play_url'] : null; $audio_swf_url = (isset($options['audio_swf_url'])) ? $options['audio_swf_url'] : null; $show_input = (isset($options['show_text_input'])) ? (bool)$options['show_text_input'] : true; $refresh_alt = (isset($options['refresh_alt_text'])) ? $options['refresh_alt_text'] : 'Refresh Image'; $refresh_title = (isset($options['refresh_title_text'])) ? $options['refresh_title_text'] : 'Refresh Image'; $input_text = (isset($options['input_text'])) ? $options['input_text'] : 'Type the text:'; $input_id = (isset($options['input_id'])) ? $options['input_id'] : 'captcha_code'; $input_name = (isset($options['input_name'])) ? $options['input_name'] : $input_id; $input_attrs = (isset($options['input_attributes'])) ? $options['input_attributes'] : array(); $image_attrs = (isset($options['image_attributes'])) ? $options['image_attributes'] : array(); $error_html = (isset($options['error_html'])) ? $options['error_html'] : null; $namespace = (isset($options['namespace'])) ? $options['namespace'] : ''; $rand = md5(uniqid($_SERVER['REMOTE_PORT'], true)); $securimage_path = rtrim($securimage_path, '/\\'); $securimage_path = str_replace('\\', '/', $securimage_path); $image_attr = ''; if (!is_array($image_attrs)) $image_attrs = array(); if (!isset($image_attrs['style'])) $image_attrs['style'] = 'float: left; padding-right: 5px'; $image_attrs['id'] = $image_id; $show_path = $securimage_path . '/securimage_show.php?'; if ($show_image_url) { if (parse_url($show_image_url, PHP_URL_QUERY)) { $show_path = "{$show_image_url}&"; } else { $show_path = "{$show_image_url}?"; } } if (!empty($namespace)) { $show_path .= sprintf('namespace=%s&amp;', $namespace); } $image_attrs['src'] = $show_path . $rand; $image_attrs['alt'] = $image_alt; foreach($image_attrs as $name => $val) { $image_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); } $swf_path = $securimage_path . '/securimage_play.swf'; $play_path = $securimage_path . '/securimage_play.php?'; $icon_path = $securimage_path . '/images/audio_icon.png'; $load_path = $securimage_path . '/images/loading.png'; $js_path = $securimage_path . '/securimage.js'; if (!empty($audio_icon_url)) { $icon_path = $audio_icon_url; } if (!empty($loading_icon_url)) { $load_path = $loading_icon_url; } if (!empty($audio_play_url)) { if (parse_url($audio_play_url, PHP_URL_QUERY)) { $play_path = "{$audio_play_url}&"; } else { $play_path = "{$audio_play_url}?"; } } if (!empty($namespace)) { $play_path .= sprintf('namespace=%s&amp;', $namespace); } if (!empty($audio_swf_url)) { $swf_path = $audio_swf_url; } $audio_obj = $image_id . '_audioObj'; $html = ''; if ( ($parts & Securimage::HTML_IMG) > 0) { $html .= sprintf('<img %s/>', $image_attr); } if ( ($parts & Securimage::HTML_AUDIO) > 0 && $show_audio_btn) { // html5 audio $html .= sprintf('<div id="%s_audio_div">', $image_id) . "\n" . sprintf('<audio id="%s_audio" preload="none" style="display: none">', $image_id) . "\n"; // check for existence and executability of LAME binary // prefer mp3 over wav by sourcing it first, if available if (is_executable(Securimage::$lame_binary_path)) { $html .= sprintf('<source id="%s_source_mp3" src="%sid=%s&amp;format=mp3" type="audio/mpeg">', $image_id, $play_path, uniqid()) . "\n"; } // output wav source $html .= sprintf('<source id="%s_source_wav" src="%sid=%s" type="audio/wav">', $image_id, $play_path, uniqid()) . "\n"; // flash audio button if (!$disable_flash_fbk) { $html .= sprintf('<object type="application/x-shockwave-flash" data="%s?bgcol=%s&amp;icon_file=%s&amp;audio_file=%s" height="%d" width="%d">', htmlspecialchars($swf_path), urlencode($audio_but_bg_col), urlencode($icon_path), urlencode(html_entity_decode($play_path)), $icon_size, $icon_size ); $html .= sprintf('<param name="movie" value="%s?bgcol=%s&amp;icon_file=%s&amp;audio_file=%s">', htmlspecialchars($swf_path), urlencode($audio_but_bg_col), urlencode($icon_path), urlencode(html_entity_decode($play_path)) ); $html .= '</object><br />'; } // html5 audio close $html .= "</audio>\n</div>\n"; // html5 audio controls $html .= sprintf('<div id="%s_audio_controls">', $image_id) . "\n" . sprintf('<a tabindex="-1" class="captcha_play_button" href="%sid=%s" onclick="return false">', $play_path, uniqid() ) . "\n" . sprintf('<img class="captcha_play_image" height="%d" width="%d" src="%s" alt="Play CAPTCHA Audio" style="border: 0px">', $icon_size, $icon_size, htmlspecialchars($icon_path)) . "\n" . sprintf('<img class="captcha_loading_image rotating" height="%d" width="%d" src="%s" alt="Loading audio" style="display: none">', $icon_size, $icon_size, htmlspecialchars($load_path)) . "\n" . "</a>\n<noscript>Enable Javascript for audio controls</noscript>\n" . "</div>\n"; // html5 javascript if (!$javascript_init) { $html .= sprintf('<script type="text/javascript" src="%s"></script>', $js_path) . "\n"; $javascript_init = true; } $html .= '<script type="text/javascript">' . "$audio_obj = new SecurimageAudio({ audioElement: '{$image_id}_audio', controlsElement: '{$image_id}_audio_controls' });" . "</script>\n"; } if ( ($parts & Securimage::HTML_ICON_REFRESH) > 0 && $show_refresh_btn) { $icon_path = $securimage_path . '/images/refresh.png'; if ($refresh_icon_url) { $icon_path = $refresh_icon_url; } $img_tag = sprintf('<img height="%d" width="%d" src="%s" alt="%s" onclick="this.blur()" style="border: 0px; vertical-align: bottom">', $icon_size, $icon_size, htmlspecialchars($icon_path), htmlspecialchars($refresh_alt)); $html .= sprintf('<a tabindex="-1" style="border: 0" href="#" title="%s" onclick="%sdocument.getElementById(\'%s\').src = \'%s\' + Math.random(); this.blur(); return false">%s</a><br>', htmlspecialchars($refresh_title), ($audio_obj) ? "if (typeof window.{$audio_obj} !== 'undefined') {$audio_obj}.refresh(); " : '', $image_id, $show_path, $img_tag ); } if ($parts == Securimage::HTML_ALL) { $html .= '<div style="clear: both"></div>'; } if ( ($parts & Securimage::HTML_INPUT_LABEL) > 0 && $show_input) { $html .= sprintf('<label for="%s">%s</label> ', htmlspecialchars($input_id), htmlspecialchars($input_text)); if (!empty($error_html)) { $html .= $error_html; } } if ( ($parts & Securimage::HTML_INPUT) > 0 && $show_input) { $input_attr = ''; if (!is_array($input_attrs)) $input_attrs = array(); $input_attrs['type'] = 'text'; $input_attrs['name'] = $input_name; $input_attrs['id'] = $input_id; $input_attrs['autocomplete'] = 'off'; foreach($input_attrs as $name => $val) { $input_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); } $html .= sprintf('<input %s>', $input_attr); } return $html; }
php
public static function getCaptchaHtml($options = array(), $parts = Securimage::HTML_ALL) { static $javascript_init = false; if (!isset($options['securimage_path'])) { $docroot = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME'])); $docroot = realpath($docroot); $sipath = dirname(__FILE__); $securimage_path = str_replace($docroot, '', $sipath); } else { $securimage_path = $options['securimage_path']; } $show_image_url = (isset($options['show_image_url'])) ? $options['show_image_url'] : null; $image_id = (isset($options['image_id'])) ? $options['image_id'] : 'captcha_image'; $image_alt = (isset($options['image_alt_text'])) ? $options['image_alt_text'] : 'CAPTCHA Image'; $show_audio_btn = (isset($options['show_audio_button'])) ? (bool)$options['show_audio_button'] : true; $disable_flash_fbk = (isset($options['disable_flash_fallback'])) ? (bool)$options['disable_flash_fallback'] : false; $show_refresh_btn = (isset($options['show_refresh_button'])) ? (bool)$options['show_refresh_button'] : true; $refresh_icon_url = (isset($options['refresh_icon_url'])) ? $options['refresh_icon_url'] : null; $audio_but_bg_col = (isset($options['audio_button_bgcol'])) ? $options['audio_button_bgcol'] : '#ffffff'; $audio_icon_url = (isset($options['audio_icon_url'])) ? $options['audio_icon_url'] : null; $loading_icon_url = (isset($options['loading_icon_url'])) ? $options['loading_icon_url'] : null; $icon_size = (isset($options['icon_size'])) ? $options['icon_size'] : 32; $audio_play_url = (isset($options['audio_play_url'])) ? $options['audio_play_url'] : null; $audio_swf_url = (isset($options['audio_swf_url'])) ? $options['audio_swf_url'] : null; $show_input = (isset($options['show_text_input'])) ? (bool)$options['show_text_input'] : true; $refresh_alt = (isset($options['refresh_alt_text'])) ? $options['refresh_alt_text'] : 'Refresh Image'; $refresh_title = (isset($options['refresh_title_text'])) ? $options['refresh_title_text'] : 'Refresh Image'; $input_text = (isset($options['input_text'])) ? $options['input_text'] : 'Type the text:'; $input_id = (isset($options['input_id'])) ? $options['input_id'] : 'captcha_code'; $input_name = (isset($options['input_name'])) ? $options['input_name'] : $input_id; $input_attrs = (isset($options['input_attributes'])) ? $options['input_attributes'] : array(); $image_attrs = (isset($options['image_attributes'])) ? $options['image_attributes'] : array(); $error_html = (isset($options['error_html'])) ? $options['error_html'] : null; $namespace = (isset($options['namespace'])) ? $options['namespace'] : ''; $rand = md5(uniqid($_SERVER['REMOTE_PORT'], true)); $securimage_path = rtrim($securimage_path, '/\\'); $securimage_path = str_replace('\\', '/', $securimage_path); $image_attr = ''; if (!is_array($image_attrs)) $image_attrs = array(); if (!isset($image_attrs['style'])) $image_attrs['style'] = 'float: left; padding-right: 5px'; $image_attrs['id'] = $image_id; $show_path = $securimage_path . '/securimage_show.php?'; if ($show_image_url) { if (parse_url($show_image_url, PHP_URL_QUERY)) { $show_path = "{$show_image_url}&"; } else { $show_path = "{$show_image_url}?"; } } if (!empty($namespace)) { $show_path .= sprintf('namespace=%s&amp;', $namespace); } $image_attrs['src'] = $show_path . $rand; $image_attrs['alt'] = $image_alt; foreach($image_attrs as $name => $val) { $image_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); } $swf_path = $securimage_path . '/securimage_play.swf'; $play_path = $securimage_path . '/securimage_play.php?'; $icon_path = $securimage_path . '/images/audio_icon.png'; $load_path = $securimage_path . '/images/loading.png'; $js_path = $securimage_path . '/securimage.js'; if (!empty($audio_icon_url)) { $icon_path = $audio_icon_url; } if (!empty($loading_icon_url)) { $load_path = $loading_icon_url; } if (!empty($audio_play_url)) { if (parse_url($audio_play_url, PHP_URL_QUERY)) { $play_path = "{$audio_play_url}&"; } else { $play_path = "{$audio_play_url}?"; } } if (!empty($namespace)) { $play_path .= sprintf('namespace=%s&amp;', $namespace); } if (!empty($audio_swf_url)) { $swf_path = $audio_swf_url; } $audio_obj = $image_id . '_audioObj'; $html = ''; if ( ($parts & Securimage::HTML_IMG) > 0) { $html .= sprintf('<img %s/>', $image_attr); } if ( ($parts & Securimage::HTML_AUDIO) > 0 && $show_audio_btn) { // html5 audio $html .= sprintf('<div id="%s_audio_div">', $image_id) . "\n" . sprintf('<audio id="%s_audio" preload="none" style="display: none">', $image_id) . "\n"; // check for existence and executability of LAME binary // prefer mp3 over wav by sourcing it first, if available if (is_executable(Securimage::$lame_binary_path)) { $html .= sprintf('<source id="%s_source_mp3" src="%sid=%s&amp;format=mp3" type="audio/mpeg">', $image_id, $play_path, uniqid()) . "\n"; } // output wav source $html .= sprintf('<source id="%s_source_wav" src="%sid=%s" type="audio/wav">', $image_id, $play_path, uniqid()) . "\n"; // flash audio button if (!$disable_flash_fbk) { $html .= sprintf('<object type="application/x-shockwave-flash" data="%s?bgcol=%s&amp;icon_file=%s&amp;audio_file=%s" height="%d" width="%d">', htmlspecialchars($swf_path), urlencode($audio_but_bg_col), urlencode($icon_path), urlencode(html_entity_decode($play_path)), $icon_size, $icon_size ); $html .= sprintf('<param name="movie" value="%s?bgcol=%s&amp;icon_file=%s&amp;audio_file=%s">', htmlspecialchars($swf_path), urlencode($audio_but_bg_col), urlencode($icon_path), urlencode(html_entity_decode($play_path)) ); $html .= '</object><br />'; } // html5 audio close $html .= "</audio>\n</div>\n"; // html5 audio controls $html .= sprintf('<div id="%s_audio_controls">', $image_id) . "\n" . sprintf('<a tabindex="-1" class="captcha_play_button" href="%sid=%s" onclick="return false">', $play_path, uniqid() ) . "\n" . sprintf('<img class="captcha_play_image" height="%d" width="%d" src="%s" alt="Play CAPTCHA Audio" style="border: 0px">', $icon_size, $icon_size, htmlspecialchars($icon_path)) . "\n" . sprintf('<img class="captcha_loading_image rotating" height="%d" width="%d" src="%s" alt="Loading audio" style="display: none">', $icon_size, $icon_size, htmlspecialchars($load_path)) . "\n" . "</a>\n<noscript>Enable Javascript for audio controls</noscript>\n" . "</div>\n"; // html5 javascript if (!$javascript_init) { $html .= sprintf('<script type="text/javascript" src="%s"></script>', $js_path) . "\n"; $javascript_init = true; } $html .= '<script type="text/javascript">' . "$audio_obj = new SecurimageAudio({ audioElement: '{$image_id}_audio', controlsElement: '{$image_id}_audio_controls' });" . "</script>\n"; } if ( ($parts & Securimage::HTML_ICON_REFRESH) > 0 && $show_refresh_btn) { $icon_path = $securimage_path . '/images/refresh.png'; if ($refresh_icon_url) { $icon_path = $refresh_icon_url; } $img_tag = sprintf('<img height="%d" width="%d" src="%s" alt="%s" onclick="this.blur()" style="border: 0px; vertical-align: bottom">', $icon_size, $icon_size, htmlspecialchars($icon_path), htmlspecialchars($refresh_alt)); $html .= sprintf('<a tabindex="-1" style="border: 0" href="#" title="%s" onclick="%sdocument.getElementById(\'%s\').src = \'%s\' + Math.random(); this.blur(); return false">%s</a><br>', htmlspecialchars($refresh_title), ($audio_obj) ? "if (typeof window.{$audio_obj} !== 'undefined') {$audio_obj}.refresh(); " : '', $image_id, $show_path, $img_tag ); } if ($parts == Securimage::HTML_ALL) { $html .= '<div style="clear: both"></div>'; } if ( ($parts & Securimage::HTML_INPUT_LABEL) > 0 && $show_input) { $html .= sprintf('<label for="%s">%s</label> ', htmlspecialchars($input_id), htmlspecialchars($input_text)); if (!empty($error_html)) { $html .= $error_html; } } if ( ($parts & Securimage::HTML_INPUT) > 0 && $show_input) { $input_attr = ''; if (!is_array($input_attrs)) $input_attrs = array(); $input_attrs['type'] = 'text'; $input_attrs['name'] = $input_name; $input_attrs['id'] = $input_id; $input_attrs['autocomplete'] = 'off'; foreach($input_attrs as $name => $val) { $input_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); } $html .= sprintf('<input %s>', $input_attr); } return $html; }
[ "public", "static", "function", "getCaptchaHtml", "(", "$", "options", "=", "array", "(", ")", ",", "$", "parts", "=", "Securimage", "::", "HTML_ALL", ")", "{", "static", "$", "javascript_init", "=", "false", ";", "if", "(", "!", "isset", "(", "$", "op...
Returns HTML code for displaying the captcha image, audio button, and form text input. Options can be specified to modify the output of the HTML. Accepted options: 'securimage_path': Optional: The URI to where securimage is installed (e.g. /securimage) 'show_image_url': Path to the securimage_show.php script (useful when integrating with a framework or moving outside the securimage directory) This will be passed as a urlencoded string to the <img> tag for outputting the captcha image 'audio_play_url': Same as show_image_url, except this indicates the URL of the audio playback script 'image_id': A string that sets the "id" attribute of the captcha image (default: captcha_image) 'image_alt_text': The alt text of the captcha image (default: CAPTCHA Image) 'show_audio_button': true/false Whether or not to show the audio button (default: true) 'disable_flash_fallback':) Allow only HTML5 audio and disable Flash fallback 'show_refresh_button': true/false Whether or not to show a button to refresh the image (default: true) 'audio_icon_url': URL to the image used for showing the HTML5 audio icon 'icon_size': Size (for both height & width) in pixels of the audio and refresh buttons 'show_text_input': true/false Whether or not to show the text input for the captcha (default: true) 'refresh_alt_text': Alt text for the refresh image (default: Refresh Image) 'refresh_title_text': Title text for the refresh image link (default: Refresh Image) 'input_id': A string that sets the "id" attribute of the captcha text input (default: captcha_code) 'input_name': A string that sets the "name" attribute of the captcha text input (default: same as input_id) 'input_text': A string that sets the text of the label for the captcha text input (default: Type the text:) 'input_attributes': An array of additional HTML tag attributes to pass to the text input tag (default: empty) 'image_attributes': An array of additional HTML tag attributes to pass to the captcha image tag (default: empty) 'error_html': Optional HTML markup to be shown above the text input field 'namespace': The optional captcha namespace to use for showing the image and playing back the audio. Namespaces are for using multiple captchas on the same page. @param array $options Array of options for modifying the HTML code. @param int $parts Securiage::HTML_* constant controlling what component of the captcha HTML to display @return string The generated HTML code for displaying the captcha
[ "Returns", "HTML", "code", "for", "displaying", "the", "captcha", "image", "audio", "button", "and", "form", "text", "input", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1339-L1545
dapphp/securimage
securimage.php
Securimage.outputAudioFile
public function outputAudioFile($format = null) { set_error_handler(array(&$this, 'errorHandler')); if (isset($_SERVER['HTTP_RANGE'])) { $range = true; $rangeId = (isset($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) ? 'ID' . $_SERVER['HTTP_X_PLAYBACK_SESSION_ID'] : 'ID' . md5($_SERVER['REQUEST_URI']); $uniq = $rangeId; } else { $uniq = md5(uniqid(microtime())); } try { if (!($audio = $this->getAudioData())) { // if previously generated audio not found for current captcha require_once dirname(__FILE__) . '/WavFile.php'; $audio = $this->getAudibleCode(); if (strtolower($format) == 'mp3') { $audio = $this->wavToMp3($audio); } $this->saveAudioData($audio); } } catch (Exception $ex) { $log_file = rtrim($this->log_path, '/\\ ') . DIRECTORY_SEPARATOR . $this->log_file; if (($fp = fopen($log_file, 'a+')) !== false) { fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n"); fclose($fp); } $audio = $this->audioError(); } if ($this->no_session != true) { // close session to make it available to other requests in the event // streaming the audio takes sevaral seconds or more session_write_close(); } if ($this->canSendHeaders() || $this->send_headers == false) { if ($this->send_headers) { if ($format == 'mp3') { $ext = 'mp3'; $type = 'audio/mpeg'; } else { $ext = 'wav'; $type = 'audio/wav'; } header('Accept-Ranges: bytes'); header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.{$ext}\""); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Expires: Sun, 1 Jan 2000 12:00:00 GMT'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT'); header('Content-type: ' . $type); } $this->rangeDownload($audio); } else { echo '<hr /><strong>' .'Failed to generate audio file, content has already been ' .'output.<br />This is most likely due to misconfiguration or ' .'a PHP error was sent to the browser.</strong>'; } restore_error_handler(); if (!$this->no_exit) exit; }
php
public function outputAudioFile($format = null) { set_error_handler(array(&$this, 'errorHandler')); if (isset($_SERVER['HTTP_RANGE'])) { $range = true; $rangeId = (isset($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) ? 'ID' . $_SERVER['HTTP_X_PLAYBACK_SESSION_ID'] : 'ID' . md5($_SERVER['REQUEST_URI']); $uniq = $rangeId; } else { $uniq = md5(uniqid(microtime())); } try { if (!($audio = $this->getAudioData())) { // if previously generated audio not found for current captcha require_once dirname(__FILE__) . '/WavFile.php'; $audio = $this->getAudibleCode(); if (strtolower($format) == 'mp3') { $audio = $this->wavToMp3($audio); } $this->saveAudioData($audio); } } catch (Exception $ex) { $log_file = rtrim($this->log_path, '/\\ ') . DIRECTORY_SEPARATOR . $this->log_file; if (($fp = fopen($log_file, 'a+')) !== false) { fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n"); fclose($fp); } $audio = $this->audioError(); } if ($this->no_session != true) { // close session to make it available to other requests in the event // streaming the audio takes sevaral seconds or more session_write_close(); } if ($this->canSendHeaders() || $this->send_headers == false) { if ($this->send_headers) { if ($format == 'mp3') { $ext = 'mp3'; $type = 'audio/mpeg'; } else { $ext = 'wav'; $type = 'audio/wav'; } header('Accept-Ranges: bytes'); header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.{$ext}\""); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Expires: Sun, 1 Jan 2000 12:00:00 GMT'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT'); header('Content-type: ' . $type); } $this->rangeDownload($audio); } else { echo '<hr /><strong>' .'Failed to generate audio file, content has already been ' .'output.<br />This is most likely due to misconfiguration or ' .'a PHP error was sent to the browser.</strong>'; } restore_error_handler(); if (!$this->no_exit) exit; }
[ "public", "function", "outputAudioFile", "(", "$", "format", "=", "null", ")", "{", "set_error_handler", "(", "array", "(", "&", "$", "this", ",", "'errorHandler'", ")", ")", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_RANGE'", "]", ")", ...
Generate an audible captcha in WAV format and send it to the browser with appropriate headers. Example: $img = new Securimage(); $img->outputAudioFile(); // outputs a wav file to the browser exit; @param string $format
[ "Generate", "an", "audible", "captcha", "in", "WAV", "format", "and", "send", "it", "to", "the", "browser", "with", "appropriate", "headers", ".", "Example", ":" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1586-L1658
dapphp/securimage
securimage.php
Securimage.rangeDownload
public function rangeDownload($audio) { /* Congratulations Firefox Android/Linux/Windows for being the most * sensible browser of all when streaming HTML5 audio! * * Chrome on Android and iOS on iPad/iPhone both make extra HTTP requests * for the audio whether on WiFi or the mobile network resulting in * multiple downloads of the audio file and wasted bandwidth. * * If I'm doing something wrong in this code or anyone knows why, I'd * love to hear from you. */ $audioLength = $size = strlen($audio); if (isset($_SERVER['HTTP_RANGE'])) { list( , $range) = explode('=', $_SERVER['HTTP_RANGE']); // bytes=byte-range-set $range = trim($range); if (strpos($range, ',') !== false) { // eventually, we should handle requests with multiple ranges // most likely these types of requests will never be sent header('HTTP/1.1 416 Range Not Satisfiable'); echo "<h1>Range Not Satisfiable</h1>"; exit; } else if (preg_match('/(\d+)-(\d+)/', $range, $match)) { // bytes n - m $range = array(intval($match[1]), intval($match[2])); } else if (preg_match('/(\d+)-$/', $range, $match)) { // bytes n - last byte of file $range = array(intval($match[1]), null); } else if (preg_match('/-(\d+)/', $range, $match)) { // final n bytes of file $range = array($size - intval($match[1]), $size - 1); } if ($range[1] === null) $range[1] = $size - 1; $length = $range[1] - $range[0] + 1; $audio = substr($audio, $range[0], $length); $audioLength = strlen($audio); header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes {$range[0]}-{$range[1]}/{$size}"); if ($range[0] < 0 ||$range[1] >= $size || $range[0] >= $size || $range[0] > $range[1]) { header('HTTP/1.1 416 Range Not Satisfiable'); echo "<h1>Range Not Satisfiable</h1>"; exit; } } header('Content-Length: ' . $audioLength); echo $audio; }
php
public function rangeDownload($audio) { /* Congratulations Firefox Android/Linux/Windows for being the most * sensible browser of all when streaming HTML5 audio! * * Chrome on Android and iOS on iPad/iPhone both make extra HTTP requests * for the audio whether on WiFi or the mobile network resulting in * multiple downloads of the audio file and wasted bandwidth. * * If I'm doing something wrong in this code or anyone knows why, I'd * love to hear from you. */ $audioLength = $size = strlen($audio); if (isset($_SERVER['HTTP_RANGE'])) { list( , $range) = explode('=', $_SERVER['HTTP_RANGE']); // bytes=byte-range-set $range = trim($range); if (strpos($range, ',') !== false) { // eventually, we should handle requests with multiple ranges // most likely these types of requests will never be sent header('HTTP/1.1 416 Range Not Satisfiable'); echo "<h1>Range Not Satisfiable</h1>"; exit; } else if (preg_match('/(\d+)-(\d+)/', $range, $match)) { // bytes n - m $range = array(intval($match[1]), intval($match[2])); } else if (preg_match('/(\d+)-$/', $range, $match)) { // bytes n - last byte of file $range = array(intval($match[1]), null); } else if (preg_match('/-(\d+)/', $range, $match)) { // final n bytes of file $range = array($size - intval($match[1]), $size - 1); } if ($range[1] === null) $range[1] = $size - 1; $length = $range[1] - $range[0] + 1; $audio = substr($audio, $range[0], $length); $audioLength = strlen($audio); header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes {$range[0]}-{$range[1]}/{$size}"); if ($range[0] < 0 ||$range[1] >= $size || $range[0] >= $size || $range[0] > $range[1]) { header('HTTP/1.1 416 Range Not Satisfiable'); echo "<h1>Range Not Satisfiable</h1>"; exit; } } header('Content-Length: ' . $audioLength); echo $audio; }
[ "public", "function", "rangeDownload", "(", "$", "audio", ")", "{", "/* Congratulations Firefox Android/Linux/Windows for being the most\n * sensible browser of all when streaming HTML5 audio!\n *\n * Chrome on Android and iOS on iPad/iPhone both make extra HTTP requests\n ...
Output audio data with http range support. Typically this shouldn't be called directly unless being used with a custom implentation. Use Securimage::outputAudioFile instead. @param string $audio Raw wav or mp3 audio file content
[ "Output", "audio", "data", "with", "http", "range", "support", ".", "Typically", "this", "shouldn", "t", "be", "called", "directly", "unless", "being", "used", "with", "a", "custom", "implentation", ".", "Use", "Securimage", "::", "outputAudioFile", "instead", ...
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1667-L1720
dapphp/securimage
securimage.php
Securimage.getCode
public function getCode($array = false, $returnExisting = false) { $code = array(); $time = 0; $disp = 'error'; if ($returnExisting && strlen($this->code) > 0) { if ($array) { return array( 'code' => $this->code, 'display' => $this->code_display, 'code_display' => $this->code_display, 'time' => 0); } else { return $this->code; } } if ($this->no_session != true) { if (isset($_SESSION['securimage_code_value'][$this->namespace]) && trim($_SESSION['securimage_code_value'][$this->namespace]) != '') { if ($this->isCodeExpired( $_SESSION['securimage_code_ctime'][$this->namespace]) == false) { $code['code'] = $_SESSION['securimage_code_value'][$this->namespace]; $code['time'] = $_SESSION['securimage_code_ctime'][$this->namespace]; $code['display'] = $_SESSION['securimage_code_disp'] [$this->namespace]; } } } if (empty($code) && $this->use_database) { // no code in session - may mean user has cookies turned off $this->openDatabase(); $code = $this->getCodeFromDatabase(); if (!empty($code)) { $code['display'] = $code['code_disp']; unset($code['code_disp']); } } else { /* no code stored in session or sqlite database, validation will fail */ } if ($array == true) { return $code; } else { return $code['code']; } }
php
public function getCode($array = false, $returnExisting = false) { $code = array(); $time = 0; $disp = 'error'; if ($returnExisting && strlen($this->code) > 0) { if ($array) { return array( 'code' => $this->code, 'display' => $this->code_display, 'code_display' => $this->code_display, 'time' => 0); } else { return $this->code; } } if ($this->no_session != true) { if (isset($_SESSION['securimage_code_value'][$this->namespace]) && trim($_SESSION['securimage_code_value'][$this->namespace]) != '') { if ($this->isCodeExpired( $_SESSION['securimage_code_ctime'][$this->namespace]) == false) { $code['code'] = $_SESSION['securimage_code_value'][$this->namespace]; $code['time'] = $_SESSION['securimage_code_ctime'][$this->namespace]; $code['display'] = $_SESSION['securimage_code_disp'] [$this->namespace]; } } } if (empty($code) && $this->use_database) { // no code in session - may mean user has cookies turned off $this->openDatabase(); $code = $this->getCodeFromDatabase(); if (!empty($code)) { $code['display'] = $code['code_disp']; unset($code['code_disp']); } } else { /* no code stored in session or sqlite database, validation will fail */ } if ($array == true) { return $code; } else { return $code['code']; } }
[ "public", "function", "getCode", "(", "$", "array", "=", "false", ",", "$", "returnExisting", "=", "false", ")", "{", "$", "code", "=", "array", "(", ")", ";", "$", "time", "=", "0", ";", "$", "disp", "=", "'error'", ";", "if", "(", "$", "returnE...
Return the code from the session or database (if configured). If none exists or was found, an empty string is returned. @param bool $array true to receive an array containing the code and properties, false to receive just the code. @param bool $returnExisting If true, and the class property *code* is set, it will be returned instead of getting the code from the session or database. @return array|string Return is an array if $array = true, otherwise a string containing the code
[ "Return", "the", "code", "from", "the", "session", "or", "database", "(", "if", "configured", ")", ".", "If", "none", "exists", "or", "was", "found", "an", "empty", "string", "is", "returned", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1729-L1775
dapphp/securimage
securimage.php
Securimage.doImage
protected function doImage() { if($this->use_transparent_text == true || $this->bgimg != '' || function_exists('imagecreatetruecolor')) { $imagecreate = 'imagecreatetruecolor'; } else { $imagecreate = 'imagecreate'; } $this->im = $imagecreate($this->image_width, $this->image_height); if (function_exists('imageantialias')) { imageantialias($this->im, true); } $this->allocateColors(); if ($this->perturbation > 0) { $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale); imagepalettecopy($this->tmpimg, $this->im); } else { $this->iscale = 1; } $this->setBackground(); $code = ''; if ($this->getCaptchaId(false) !== null) { // a captcha Id was supplied // check to see if a display_value for the captcha image was set if (is_string($this->display_value) && strlen($this->display_value) > 0) { $this->code_display = $this->display_value; $this->code = ($this->case_sensitive) ? $this->display_value : strtolower($this->display_value); $code = $this->code; } elseif ($this->openDatabase()) { // no display_value, check the database for existing captchaId $code = $this->getCodeFromDatabase(); // got back a result from the database with a valid code for captchaId if (is_array($code)) { $this->code = $code['code']; $this->code_display = $code['code_disp']; $code = $code['code']; } } } if ($code == '') { // if the code was not set using display_value or was not found in // the database, create a new code $this->createCode(); } if ($this->noise_level > 0) { $this->drawNoise(); } $this->drawWord(); if ($this->perturbation > 0 && is_readable($this->ttf_file)) { $this->distortedCopy(); } if ($this->num_lines > 0) { $this->drawLines(); } if (trim($this->image_signature) != '') { $this->addSignature(); } $this->output(); }
php
protected function doImage() { if($this->use_transparent_text == true || $this->bgimg != '' || function_exists('imagecreatetruecolor')) { $imagecreate = 'imagecreatetruecolor'; } else { $imagecreate = 'imagecreate'; } $this->im = $imagecreate($this->image_width, $this->image_height); if (function_exists('imageantialias')) { imageantialias($this->im, true); } $this->allocateColors(); if ($this->perturbation > 0) { $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale); imagepalettecopy($this->tmpimg, $this->im); } else { $this->iscale = 1; } $this->setBackground(); $code = ''; if ($this->getCaptchaId(false) !== null) { // a captcha Id was supplied // check to see if a display_value for the captcha image was set if (is_string($this->display_value) && strlen($this->display_value) > 0) { $this->code_display = $this->display_value; $this->code = ($this->case_sensitive) ? $this->display_value : strtolower($this->display_value); $code = $this->code; } elseif ($this->openDatabase()) { // no display_value, check the database for existing captchaId $code = $this->getCodeFromDatabase(); // got back a result from the database with a valid code for captchaId if (is_array($code)) { $this->code = $code['code']; $this->code_display = $code['code_disp']; $code = $code['code']; } } } if ($code == '') { // if the code was not set using display_value or was not found in // the database, create a new code $this->createCode(); } if ($this->noise_level > 0) { $this->drawNoise(); } $this->drawWord(); if ($this->perturbation > 0 && is_readable($this->ttf_file)) { $this->distortedCopy(); } if ($this->num_lines > 0) { $this->drawLines(); } if (trim($this->image_signature) != '') { $this->addSignature(); } $this->output(); }
[ "protected", "function", "doImage", "(", ")", "{", "if", "(", "$", "this", "->", "use_transparent_text", "==", "true", "||", "$", "this", "->", "bgimg", "!=", "''", "||", "function_exists", "(", "'imagecreatetruecolor'", ")", ")", "{", "$", "imagecreate", ...
The main image drawing routing, responsible for constructing the entire image and serving it
[ "The", "main", "image", "drawing", "routing", "responsible", "for", "constructing", "the", "entire", "image", "and", "serving", "it" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1780-L1855
dapphp/securimage
securimage.php
Securimage.allocateColors
protected function allocateColors() { // allocate bg color first for imagecreate $this->gdbgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b); $alpha = intval($this->text_transparency_percentage / 100 * 127); if ($this->use_transparent_text == true) { $this->gdtextcolor = imagecolorallocatealpha($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b, $alpha); $this->gdlinecolor = imagecolorallocatealpha($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b, $alpha); $this->gdnoisecolor = imagecolorallocatealpha($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b, $alpha); } else { $this->gdtextcolor = imagecolorallocate($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b); $this->gdlinecolor = imagecolorallocate($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b); $this->gdnoisecolor = imagecolorallocate($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b); } $this->gdsignaturecolor = imagecolorallocate($this->im, $this->signature_color->r, $this->signature_color->g, $this->signature_color->b); }
php
protected function allocateColors() { // allocate bg color first for imagecreate $this->gdbgcolor = imagecolorallocate($this->im, $this->image_bg_color->r, $this->image_bg_color->g, $this->image_bg_color->b); $alpha = intval($this->text_transparency_percentage / 100 * 127); if ($this->use_transparent_text == true) { $this->gdtextcolor = imagecolorallocatealpha($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b, $alpha); $this->gdlinecolor = imagecolorallocatealpha($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b, $alpha); $this->gdnoisecolor = imagecolorallocatealpha($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b, $alpha); } else { $this->gdtextcolor = imagecolorallocate($this->im, $this->text_color->r, $this->text_color->g, $this->text_color->b); $this->gdlinecolor = imagecolorallocate($this->im, $this->line_color->r, $this->line_color->g, $this->line_color->b); $this->gdnoisecolor = imagecolorallocate($this->im, $this->noise_color->r, $this->noise_color->g, $this->noise_color->b); } $this->gdsignaturecolor = imagecolorallocate($this->im, $this->signature_color->r, $this->signature_color->g, $this->signature_color->b); }
[ "protected", "function", "allocateColors", "(", ")", "{", "// allocate bg color first for imagecreate", "$", "this", "->", "gdbgcolor", "=", "imagecolorallocate", "(", "$", "this", "->", "im", ",", "$", "this", "->", "image_bg_color", "->", "r", ",", "$", "this"...
Allocate the colors to be used for the image
[ "Allocate", "the", "colors", "to", "be", "used", "for", "the", "image" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1860-L1906
dapphp/securimage
securimage.php
Securimage.setBackground
protected function setBackground() { // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color imagefilledrectangle($this->im, 0, 0, $this->image_width, $this->image_height, $this->gdbgcolor); if ($this->perturbation > 0) { imagefilledrectangle($this->tmpimg, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $this->gdbgcolor); } if ($this->bgimg == '') { if ($this->background_directory != null && is_dir($this->background_directory) && is_readable($this->background_directory)) { $img = $this->getBackgroundFromDirectory(); if ($img != false) { $this->bgimg = $img; } } } if ($this->bgimg == '') { return; } $dat = @getimagesize($this->bgimg); if($dat == false) { return; } switch($dat[2]) { case 1: $newim = @imagecreatefromgif($this->bgimg); break; case 2: $newim = @imagecreatefromjpeg($this->bgimg); break; case 3: $newim = @imagecreatefrompng($this->bgimg); break; default: return; } if(!$newim) return; imagecopyresized($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height, imagesx($newim), imagesy($newim)); }
php
protected function setBackground() { // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color imagefilledrectangle($this->im, 0, 0, $this->image_width, $this->image_height, $this->gdbgcolor); if ($this->perturbation > 0) { imagefilledrectangle($this->tmpimg, 0, 0, $this->image_width * $this->iscale, $this->image_height * $this->iscale, $this->gdbgcolor); } if ($this->bgimg == '') { if ($this->background_directory != null && is_dir($this->background_directory) && is_readable($this->background_directory)) { $img = $this->getBackgroundFromDirectory(); if ($img != false) { $this->bgimg = $img; } } } if ($this->bgimg == '') { return; } $dat = @getimagesize($this->bgimg); if($dat == false) { return; } switch($dat[2]) { case 1: $newim = @imagecreatefromgif($this->bgimg); break; case 2: $newim = @imagecreatefromjpeg($this->bgimg); break; case 3: $newim = @imagecreatefrompng($this->bgimg); break; default: return; } if(!$newim) return; imagecopyresized($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height, imagesx($newim), imagesy($newim)); }
[ "protected", "function", "setBackground", "(", ")", "{", "// set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color", "imagefilledrectangle", "(", "$", "this", "->", "im", ",", "0", ",", "0", ",", "$", "this", "->", "image_wid...
The the background color, or background image to be used
[ "The", "the", "background", "color", "or", "background", "image", "to", "be", "used" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1911-L1957
dapphp/securimage
securimage.php
Securimage.getBackgroundFromDirectory
protected function getBackgroundFromDirectory() { $images = array(); if ( ($dh = opendir($this->background_directory)) !== false) { while (($file = readdir($dh)) !== false) { if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file; } closedir($dh); if (sizeof($images) > 0) { return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images)-1)]; } } return false; }
php
protected function getBackgroundFromDirectory() { $images = array(); if ( ($dh = opendir($this->background_directory)) !== false) { while (($file = readdir($dh)) !== false) { if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file; } closedir($dh); if (sizeof($images) > 0) { return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images)-1)]; } } return false; }
[ "protected", "function", "getBackgroundFromDirectory", "(", ")", "{", "$", "images", "=", "array", "(", ")", ";", "if", "(", "(", "$", "dh", "=", "opendir", "(", "$", "this", "->", "background_directory", ")", ")", "!==", "false", ")", "{", "while", "(...
Scan the directory for a background image to use @return string|bool
[ "Scan", "the", "directory", "for", "a", "background", "image", "to", "use" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1963-L1980
dapphp/securimage
securimage.php
Securimage.createCode
public function createCode() { $this->code = false; switch($this->captcha_type) { case self::SI_CAPTCHA_MATHEMATIC: { do { $signs = array('+', '-', 'x'); $left = mt_rand(1, 10); $right = mt_rand(1, 5); $sign = $signs[mt_rand(0, 2)]; switch($sign) { case 'x': $c = $left * $right; break; case '-': $c = $left - $right; break; default: $c = $left + $right; break; } } while ($c <= 0); // no negative #'s or 0 $this->code = "$c"; $this->code_display = "$left $sign $right"; break; } case self::SI_CAPTCHA_WORDS: $words = $this->readCodeFromFile(2); $this->code = implode(' ', $words); $this->code_display = $this->code; break; default: { if ($this->use_wordlist && is_readable($this->wordlist_file)) { $this->code = $this->readCodeFromFile(); } if ($this->code == false) { $this->code = $this->generateCode($this->code_length); } $this->code_display = $this->code; $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code); } // default } $this->saveData(); }
php
public function createCode() { $this->code = false; switch($this->captcha_type) { case self::SI_CAPTCHA_MATHEMATIC: { do { $signs = array('+', '-', 'x'); $left = mt_rand(1, 10); $right = mt_rand(1, 5); $sign = $signs[mt_rand(0, 2)]; switch($sign) { case 'x': $c = $left * $right; break; case '-': $c = $left - $right; break; default: $c = $left + $right; break; } } while ($c <= 0); // no negative #'s or 0 $this->code = "$c"; $this->code_display = "$left $sign $right"; break; } case self::SI_CAPTCHA_WORDS: $words = $this->readCodeFromFile(2); $this->code = implode(' ', $words); $this->code_display = $this->code; break; default: { if ($this->use_wordlist && is_readable($this->wordlist_file)) { $this->code = $this->readCodeFromFile(); } if ($this->code == false) { $this->code = $this->generateCode($this->code_length); } $this->code_display = $this->code; $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code); } // default } $this->saveData(); }
[ "public", "function", "createCode", "(", ")", "{", "$", "this", "->", "code", "=", "false", ";", "switch", "(", "$", "this", "->", "captcha_type", ")", "{", "case", "self", "::", "SI_CAPTCHA_MATHEMATIC", ":", "{", "do", "{", "$", "signs", "=", "array",...
This method generates a new captcha code. Generates a random captcha code based on *charset*, math problem, or captcha from the wordlist and saves the value to the session and/or database.
[ "This", "method", "generates", "a", "new", "captcha", "code", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L1987-L2034
dapphp/securimage
securimage.php
Securimage.drawWord
protected function drawWord() { $ratio = ($this->font_ratio) ? $this->font_ratio : 0.4; if ((float)$ratio < 0.1 || (float)$ratio >= 1) { $ratio = 0.4; } if (!is_readable($this->ttfFile())) { // this will not catch missing fonts after the first! $this->perturbation = 0; imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor); return ; } if ($this->perturbation > 0) { $width = $this->image_width * $this->iscale; $height = $this->image_height * $this->iscale; $font_size = $height * $ratio; $im = &$this->tmpimg; $scale = $this->iscale; } else { $height = $this->image_height; $width = $this->image_width; $font_size = $this->image_height * $ratio; $im = &$this->im; $scale = 1; } $captcha_text = $this->code_display; if ($this->use_random_spaces && $this->strpos($captcha_text, ' ') === false) { if (mt_rand(1, 100) % 5 > 0) { // ~20% chance no spacing added $index = mt_rand(1, $this->strlen($captcha_text) -1); $spaces = mt_rand(1, 3); // in general, we want all characters drawn close together to // prevent easy segmentation by solvers, but this adds random // spacing between two groups to make character positioning // less normalized. $captcha_text = sprintf( '%s%s%s', $this->substr($captcha_text, 0, $index), str_repeat(' ', $spaces), $this->substr($captcha_text, $index) ); } } $fonts = array(); // list of fonts corresponding to each char $i $angles = array(); // angles corresponding to each char $i $distance = array(); // distance from current char $i to previous char $dims = array(); // dimensions of each individual char $i $txtWid = 0; // width of the entire text string, including spaces and distances // Character positioning and angle $angle0 = mt_rand(10, 20); $angleN = mt_rand(-20, 10); if ($this->use_text_angles == false) { $angle0 = $angleN = $step = 0; } if (mt_rand(0, 99) % 2 == 0) { $angle0 = -$angle0; } if (mt_rand(0, 99) % 2 == 1) { $angleN = -$angleN; } $step = abs($angle0 - $angleN) / ($this->strlen($captcha_text) - 1); $step = ($angle0 > $angleN) ? -$step : $step; $angle = $angle0; for ($c = 0; $c < $this->strlen($captcha_text); ++$c) { $font = $this->ttfFile(); // select random font from list for this character $fonts[] = $font; $angles[] = $angle; // the angle of this character $dist = mt_rand(-2, 0) * $scale; // random distance between this and next character $distance[] = $dist; $char = $this->substr($captcha_text, $c, 1); // the character to draw for this sequence $dim = $this->getCharacterDimensions($char, $font_size, $angle, $font); // calculate dimensions of this character $dim[0] += $dist; // add the distance to the dimension (negative to bring them closer) $txtWid += $dim[0]; // increment width based on character width $dims[] = $dim; $angle += $step; // next angle if ($angle > 20) { $angle = 20; $step = $step * -1; } elseif ($angle < -20) { $angle = -20; $step = -1 * $step; } } $nextYPos = function($y, $i, $step) use ($height, $scale, $dims) { static $dir = 1; if ($y + $step + $dims[$i][2] + (10 * $scale) > $height) { $dir = 0; } elseif ($y - $step - $dims[$i][2] < $dims[$i][1] + $dims[$i][2] + (5 * $scale)) { $dir = 1; } if ($dir) { $y += $step; } else { $y -= $step; } return $y; }; $cx = floor($width / 2 - ($txtWid / 2)); $x = mt_rand(5 * $scale, max($cx * 2 - (5 * $scale), 5 * $scale)); if ($this->use_random_baseline) { $y = mt_rand($dims[0][1], $height - 10); } else { $y = ($height / 2 + $dims[0][1] / 2 - $dims[0][2]); } $st = $scale * mt_rand(5, 10); for ($c = 0; $c < $this->strlen($captcha_text); ++$c) { $font = $fonts[$c]; $char = $this->substr($captcha_text, $c, 1); $angle = $angles[$c]; $dim = $dims[$c]; if ($this->use_random_baseline) { $y = $nextYPos($y, $c, $st); } imagettftext( $im, $font_size, $angle, (int)$x, (int)$y, $this->gdtextcolor, $font, $char ); if ($this->use_random_boxes && strlen(trim($char)) && mt_rand(1,100) % 5 == 0) { imagesetthickness($im, 3); imagerectangle($im, $x, $y - $dim[1] + $dim[2], $x + $dim[0], $y + $dim[2], $this->gdtextcolor); } if ($c == ' ') { $x += $dim[0]; } else { $x += $dim[0] + $distance[$c]; } } // DEBUG //$this->im = $im; //$this->output(); }
php
protected function drawWord() { $ratio = ($this->font_ratio) ? $this->font_ratio : 0.4; if ((float)$ratio < 0.1 || (float)$ratio >= 1) { $ratio = 0.4; } if (!is_readable($this->ttfFile())) { // this will not catch missing fonts after the first! $this->perturbation = 0; imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor); return ; } if ($this->perturbation > 0) { $width = $this->image_width * $this->iscale; $height = $this->image_height * $this->iscale; $font_size = $height * $ratio; $im = &$this->tmpimg; $scale = $this->iscale; } else { $height = $this->image_height; $width = $this->image_width; $font_size = $this->image_height * $ratio; $im = &$this->im; $scale = 1; } $captcha_text = $this->code_display; if ($this->use_random_spaces && $this->strpos($captcha_text, ' ') === false) { if (mt_rand(1, 100) % 5 > 0) { // ~20% chance no spacing added $index = mt_rand(1, $this->strlen($captcha_text) -1); $spaces = mt_rand(1, 3); // in general, we want all characters drawn close together to // prevent easy segmentation by solvers, but this adds random // spacing between two groups to make character positioning // less normalized. $captcha_text = sprintf( '%s%s%s', $this->substr($captcha_text, 0, $index), str_repeat(' ', $spaces), $this->substr($captcha_text, $index) ); } } $fonts = array(); // list of fonts corresponding to each char $i $angles = array(); // angles corresponding to each char $i $distance = array(); // distance from current char $i to previous char $dims = array(); // dimensions of each individual char $i $txtWid = 0; // width of the entire text string, including spaces and distances // Character positioning and angle $angle0 = mt_rand(10, 20); $angleN = mt_rand(-20, 10); if ($this->use_text_angles == false) { $angle0 = $angleN = $step = 0; } if (mt_rand(0, 99) % 2 == 0) { $angle0 = -$angle0; } if (mt_rand(0, 99) % 2 == 1) { $angleN = -$angleN; } $step = abs($angle0 - $angleN) / ($this->strlen($captcha_text) - 1); $step = ($angle0 > $angleN) ? -$step : $step; $angle = $angle0; for ($c = 0; $c < $this->strlen($captcha_text); ++$c) { $font = $this->ttfFile(); // select random font from list for this character $fonts[] = $font; $angles[] = $angle; // the angle of this character $dist = mt_rand(-2, 0) * $scale; // random distance between this and next character $distance[] = $dist; $char = $this->substr($captcha_text, $c, 1); // the character to draw for this sequence $dim = $this->getCharacterDimensions($char, $font_size, $angle, $font); // calculate dimensions of this character $dim[0] += $dist; // add the distance to the dimension (negative to bring them closer) $txtWid += $dim[0]; // increment width based on character width $dims[] = $dim; $angle += $step; // next angle if ($angle > 20) { $angle = 20; $step = $step * -1; } elseif ($angle < -20) { $angle = -20; $step = -1 * $step; } } $nextYPos = function($y, $i, $step) use ($height, $scale, $dims) { static $dir = 1; if ($y + $step + $dims[$i][2] + (10 * $scale) > $height) { $dir = 0; } elseif ($y - $step - $dims[$i][2] < $dims[$i][1] + $dims[$i][2] + (5 * $scale)) { $dir = 1; } if ($dir) { $y += $step; } else { $y -= $step; } return $y; }; $cx = floor($width / 2 - ($txtWid / 2)); $x = mt_rand(5 * $scale, max($cx * 2 - (5 * $scale), 5 * $scale)); if ($this->use_random_baseline) { $y = mt_rand($dims[0][1], $height - 10); } else { $y = ($height / 2 + $dims[0][1] / 2 - $dims[0][2]); } $st = $scale * mt_rand(5, 10); for ($c = 0; $c < $this->strlen($captcha_text); ++$c) { $font = $fonts[$c]; $char = $this->substr($captcha_text, $c, 1); $angle = $angles[$c]; $dim = $dims[$c]; if ($this->use_random_baseline) { $y = $nextYPos($y, $c, $st); } imagettftext( $im, $font_size, $angle, (int)$x, (int)$y, $this->gdtextcolor, $font, $char ); if ($this->use_random_boxes && strlen(trim($char)) && mt_rand(1,100) % 5 == 0) { imagesetthickness($im, 3); imagerectangle($im, $x, $y - $dim[1] + $dim[2], $x + $dim[0], $y + $dim[2], $this->gdtextcolor); } if ($c == ' ') { $x += $dim[0]; } else { $x += $dim[0] + $distance[$c]; } } // DEBUG //$this->im = $im; //$this->output(); }
[ "protected", "function", "drawWord", "(", ")", "{", "$", "ratio", "=", "(", "$", "this", "->", "font_ratio", ")", "?", "$", "this", "->", "font_ratio", ":", "0.4", ";", "if", "(", "(", "float", ")", "$", "ratio", "<", "0.1", "||", "(", "float", "...
Draws the captcha code on the image
[ "Draws", "the", "captcha", "code", "on", "the", "image" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2039-L2207
dapphp/securimage
securimage.php
Securimage.getCharacterDimensions
protected function getCharacterDimensions($char, $size, $angle, $font) { $box = imagettfbbox($size, $angle, $font, $char); return array($box[2] - $box[0], max($box[1] - $box[7], $box[5] - $box[3]), $box[1]); }
php
protected function getCharacterDimensions($char, $size, $angle, $font) { $box = imagettfbbox($size, $angle, $font, $char); return array($box[2] - $box[0], max($box[1] - $box[7], $box[5] - $box[3]), $box[1]); }
[ "protected", "function", "getCharacterDimensions", "(", "$", "char", ",", "$", "size", ",", "$", "angle", ",", "$", "font", ")", "{", "$", "box", "=", "imagettfbbox", "(", "$", "size", ",", "$", "angle", ",", "$", "font", ",", "$", "char", ")", ";"...
Get the width and height (in points) of a character for a given font, angle, and size. @param string $char The character to get dimensions for @param number $size The font size, in points @param number $angle The angle of the text @return number[] A 3-element array representing the width, height and baseline of the text
[ "Get", "the", "width", "and", "height", "(", "in", "points", ")", "of", "a", "character", "for", "a", "given", "font", "angle", "and", "size", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2218-L2223
dapphp/securimage
securimage.php
Securimage.distortedCopy
protected function distortedCopy() { $numpoles = 3; // distortion factor $px = array(); // x coordinates of poles $py = array(); // y coordinates of poles $rad = array(); // radius of distortion from pole $amp = array(); // amplitude $x = ($this->image_width / 4); // lowest x coordinate of a pole $maxX = $this->image_width - $x; // maximum x coordinate of a pole $dx = mt_rand($x / 10, $x); // horizontal distance between poles $y = mt_rand(20, $this->image_height - 20); // random y coord $dy = mt_rand(20, $this->image_height * 0.7); // y distance $minY = 20; // minimum y coordinate $maxY = $this->image_height - 20; // maximum y cooddinate // make array of poles AKA attractor points for ($i = 0; $i < $numpoles; ++ $i) { $px[$i] = ($x + ($dx * $i)) % $maxX; $py[$i] = ($y + ($dy * $i)) % $maxY + $minY; $rad[$i] = mt_rand($this->image_height * 0.4, $this->image_height * 0.8); $tmp = ((- $this->frand()) * 0.15) - .15; $amp[$i] = $this->perturbation * $tmp; } $bgCol = imagecolorat($this->tmpimg, 0, 0); $width2 = $this->iscale * $this->image_width; $height2 = $this->iscale * $this->image_height; imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across // loop over $img pixels, take pixels from $tmpimg with distortion field for ($ix = 0; $ix < $this->image_width; ++ $ix) { for ($iy = 0; $iy < $this->image_height; ++ $iy) { $x = $ix; $y = $iy; for ($i = 0; $i < $numpoles; ++ $i) { $dx = $ix - $px[$i]; $dy = $iy - $py[$i]; if ($dx == 0 && $dy == 0) { continue; } $r = sqrt($dx * $dx + $dy * $dy); if ($r > $rad[$i]) { continue; } $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]); $x += $dx * $rscale; $y += $dy * $rscale; } $c = $bgCol; $x *= $this->iscale; $y *= $this->iscale; if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) { $c = imagecolorat($this->tmpimg, $x, $y); } if ($c != $bgCol) { // only copy pixels of letters to preserve any background image imagesetpixel($this->im, $ix, $iy, $c); } } } }
php
protected function distortedCopy() { $numpoles = 3; // distortion factor $px = array(); // x coordinates of poles $py = array(); // y coordinates of poles $rad = array(); // radius of distortion from pole $amp = array(); // amplitude $x = ($this->image_width / 4); // lowest x coordinate of a pole $maxX = $this->image_width - $x; // maximum x coordinate of a pole $dx = mt_rand($x / 10, $x); // horizontal distance between poles $y = mt_rand(20, $this->image_height - 20); // random y coord $dy = mt_rand(20, $this->image_height * 0.7); // y distance $minY = 20; // minimum y coordinate $maxY = $this->image_height - 20; // maximum y cooddinate // make array of poles AKA attractor points for ($i = 0; $i < $numpoles; ++ $i) { $px[$i] = ($x + ($dx * $i)) % $maxX; $py[$i] = ($y + ($dy * $i)) % $maxY + $minY; $rad[$i] = mt_rand($this->image_height * 0.4, $this->image_height * 0.8); $tmp = ((- $this->frand()) * 0.15) - .15; $amp[$i] = $this->perturbation * $tmp; } $bgCol = imagecolorat($this->tmpimg, 0, 0); $width2 = $this->iscale * $this->image_width; $height2 = $this->iscale * $this->image_height; imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across // loop over $img pixels, take pixels from $tmpimg with distortion field for ($ix = 0; $ix < $this->image_width; ++ $ix) { for ($iy = 0; $iy < $this->image_height; ++ $iy) { $x = $ix; $y = $iy; for ($i = 0; $i < $numpoles; ++ $i) { $dx = $ix - $px[$i]; $dy = $iy - $py[$i]; if ($dx == 0 && $dy == 0) { continue; } $r = sqrt($dx * $dx + $dy * $dy); if ($r > $rad[$i]) { continue; } $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]); $x += $dx * $rscale; $y += $dy * $rscale; } $c = $bgCol; $x *= $this->iscale; $y *= $this->iscale; if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) { $c = imagecolorat($this->tmpimg, $x, $y); } if ($c != $bgCol) { // only copy pixels of letters to preserve any background image imagesetpixel($this->im, $ix, $iy, $c); } } } }
[ "protected", "function", "distortedCopy", "(", ")", "{", "$", "numpoles", "=", "3", ";", "// distortion factor", "$", "px", "=", "array", "(", ")", ";", "// x coordinates of poles", "$", "py", "=", "array", "(", ")", ";", "// y coordinates of poles", "$", "r...
Copies the captcha image to the final image with distortion applied
[ "Copies", "the", "captcha", "image", "to", "the", "final", "image", "with", "distortion", "applied" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2228-L2287
dapphp/securimage
securimage.php
Securimage.drawLines
protected function drawLines() { for ($line = 0; $line < $this->num_lines; ++ $line) { $x = $this->image_width * (1 + $line) / ($this->num_lines + 1); $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines; $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9); $theta = ($this->frand() - 0.5) * M_PI * 0.33; $w = $this->image_width; $len = mt_rand($w * 0.4, $w * 0.7); $lwid = mt_rand(0, 2); $k = $this->frand() * 0.6 + 0.2; $k = $k * $k * 0.5; $phi = $this->frand() * 6.28; $step = 0.5; $dx = $step * cos($theta); $dy = $step * sin($theta); $n = $len / $step; $amp = 1.5 * $this->frand() / ($k + 5.0 / $len); $x0 = $x - 0.5 * $len * cos($theta); $y0 = $y - 0.5 * $len * sin($theta); $ldx = round(- $dy * $lwid); $ldy = round($dx * $lwid); for ($i = 0; $i < $n; ++ $i) { $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi); $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi); imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor); } } }
php
protected function drawLines() { for ($line = 0; $line < $this->num_lines; ++ $line) { $x = $this->image_width * (1 + $line) / ($this->num_lines + 1); $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines; $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9); $theta = ($this->frand() - 0.5) * M_PI * 0.33; $w = $this->image_width; $len = mt_rand($w * 0.4, $w * 0.7); $lwid = mt_rand(0, 2); $k = $this->frand() * 0.6 + 0.2; $k = $k * $k * 0.5; $phi = $this->frand() * 6.28; $step = 0.5; $dx = $step * cos($theta); $dy = $step * sin($theta); $n = $len / $step; $amp = 1.5 * $this->frand() / ($k + 5.0 / $len); $x0 = $x - 0.5 * $len * cos($theta); $y0 = $y - 0.5 * $len * sin($theta); $ldx = round(- $dy * $lwid); $ldy = round($dx * $lwid); for ($i = 0; $i < $n; ++ $i) { $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi); $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi); imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor); } } }
[ "protected", "function", "drawLines", "(", ")", "{", "for", "(", "$", "line", "=", "0", ";", "$", "line", "<", "$", "this", "->", "num_lines", ";", "++", "$", "line", ")", "{", "$", "x", "=", "$", "this", "->", "image_width", "*", "(", "1", "+"...
Draws distorted lines on the image
[ "Draws", "distorted", "lines", "on", "the", "image" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2292-L2324
dapphp/securimage
securimage.php
Securimage.drawNoise
protected function drawNoise() { if ($this->noise_level > 10) { $noise_level = 10; } else { $noise_level = $this->noise_level; } $t0 = microtime(true); $noise_level *= M_LOG2E; for ($x = 1; $x < $this->image_width; $x += 20) { for ($y = 1; $y < $this->image_height; $y += 20) { for ($i = 0; $i < $noise_level; ++$i) { $x1 = mt_rand($x, $x + 20); $y1 = mt_rand($y, $y + 20); $size = mt_rand(1, 3); if ($x1 - $size <= 0 && $y1 - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy imagefilledarc($this->im, $x1, $y1, $size, $size, 0, mt_rand(180,360), $this->gdlinecolor, IMG_ARC_PIE); } } } $t = microtime(true) - $t0; /* // DEBUG imagestring($this->im, 5, 25, 30, "$t", $this->gdnoisecolor); header('content-type: image/png'); imagepng($this->im); exit; */ }
php
protected function drawNoise() { if ($this->noise_level > 10) { $noise_level = 10; } else { $noise_level = $this->noise_level; } $t0 = microtime(true); $noise_level *= M_LOG2E; for ($x = 1; $x < $this->image_width; $x += 20) { for ($y = 1; $y < $this->image_height; $y += 20) { for ($i = 0; $i < $noise_level; ++$i) { $x1 = mt_rand($x, $x + 20); $y1 = mt_rand($y, $y + 20); $size = mt_rand(1, 3); if ($x1 - $size <= 0 && $y1 - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy imagefilledarc($this->im, $x1, $y1, $size, $size, 0, mt_rand(180,360), $this->gdlinecolor, IMG_ARC_PIE); } } } $t = microtime(true) - $t0; /* // DEBUG imagestring($this->im, 5, 25, 30, "$t", $this->gdnoisecolor); header('content-type: image/png'); imagepng($this->im); exit; */ }
[ "protected", "function", "drawNoise", "(", ")", "{", "if", "(", "$", "this", "->", "noise_level", ">", "10", ")", "{", "$", "noise_level", "=", "10", ";", "}", "else", "{", "$", "noise_level", "=", "$", "this", "->", "noise_level", ";", "}", "$", "...
Draws random noise on the image
[ "Draws", "random", "noise", "on", "the", "image" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2329-L2362
dapphp/securimage
securimage.php
Securimage.addSignature
protected function addSignature() { $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature); $textlen = $bbox[2] - $bbox[0]; $x = $this->image_width - $textlen - 5; $y = $this->image_height - 3; imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature); }
php
protected function addSignature() { $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature); $textlen = $bbox[2] - $bbox[0]; $x = $this->image_width - $textlen - 5; $y = $this->image_height - 3; imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature); }
[ "protected", "function", "addSignature", "(", ")", "{", "$", "bbox", "=", "imagettfbbox", "(", "10", ",", "0", ",", "$", "this", "->", "signature_font", ",", "$", "this", "->", "image_signature", ")", ";", "$", "textlen", "=", "$", "bbox", "[", "2", ...
Print signature text on image
[ "Print", "signature", "text", "on", "image" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2367-L2375
dapphp/securimage
securimage.php
Securimage.output
protected function output() { if ($this->canSendHeaders() || $this->send_headers == false) { if ($this->send_headers) { // only send the content-type headers if no headers have been output // this will ease debugging on misconfigured servers where warnings // may have been output which break the image and prevent easily viewing // source to see the error. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); } switch ($this->image_type) { case self::SI_IMAGE_JPEG: if ($this->send_headers) header("Content-Type: image/jpeg"); imagejpeg($this->im, null, 90); break; case self::SI_IMAGE_GIF: if ($this->send_headers) header("Content-Type: image/gif"); imagegif($this->im); break; default: if ($this->send_headers) header("Content-Type: image/png"); imagepng($this->im); break; } } else { echo '<hr /><strong>' .'Failed to generate captcha image, content has already been ' .'output.<br />This is most likely due to misconfiguration or ' .'a PHP error was sent to the browser.</strong>'; } imagedestroy($this->im); restore_error_handler(); if (!$this->no_exit) exit; }
php
protected function output() { if ($this->canSendHeaders() || $this->send_headers == false) { if ($this->send_headers) { // only send the content-type headers if no headers have been output // this will ease debugging on misconfigured servers where warnings // may have been output which break the image and prevent easily viewing // source to see the error. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); } switch ($this->image_type) { case self::SI_IMAGE_JPEG: if ($this->send_headers) header("Content-Type: image/jpeg"); imagejpeg($this->im, null, 90); break; case self::SI_IMAGE_GIF: if ($this->send_headers) header("Content-Type: image/gif"); imagegif($this->im); break; default: if ($this->send_headers) header("Content-Type: image/png"); imagepng($this->im); break; } } else { echo '<hr /><strong>' .'Failed to generate captcha image, content has already been ' .'output.<br />This is most likely due to misconfiguration or ' .'a PHP error was sent to the browser.</strong>'; } imagedestroy($this->im); restore_error_handler(); if (!$this->no_exit) exit; }
[ "protected", "function", "output", "(", ")", "{", "if", "(", "$", "this", "->", "canSendHeaders", "(", ")", "||", "$", "this", "->", "send_headers", "==", "false", ")", "{", "if", "(", "$", "this", "->", "send_headers", ")", "{", "// only send the conten...
Sends the appropriate image and cache headers and outputs image to the browser
[ "Sends", "the", "appropriate", "image", "and", "cache", "headers", "and", "outputs", "image", "to", "the", "browser" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2380-L2420
dapphp/securimage
securimage.php
Securimage.getAudibleCode
protected function getAudibleCode() { $letters = array(); $code = $this->getCode(true, true); if (empty($code) || empty($code['code'])) { if (strlen($this->display_value) > 0) { $code = array('code' => $this->display_value, 'display' => $this->display_value); } else { $this->createCode(); $code = $this->getCode(true); } } if (empty($code)) { $error = 'Failed to get audible code (are database settings correct?). Check the error log for details'; trigger_error($error, E_USER_WARNING); throw new \Exception($error); } if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq)) { $math = true; $left = $eq[1]; $sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]); $right = $eq[3]; $letters = array($left, $sign, $right); } else { $math = false; $length = $this->strlen($code['display']); for($i = 0; $i < $length; ++$i) { $letter = $this->substr($code['display'], $i, 1); $letters[] = $letter; } } try { return $this->generateWAV($letters); } catch(\Exception $ex) { throw $ex; } }
php
protected function getAudibleCode() { $letters = array(); $code = $this->getCode(true, true); if (empty($code) || empty($code['code'])) { if (strlen($this->display_value) > 0) { $code = array('code' => $this->display_value, 'display' => $this->display_value); } else { $this->createCode(); $code = $this->getCode(true); } } if (empty($code)) { $error = 'Failed to get audible code (are database settings correct?). Check the error log for details'; trigger_error($error, E_USER_WARNING); throw new \Exception($error); } if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq)) { $math = true; $left = $eq[1]; $sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]); $right = $eq[3]; $letters = array($left, $sign, $right); } else { $math = false; $length = $this->strlen($code['display']); for($i = 0; $i < $length; ++$i) { $letter = $this->substr($code['display'], $i, 1); $letters[] = $letter; } } try { return $this->generateWAV($letters); } catch(\Exception $ex) { throw $ex; } }
[ "protected", "function", "getAudibleCode", "(", ")", "{", "$", "letters", "=", "array", "(", ")", ";", "$", "code", "=", "$", "this", "->", "getCode", "(", "true", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "code", ")", "||", "empty", "...
Generates an audio captcha in WAV format @return string The audio representation of the captcha in Wav format
[ "Generates", "an", "audio", "captcha", "in", "WAV", "format" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2427-L2471
dapphp/securimage
securimage.php
Securimage.readCodeFromFile
protected function readCodeFromFile($numWords = 1) { $strtolower_func = 'strtolower'; $mb_support = false; if (!empty($this->wordlist_file_encoding)) { if (!extension_loaded('mbstring')) { trigger_error("wordlist_file_encoding option set, but PHP does not have mbstring support", E_USER_WARNING); return false; } // emits PHP warning if not supported $mb_support = mb_internal_encoding($this->wordlist_file_encoding); if (!$mb_support) { return false; } $strtolower_func = 'mb_strtolower'; } $fp = fopen($this->wordlist_file, 'rb'); if (!$fp) return false; $fsize = filesize($this->wordlist_file); if ($fsize < 128) return false; // too small of a list to be effective if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1; $words = array(); $i = 0; do { fseek($fp, mt_rand(0, $fsize - 128), SEEK_SET); // seek to a random position of file from 0 to filesize-128 $data = fread($fp, 128); // read a chunk from our random position if ($mb_support !== false) { $data = mb_ereg_replace("\r?\n", "\n", $data); } else { $data = preg_replace("/\r?\n/", "\n", $data); } $start = @$this->strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position $end = @$this->strpos($data, "\n", $start); // find end of word if ($start === false) { // picked start position at end of file continue; } else if ($end === false) { $end = $this->strlen($data); } $word = $strtolower_func($this->substr($data, $start, $end - $start)); // return a line of the file if ($mb_support) { // convert to UTF-8 for imagettftext $word = mb_convert_encoding($word, 'UTF-8', $this->wordlist_file_encoding); } $words[] = $word; } while (++$i < $numWords); fclose($fp); if ($numWords < 2) { return $words[0]; } else { return $words; } }
php
protected function readCodeFromFile($numWords = 1) { $strtolower_func = 'strtolower'; $mb_support = false; if (!empty($this->wordlist_file_encoding)) { if (!extension_loaded('mbstring')) { trigger_error("wordlist_file_encoding option set, but PHP does not have mbstring support", E_USER_WARNING); return false; } // emits PHP warning if not supported $mb_support = mb_internal_encoding($this->wordlist_file_encoding); if (!$mb_support) { return false; } $strtolower_func = 'mb_strtolower'; } $fp = fopen($this->wordlist_file, 'rb'); if (!$fp) return false; $fsize = filesize($this->wordlist_file); if ($fsize < 128) return false; // too small of a list to be effective if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1; $words = array(); $i = 0; do { fseek($fp, mt_rand(0, $fsize - 128), SEEK_SET); // seek to a random position of file from 0 to filesize-128 $data = fread($fp, 128); // read a chunk from our random position if ($mb_support !== false) { $data = mb_ereg_replace("\r?\n", "\n", $data); } else { $data = preg_replace("/\r?\n/", "\n", $data); } $start = @$this->strpos($data, "\n", mt_rand(0, 56)) + 1; // random start position $end = @$this->strpos($data, "\n", $start); // find end of word if ($start === false) { // picked start position at end of file continue; } else if ($end === false) { $end = $this->strlen($data); } $word = $strtolower_func($this->substr($data, $start, $end - $start)); // return a line of the file if ($mb_support) { // convert to UTF-8 for imagettftext $word = mb_convert_encoding($word, 'UTF-8', $this->wordlist_file_encoding); } $words[] = $word; } while (++$i < $numWords); fclose($fp); if ($numWords < 2) { return $words[0]; } else { return $words; } }
[ "protected", "function", "readCodeFromFile", "(", "$", "numWords", "=", "1", ")", "{", "$", "strtolower_func", "=", "'strtolower'", ";", "$", "mb_support", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "wordlist_file_encoding", ")", "...
Gets a captcha code from a file containing a list of words. Seek to a random offset in the file and reads a block of data and returns a line from the file. @param int $numWords Number of words (lines) to read from the file @return string|array|bool Returns a string if only one word is to be read, or an array of words
[ "Gets", "a", "captcha", "code", "from", "a", "file", "containing", "a", "list", "of", "words", "." ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2481-L2549
dapphp/securimage
securimage.php
Securimage.generateCode
protected function generateCode() { $code = ''; for($i = 1, $cslen = $this->strlen($this->charset); $i <= $this->code_length; ++$i) { $code .= $this->substr($this->charset, mt_rand(0, $cslen - 1), 1); } return $code; }
php
protected function generateCode() { $code = ''; for($i = 1, $cslen = $this->strlen($this->charset); $i <= $this->code_length; ++$i) { $code .= $this->substr($this->charset, mt_rand(0, $cslen - 1), 1); } return $code; }
[ "protected", "function", "generateCode", "(", ")", "{", "$", "code", "=", "''", ";", "for", "(", "$", "i", "=", "1", ",", "$", "cslen", "=", "$", "this", "->", "strlen", "(", "$", "this", "->", "charset", ")", ";", "$", "i", "<=", "$", "this", ...
Generates a random captcha code from the set character set @see Securimage::$charset Charset option @return string A randomly generated CAPTCHA code
[ "Generates", "a", "random", "captcha", "code", "from", "the", "set", "character", "set" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2557-L2566
dapphp/securimage
securimage.php
Securimage.validate
protected function validate() { if (!is_string($this->code) || strlen($this->code) == 0) { $code = $this->getCode(true); // returns stored code, or an empty string if no stored code was found // checks the session and database if enabled } else { $code = $this->code; } if (is_array($code)) { if (!empty($code)) { $ctime = $code['time']; $code = $code['code']; $this->_timeToSolve = time() - $ctime; } else { $code = ''; } } if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) { // case sensitive was set from securimage_show.php but not in class // the code saved in the session has capitals so set case sensitive to true $this->case_sensitive = true; } $code_entered = trim( (($this->case_sensitive) ? $this->code_entered : strtolower($this->code_entered)) ); $this->correct_code = false; if ($code != '') { if (strpos($code, ' ') !== false) { // for multi word captchas, remove more than once space from input $code_entered = preg_replace('/\s+/', ' ', $code_entered); $code_entered = strtolower($code_entered); } if ((string)$code === (string)$code_entered) { $this->correct_code = true; if ($this->no_session != true) { $_SESSION['securimage_code_disp'] [$this->namespace] = ''; $_SESSION['securimage_code_value'][$this->namespace] = ''; $_SESSION['securimage_code_ctime'][$this->namespace] = ''; $_SESSION['securimage_code_audio'][$this->namespace] = ''; } $this->clearCodeFromDatabase(); } } }
php
protected function validate() { if (!is_string($this->code) || strlen($this->code) == 0) { $code = $this->getCode(true); // returns stored code, or an empty string if no stored code was found // checks the session and database if enabled } else { $code = $this->code; } if (is_array($code)) { if (!empty($code)) { $ctime = $code['time']; $code = $code['code']; $this->_timeToSolve = time() - $ctime; } else { $code = ''; } } if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) { // case sensitive was set from securimage_show.php but not in class // the code saved in the session has capitals so set case sensitive to true $this->case_sensitive = true; } $code_entered = trim( (($this->case_sensitive) ? $this->code_entered : strtolower($this->code_entered)) ); $this->correct_code = false; if ($code != '') { if (strpos($code, ' ') !== false) { // for multi word captchas, remove more than once space from input $code_entered = preg_replace('/\s+/', ' ', $code_entered); $code_entered = strtolower($code_entered); } if ((string)$code === (string)$code_entered) { $this->correct_code = true; if ($this->no_session != true) { $_SESSION['securimage_code_disp'] [$this->namespace] = ''; $_SESSION['securimage_code_value'][$this->namespace] = ''; $_SESSION['securimage_code_ctime'][$this->namespace] = ''; $_SESSION['securimage_code_audio'][$this->namespace] = ''; } $this->clearCodeFromDatabase(); } } }
[ "protected", "function", "validate", "(", ")", "{", "if", "(", "!", "is_string", "(", "$", "this", "->", "code", ")", "||", "strlen", "(", "$", "this", "->", "code", ")", "==", "0", ")", "{", "$", "code", "=", "$", "this", "->", "getCode", "(", ...
Validate a code supplied by the user Checks the entered code against the value stored in the session and/or database (if configured). Handles case sensitivity. Also removes the code from session/database if the code was entered correctly to prevent re-use attack. This function does not return a value. @see Securimage::$correct_code 'correct_code' property
[ "Validate", "a", "code", "supplied", "by", "the", "user" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2578-L2628
dapphp/securimage
securimage.php
Securimage.saveData
protected function saveData() { if ($this->no_session != true) { if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value'])) { // fix for migration from v2 - v3 unset($_SESSION['securimage_code_value']); unset($_SESSION['securimage_code_ctime']); } $_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display; $_SESSION['securimage_code_value'][$this->namespace] = $this->code; $_SESSION['securimage_code_ctime'][$this->namespace] = time(); $_SESSION['securimage_code_audio'][$this->namespace] = null; // clear previous audio, if set } if ($this->use_database) { $this->saveCodeToDatabase(); } }
php
protected function saveData() { if ($this->no_session != true) { if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value'])) { // fix for migration from v2 - v3 unset($_SESSION['securimage_code_value']); unset($_SESSION['securimage_code_ctime']); } $_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display; $_SESSION['securimage_code_value'][$this->namespace] = $this->code; $_SESSION['securimage_code_ctime'][$this->namespace] = time(); $_SESSION['securimage_code_audio'][$this->namespace] = null; // clear previous audio, if set } if ($this->use_database) { $this->saveCodeToDatabase(); } }
[ "protected", "function", "saveData", "(", ")", "{", "if", "(", "$", "this", "->", "no_session", "!=", "true", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", "[", "'securimage_code_value'", "]", ")", "&&", "is_scalar", "(", "$", "_SESSION", "[", "'...
Save CAPTCHA data to session and database (if configured)
[ "Save", "CAPTCHA", "data", "to", "session", "and", "database", "(", "if", "configured", ")" ]
train
https://github.com/dapphp/securimage/blob/1ecb884797c66e01a875c058def46c85aecea45b/securimage.php#L2633-L2651