sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function _generateTableColumns($model)
{
$model = TableRegistry::get($model);
$columns = ConnectionManager::get('default')->schemaCollection()->describe($model->table())->columns();
$result = [];
$counter = 0;
$max = 2;
if (in_array('id', $columns)) {
$result['id'] = [];
unset($columns['id']);
}
foreach ($columns as $column) {
if ($counter < $max) {
$result[$column] = [];
unset($columns[$column]);
$counter++;
}
}
if (in_array('created', $columns)) {
$result['created'] = [];
}
return $result;
} | If no tablecolumns are given, this method will be called to generate a list of tablecolumns.
@param \Cake\ORM\Table $model Model to rely on.
@return array | entailment |
protected function _generateFormFields($model)
{
$model = TableRegistry::get($model);
$columns = ConnectionManager::get('default')->schemaCollection()->describe($model->table())->columns();
$ignoredFields = [
'created',
'modified',
'created_by',
'modified_by',
'password'
];
$result = [];
foreach ($columns as $column) {
if (!in_array($column, $ignoredFields)) {
$result[$column] = [];
}
}
return $result;
} | If no formfields are given, this method will be called to generate a list of formfields.
@param \Cake\ORM\Table $model Model to rely on.
@return array | entailment |
protected function _normalizeFormFields($fields)
{
$_options = [
'on' => 'both'
];
$_defaults = [
'_create' => $_options
];
$result = [];
$result['_create'] = $_defaults['_create'];
foreach ($fields as $name => $options) {
if (is_array($options)) {
$result[$name] = array_merge($_options, $options);
} else {
$result[$options] = $_options;
}
}
return $result;
} | Normalizes the formfields-array.
@param array $fields Fields to normalize.
@return array | entailment |
protected function _normalizeTableColumns($columns)
{
$_defaults = [
'get' => false,
'before' => '',
'after' => '',
];
$result = [];
foreach ($columns as $name => $options) {
if (is_array($options)) {
$_defaults['get'] = $name;
$result[$name] = array_merge($_defaults, $options);
} else {
$_defaults['get'] = $options;
$result[$options] = $_defaults;
}
}
return $result;
} | Normalizes the tablecolumns-array.
@param array $columns Columns to normalize.
@return array | entailment |
public function checkRecord($marc)
{
// Reset warnings:
$this->warnings = array();
// Fail if we didn't get a valid object:
if (!is_a($marc, 'File_MARC_Record')) {
$this->warn('Must pass a File_MARC_Record object to checkRecord');
} else {
$this->checkDuplicate1xx($marc);
$this->checkMissing245($marc);
$this->standardFieldChecks($marc);
}
return $this->warnings;
} | Check the provided MARC record and return an array of warning messages.
@param File_MARC_Record $marc Record to check
@return array | entailment |
protected function checkDuplicate1xx($marc)
{
$result = $marc->getFields('1[0-9][0-9]', true);
$count = count($result);
if ($count > 1) {
$this->warn(
"1XX: Only one 1XX tag is allowed, but I found $count of them."
);
}
} | Check for multiple 1xx fields.
@param File_MARC_Record $marc Record to check
@return void | entailment |
protected function standardFieldChecks($marc)
{
$fieldsSeen = array();
foreach ($marc->getFields() as $current) {
$tagNo = $current->getTag();
// if 880 field, inherit rules from tagno in subfield _6
if ($tagNo == 880) {
if ($sub6 = $current->getSubfield(6)) {
$tagNo = substr($sub6->getData(), 0, 3);
$tagrules = isset($this->rules[$tagNo])
? $this->rules[$tagNo] : null;
// 880 is repeatable, but its linked field may not be
if (isset($tagrules['repeatable'])
&& $tagrules['repeatable'] == 'NR'
&& isset($fieldsSeen['880.'.$tagNo])
) {
$this->warn("$tagNo: Field is not repeatable.");
}
$fieldsSeen['880.'.$tagNo] = isset($fieldsSeen['880.'.$tagNo])
? $fieldsSeen['880.'.$tagNo] + 1 : 1;
} else {
$this->warn("880: No subfield 6.");
$tagRules = null;
}
} else {
// Default case -- not an 880 field:
$tagrules = isset($this->rules[$tagNo])
? $this->rules[$tagNo] : null;
if (isset($tagrules['repeatable']) && $tagrules['repeatable'] == 'NR'
&& isset($fieldsSeen[$tagNo])
) {
$this->warn("$tagNo: Field is not repeatable.");
}
$fieldsSeen[$tagNo] = isset($fieldsSeen[$tagNo])
? $fieldsSeen[$tagNo] + 1 : 1;
}
// Treat data fields differently from control fields:
if (intval(ltrim($tagNo, '0')) >= 10) {
if (!empty($tagrules)) {
$this->checkIndicators($tagNo, $current, $tagrules);
$this->checkSubfields($tagNo, $current, $tagrules);
}
} else {
// Control field:
if (strstr($current->toRaw(), chr(hexdec('1F')))) {
$this->warn(
"$tagNo: Subfields are not allowed in fields lower than 010"
);
}
}
// Check to see if a checkxxx() function exists, and call it on the
// field if it does
$method = 'check' . $tagNo;
if (method_exists($this, $method)) {
$this->$method($current);
}
}
} | Check all fields against the standard rules encoded in the class.
@param File_MARC_Record $marc Record to check
@return void | entailment |
protected function checkIndicators($tagNo, $field, $rules)
{
for ($i = 1; $i <= 2; $i++) {
$ind = $field->getIndicator($i);
if ($ind === false || $ind == ' ') {
$ind = 'b';
}
if (!strstr($rules['ind' . $i]['values'], $ind)) {
// Make indicator blank value human-readable for message:
if ($ind == 'b') {
$ind = 'blank';
}
$this->warn(
"$tagNo: Indicator $i must be "
. $rules['ind' . $i]['hr_values']
. " but it's \"$ind\""
);
}
}
} | Check the indicators for the provided field.
@param string $tagNo Tag number being checked
@param File_MARC_Field $field Field to check
@param array $rules Rules to use for checking
@return void | entailment |
protected function checkSubfields($tagNo, $field, $rules)
{
$subSeen = array();
foreach ($field->getSubfields() as $current) {
$code = $current->getCode();
$data = $current->getData();
$subrules = isset($rules['sub' . $code])
? $rules['sub' . $code] : null;
if (empty($subrules)) {
$this->warn("$tagNo: Subfield _$code is not allowed.");
} elseif ($subrules['repeatable'] == 'NR' && isset($subSeen[$code])) {
$this->warn("$tagNo: Subfield _$code is not repeatable.");
}
if (preg_match('/\r|\t|\n/', $data)) {
$this->warn(
"$tagNo: Subfield _$code has an invalid control character"
);
}
$subSeen[$code] = isset($subSeen[$code]) ? $subSeen[$code]++ : 1;
}
} | Check the subfields for the provided field.
@param string $tagNo Tag number being checked
@param File_MARC_Field $field Field to check
@param array $rules Rules to use for checking
@return void | entailment |
protected function check020($field)
{
foreach ($field->getSubfields() as $current) {
$data = $current->getData();
// remove any hyphens
$isbn = str_replace('-', '', $data);
// remove nondigits
$isbn = preg_replace('/^\D*(\d{9,12}[X\d])\b.*$/', '$1', $isbn);
if ($current->getCode() == 'a') {
if ((substr($data, 0, strlen($isbn)) != $isbn)) {
$this->warn("020: Subfield a may have invalid characters.");
}
// report error if no space precedes a qualifier in subfield a
if (preg_match('/\(/', $data) && !preg_match('/[X0-9] \(/', $data)) {
$this->warn(
"020: Subfield a qualifier must be preceded by space, $data."
);
}
// report error if unable to find 10-13 digit string of digits in
// subfield 'a'
if (!preg_match('/(?:^\d{10}$)|(?:^\d{13}$)|(?:^\d{9}X$)/', $isbn)) {
$this->warn(
"020: Subfield a has the wrong number of digits, $data."
);
} else {
if (strlen($isbn) == 10) {
if (!Validate_ISPN::isbn10($isbn)) {
$this->warn("020: Subfield a has bad checksum, $data.");
}
} else if (strlen($isbn) == 13) {
if (!Validate_ISPN::isbn13($isbn)) {
$this->warn(
"020: Subfield a has bad checksum (13 digit), $data."
);
}
}
}
} else if ($current->getCode() == 'z') {
// look for valid isbn in 020$z
if (preg_match('/^ISBN/', $data)
|| preg_match('/^\d*\-\d+/', $data)
) {
// ##################################################
// ## Turned on for now--Comment to unimplement ####
// ##################################################
if ((strlen($isbn) == 10)
&& (Validate_ISPN::isbn10($isbn) == 1)
) {
$this->warn("020: Subfield z is numerically valid.");
}
}
}
}
} | Looks at 020$a and reports errors if the check digit is wrong.
Looks at 020$z and validates number if hyphens are present.
@param File_MARC_Field $field Field to check
@return void | entailment |
protected function check041($field)
{
// warn if length of each subfield is not divisible by 3 unless ind2 is 7
if ($field->getIndicator(2) != '7') {
foreach ($field->getSubfields() as $sub) {
$code = $sub->getCode();
$data = $sub->getData();
if (strlen($data) % 3 != 0) {
$this->warn(
"041: Subfield _$code must be evenly divisible by 3 or "
. "exactly three characters if ind2 is not 7, ($data)."
);
} else {
for ($i = 0; $i < strlen($data); $i += 3) {
$chk = substr($data, $i, 3);
if (!in_array($chk, $this->data->languageCodes)) {
$obs = $this->data->obsoleteLanguageCodes;
if (in_array($chk, $obs)) {
$this->warn(
"041: Subfield _$code, $data, may be obsolete."
);
} else {
$this->warn(
"041: Subfield _$code, $data ($chk),"
. " is not valid."
);
}
}
}
}
}
}
} | Warns if subfields are not evenly divisible by 3 unless second indicator is 7
(future implementation would ensure that each subfield is exactly 3 characters
unless ind2 is 7--since subfields are now repeatable. This is not implemented
here due to the large number of records needing to be corrected.). Validates
against the MARC Code List for Languages (<http://www.loc.gov/marc/>).
@param File_MARC_Field $field Field to check
@return void | entailment |
protected function check043($field)
{
foreach ($field->getSubfields('a') as $suba) {
// warn if length of subfield a is not exactly 7
$data = $suba->getData();
if (strlen($data) != 7) {
$this->warn("043: Subfield _a must be exactly 7 characters, $data");
} else if (!in_array($data, $this->data->geogAreaCodes)) {
if (in_array($data, $this->data->obsoleteGeogAreaCodes)) {
$this->warn("043: Subfield _a, $data, may be obsolete.");
} else {
$this->warn("043: Subfield _a, $data, is not valid.");
}
}
}
} | Warns if each subfield a is not exactly 7 characters. Validates each code
against the MARC code list for Geographic Areas (<http://www.loc.gov/marc/>).
@param File_MARC_Field $field Field to check
@return void | entailment |
protected function check245($field)
{
if (count($field->getSubfields('a')) == 0) {
$this->warn("245: Must have a subfield _a.");
}
// Convert subfields to array and set flags indicating which subfields are
// present while we're at it.
$tmp = $field->getSubfields();
$hasSubfields = $subfields = array();
foreach ($tmp as $current) {
$subfields[] = $current;
$hasSubfields[$current->getCode()] = true;
}
// 245 must end in period (may want to make this less restrictive by allowing
// trailing spaces)
// do 2 checks--for final punctuation (MARC21 rule), and for period
// (LCRI 1.0C, Nov. 2003)
$lastChar = substr($subfields[count($subfields)-1]->getData(), -1);
if (!in_array($lastChar, array('.', '?', '!'))) {
$this->warn("245: Must end with . (period).");
} else if ($lastChar != '.') {
$this->warn(
"245: MARC21 allows ? or ! as final punctuation but LCRI 1.0C, Nov."
. " 2003 (LCPS 1.7.1 for RDA records), requires period."
);
}
// Check for first subfield
// subfield a should be first subfield (or 2nd if subfield '6' is present)
if (isset($hasSubfields['6'])) {
// make sure there are at least 2 subfields
if (count($subfields) < 2) {
$this->warn("245: May have too few subfields.");
} else {
$first = $subfields[0]->getCode();
$second = $subfields[1]->getCode();
if ($first != '6') {
$this->warn("245: First subfield must be _6, but it is $first");
}
if ($second != 'a') {
$this->warn(
"245: First subfield after subfield _6 must be _a, but it "
. "is _$second"
);
}
}
} else {
// 1st subfield must be 'a'
$first = $subfields[0]->getCode();
if ($first != 'a') {
$this->warn("245: First subfield must be _a, but it is _$first");
}
}
// End check for first subfield
// subfield c, if present, must be preceded by /
// also look for space between initials
if (isset($hasSubfields['c'])) {
foreach ($subfields as $i => $current) {
// 245 subfield c must be preceded by / (space-/)
if ($current->getCode() == 'c') {
if ($i > 0
&& !preg_match('/\s\/$/', $subfields[$i-1]->getData())
) {
$this->warn("245: Subfield _c must be preceded by /");
}
// 245 subfield c initials should not have space
if (preg_match('/\b\w\. \b\w\./', $current->getData())) {
$this->warn(
"245: Subfield _c initials should not have a space."
);
}
break;
}
}
}
// each subfield b, if present, should be preceded by :;= (colon, semicolon,
// or equals sign)
if (isset($hasSubfields['b'])) {
// 245 subfield b should be preceded by space-:;= (colon, semicolon, or
// equals sign)
foreach ($subfields as $i => $current) {
if ($current->getCode() == 'b' && $i > 0
&& !preg_match('/ [:;=]$/', $subfields[$i-1]->getData())
) {
$this->warn(
"245: Subfield _b should be preceded by space-colon, "
. "space-semicolon, or space-equals sign."
);
}
}
}
// each subfield h, if present, should be preceded by non-space
if (isset($hasSubfields['h'])) {
// 245 subfield h should not be preceded by space
foreach ($subfields as $i => $current) {
// report error if subfield 'h' is preceded by space (unless
// dash-space)
if ($current->getCode() == 'h') {
$prev = $subfields[$i-1]->getData();
if ($i > 0 && !preg_match('/(\S$)|(\-\- $)/', $prev)) {
$this->warn(
"245: Subfield _h should not be preceded by space."
);
}
// report error if subfield 'h' does not start with open square
// bracket with a matching close bracket; could have check
// against list of valid values here
$data = $current->getData();
if (!preg_match('/^\[\w*\s*\w*\]/', $data)) {
$this->warn(
"245: Subfield _h must have matching square brackets,"
. " $data."
);
}
}
}
}
// each subfield n, if present, must be preceded by . (period)
if (isset($hasSubfields['n'])) {
// 245 subfield n must be preceded by . (period)
foreach ($subfields as $i => $current) {
// report error if subfield 'n' is not preceded by non-space-period
// or dash-space-period
if ($current->getCode() == 'n' && $i > 0) {
$prev = $subfields[$i-1]->getData();
if (!preg_match('/(\S\.$)|(\-\- \.$)/', $prev)) {
$this->warn(
"245: Subfield _n must be preceded by . (period)."
);
}
}
}
}
// each subfield p, if present, must be preceded by a , (no-space-comma)
// if it follows subfield n, or by . (no-space-period or
// dash-space-period) following other subfields
if (isset($hasSubfields['p'])) {
// 245 subfield p must be preceded by . (period) or , (comma)
foreach ($subfields as $i => $current) {
if ($current->getCode() == 'p' && $i > 0) {
$prev = $subfields[$i-1];
// case for subfield 'n' being field before this one (allows
// dash-space-comma)
if ($prev->getCode() == 'n'
&& !preg_match('/(\S,$)|(\-\- ,$)/', $prev->getData())
) {
$this->warn(
"245: Subfield _p must be preceded by , (comma) "
. "when it follows subfield _n."
);
} else if ($prev->getCode() != 'n'
&& !preg_match('/(\S\.$)|(\-\- \.$)/', $prev->getData())
) {
$this->warn(
"245: Subfield _p must be preceded by . (period)"
. " when it follows a subfield other than _n."
);
}
}
}
}
// check for invalid 2nd indicator
$this->checkArticle($field);
} | -Makes sure $a exists (and is first subfield).
-Warns if last character of field is not a period
--Follows LCRI 1.0C, Nov. 2003 rather than MARC21 rule
-Verifies that $c is preceded by / (space-/)
-Verifies that initials in $c are not spaced
-Verifies that $b is preceded by :;= (space-colon, space-semicolon,
space-equals)
-Verifies that $h is not preceded by space unless it is dash-space
-Verifies that data of $h is enclosed in square brackets
-Verifies that $n is preceded by . (period)
--As part of that, looks for no-space period, or dash-space-period
(for replaced elipses)
-Verifies that $p is preceded by , (no-space-comma) when following $n and
. (period) when following other subfields.
-Performs rudimentary article check of 245 2nd indicator vs. 1st word of
245$a (for manual verification).
Article checking is done by internal checkArticle method, which should work
for 130, 240, 245, 440, 630, 730, and 830.
@param File_MARC_Field $field Field to check
@return void | entailment |
protected function checkArticle($field)
{
// add articles here as needed
// Some omitted due to similarity with valid words (e.g. the German 'die').
static $article = array(
'a' => 'eng glg hun por',
'an' => 'eng',
'das' => 'ger',
'dem' => 'ger',
'der' => 'ger',
'ein' => 'ger',
'eine' => 'ger',
'einem' => 'ger',
'einen' => 'ger',
'einer' => 'ger',
'eines' => 'ger',
'el' => 'spa',
'en' => 'cat dan nor swe',
'gl' => 'ita',
'gli' => 'ita',
'il' => 'ita mlt',
'l' => 'cat fre ita mlt',
'la' => 'cat fre ita spa',
'las' => 'spa',
'le' => 'fre ita',
'les' => 'cat fre',
'lo' => 'ita spa',
'los' => 'spa',
'os' => 'por',
'the' => 'eng',
'um' => 'por',
'uma' => 'por',
'un' => 'cat spa fre ita',
'una' => 'cat spa ita',
'une' => 'fre',
'uno' => 'ita',
);
// add exceptions here as needed
// may want to make keys lowercase
static $exceptions = array(
'A & E',
'A & ',
'A-',
'A+',
'A is ',
'A isn\'t ',
'A l\'',
'A la ',
'A posteriori',
'A priori',
'A to ',
'El Nino',
'El Salvador',
'L is ',
'L-',
'La Salle',
'Las Vegas',
'Lo mein',
'Los Alamos',
'Los Angeles',
);
// get tagno to determine which indicator to check and for reporting
$tagNo = $field->getTag();
// retrieve tagno from subfield 6 if 880 field
if ($tagNo == '880' && ($sub6 = $field->getSubfield('6'))) {
$tagNo = substr($sub6->getData(), 0, 3);
}
// $ind holds nonfiling character indicator value
$ind = '';
// $first_or_second holds which indicator is for nonfiling char value
$first_or_second = '';
if (in_array($tagNo, array(130, 630, 730))) {
$ind = $field->getIndicator(1);
$first_or_second = '1st';
} else if (in_array($tagNo, array(240, 245, 440, 830))) {
$ind = $field->getIndicator(2);
$first_or_second = '2nd';
} else {
$this->warn(
'Internal error: ' . $tagNo
. " is not a valid field for article checking\n"
);
return;
}
if (!is_numeric($ind)) {
$this->warn($tagNo . ": Non-filing indicator is non-numeric");
return;
}
// get subfield 'a' of the title field
$titleField = $field->getSubfield('a');
$title = $titleField ? $titleField->getData() : '';
$char1_notalphanum = 0;
// check for apostrophe, quote, bracket, or parenthesis, before first word
// remove if found and add to non-word counter
while (preg_match('/^["\'\[\(*]/', $title)) {
$char1_notalphanum++;
$title = preg_replace('/^["\'\[\(*]/', '', $title);
}
// split title into first word + rest on space, parens, bracket, apostrophe,
// quote, or hyphen
preg_match('/^([^ \(\)\[\]\'"\-]+)([ \(\)\[\]\'"\-])?(.*)/i', $title, $hits);
$firstword = isset($hits[1]) ? $hits[1] : '';
$separator = isset($hits[2]) ? $hits[2] : '';
$etc = isset($hits[3]) ? $hits[3] : '';
// get length of first word plus the number of chars removed above plus one
// for the separator
$nonfilingchars = strlen($firstword) + $char1_notalphanum + 1;
// check to see if first word is an exception
$isan_exception = false;
foreach ($exceptions as $current) {
if (substr($title, 0, strlen($current)) == $current) {
$isan_exception = true;
break;
}
}
// lowercase chars of $firstword for comparison with article list
$firstword = strtolower($firstword);
// see if first word is in the list of articles and not an exception
$isan_article = !$isan_exception && isset($article[$firstword]);
// if article then $nonfilingchars should match $ind
if ($isan_article) {
// account for quotes, apostrophes, parens, or brackets before 2nd word
if (strlen($separator) && preg_match('/^[ \(\)\[\]\'"\-]+/', $etc)) {
while (preg_match('/^[ "\'\[\]\(\)*]/', $etc)) {
$nonfilingchars++;
$etc = preg_replace('/^[ "\'\[\]\(\)*]/', '', $etc);
}
}
if ($nonfilingchars != $ind) {
$this->warn(
$tagNo . ": First word, $firstword, may be an article, check "
. "$first_or_second indicator ($ind)."
);
}
} else {
// not an article so warn if $ind is not 0
if ($ind != '0') {
$this->warn(
$tagNo . ": First word, $firstword, does not appear to be an "
. "article, check $first_or_second indicator ($ind)."
);
}
}
} | Check of articles is based on code from Ian Hamilton. This version is more
limited in that it focuses on English, Spanish, French, Italian and German
articles. Certain possible articles have been removed if they are valid
English non-articles. This version also disregards 008_language/041 codes
and just uses the list of articles to provide warnings/suggestions.
source for articles = <http://www.loc.gov/marc/bibliographic/bdapp-e.html>
Should work with fields 130, 240, 245, 440, 630, 730, and 830. Reports error
if another field is passed in.
@param File_MARC_Field $field Field to check
@return void | entailment |
protected function parseRules()
{
// Break apart the rule data on line breaks:
$lines = explode("\n", $this->getRawRules());
// Each group of data is split by a blank line -- process one group
// at a time:
$currentGroup = array();
foreach ($lines as $currentLine) {
if (empty($currentLine) && !empty($currentGroup)) {
$this->processRuleGroup($currentGroup);
$currentGroup = array();
} else {
$currentGroup[] = preg_replace("/\s+/", " ", $currentLine);
}
}
// Still have unprocessed data after the loop? Handle it now:
if (!empty($currentGroup)) {
$this->processRuleGroup($currentGroup);
}
} | Support method for constructor to load MARC rules.
@return void | entailment |
protected function processRuleGroup($rules)
{
// The first line is guaranteed to exist and gives us some basic info:
list($tag, $repeatable, $description) = explode(' ', $rules[0]);
$this->rules[$tag] = array(
'repeatable' => $repeatable,
'desc' => $description
);
// We may or may not have additional details:
for ($i = 1; $i < count($rules); $i++) {
list($key, $value, $lineDesc) = explode(' ', $rules[$i]);
if (substr($key, 0, 3) == 'ind') {
// Expand ranges:
$value = str_replace('0-9', '0123456789', $value);
$this->rules[$tag][$key] = array(
'values' => $value,
'hr_values' => $this->getHumanReadableIndicatorValues($value),
'desc'=> $lineDesc
);
} else {
if (strlen($key) <= 1) {
$this->rules[$tag]['sub' . $key] = array(
'repeatable' => $value,
'desc' => $lineDesc
);
} elseif (strstr($key, '-')) {
list($startKey, $endKey) = explode('-', $key);
for ($key = $startKey; $key <= $endKey; $key++) {
$this->rules[$tag]['sub' . $key] = array(
'repeatable' => $value,
'desc' => $lineDesc
);
}
}
}
}
} | Support method for parseRules() -- process one group of lines representing
a single tag.
@param array $rules Rule lines to process
@return void | entailment |
protected function getHumanReadableIndicatorValues($rules)
{
// No processing needed for blank rule:
if ($rules == 'blank') {
return $rules;
}
// Create string:
$string = '';
$length = strlen($rules);
for ($i = 0; $i < $length; $i++) {
$current = substr($rules, $i, 1);
if ($current == 'b') {
$current = 'blank';
}
$string .= $current;
if ($length - $i == 2) {
$string .= ' or ';
} else if ($length - $i > 2) {
$string .= ', ';
}
}
return $string;
} | Turn a set of indicator rules into a human-readable list.
@param string $rules Indicator rules
@return string | entailment |
private function readData(string $refName, string $ext) : array
{
$majorReleases = array(
'core' => array(
'classes' => array('4', '5', '7', '71'),
'constants' => array('4', '5', '71'),
'functions' => array('4', '5', '7', '73'),
'iniEntries' => array('4', '5', '7', '71', '73'),
'interfaces' => array('5', '7', '72'),
'releases' => array('4', '5', '70', '71', '72'),
),
'standard' => array(
'classes' => array('4', '5', '7'),
'constants' => array('4', '5', '7', '71'),
'functions' => array('4', '5', '7', '71', '72', '73'),
'iniEntries' => array('4', '5', '7', '71'),
'releases' => array('4', '5', '7', '72'),
'methods' => array('4', '5', '7', '71'),
),
'apcu' => array(
'classes' => array('5'),
'constants' => array(''),
'functions' => array('', '5'),
'methods' => array('5'),
'releases' => array('', '5'),
),
'ast' => array(
'classes' => array(''),
'constants' => array(''),
'functions' => array(''),
'methods' => array(''),
'releases' => array(''),
),
'bcmath' => array(
'releases' => array('', '70', '71'),
),
'bz2' => array(
'releases' => array('', '70', '71'),
),
'calendar' => array(
'releases' => array('', '70', '71'),
),
'ctype' => array(
'releases' => array('', '70', '71'),
),
'curl' => array(
'functions' => array('', '71'),
'releases' => array('', '70', '71'),
),
'date' => array(
'const' => array('', '70', '71', '72'),
'constants' => array('', '70'),
'releases' => array('', '70', '71'),
),
'dom' => array(
'classes' => array(''),
'constants' => array(''),
'functions' => array(''),
'methods' => array(''),
'releases' => array(''),
),
'filter' => array(
'constants' => array('', '70', '71'),
'releases' => array('', '70', '71'),
),
'ftp' => array(
'constants' => array('', '56'),
'functions' => array('', '72'),
'releases' => array('', '70', '71'),
),
'gd' => array(
'functions' => array('', '72'),
'releases' => array('', '70', '71'),
),
'gender' => array(
'classes' => array(''),
'releases' => array('', '1'),
'const' => array('', '1'),
'methods' => array(''),
),
'geoip' => array(
'iniEntries' => array('1'),
'constants' => array('', '1'),
'functions' => array('', '1'),
'releases' => array('', '1'),
),
'gmp' => array(
'functions' => array('', '73'),
'releases' => array('', '70', '71'),
),
'hash' => array(
'functions' => array('', '71', '72'),
),
'haru' => array(
'releases' => array('', '1'),
'methods' => array('', '1'),
),
'htscanner' => array(
'iniEntries' => array('', '1'),
'releases' => array('', '1'),
),
'http' => array(
'classes' => array('', '1', '2'),
'constants' => array('', '2'),
'functions' => array(''),
'iniEntries' => array('', '2'),
'interfaces' => array('2', '3'),
'releases' => array('', '1', '2', '3'),
'const' => array('2', '3'),
'methods' => array('2'),
),
'imap' => array(
'iniEntries' => array('56'),
),
'imagick' => array(
'classes' => array(''),
'const' => array(''),
'iniEntries' => array(''),
'releases' => array(''),
),
'igbinary' => array(
'functions' => array('1'),
'iniEntries' => array('1'),
'releases' => array('1', '2', '3'),
),
'intl' => array(
'classes' => array('1', '2', '5', '70'),
'constants' => array('1', '2'),
'functions' => array('1', '2', '5', '73'),
'iniEntries' => array('1', '3'),
'releases' => array('1', '2', '3', '5'),
'const' => array('1', '2', '5', '70'),
'methods' => array('1', '2', '5', '70', '71'),
),
'jsmin' => array(
'constants' => array(''),
'functions' => array(''),
'releases' => array('', '1', '2'),
),
'ldap' => array(
'constants' => array('', '70', '71'),
'functions' => array('', '72', '73'),
'releases' => array('', '70', '71'),
),
'lzf' => array(
'functions' => array('', '1'),
'releases' => array('', '1'),
),
'mailparse' => array(
'classes' => array(''),
'constants' => array(''),
'functions' => array(''),
'iniEntries' => array(''),
'releases' => array('', '2', '3'),
'methods' => array(''),
),
'mbstring' => array(
'functions' => array('', '72'),
'releases' => array('', '70', '71'),
),
'memcached' => array(
'functions' => array('3'),
'iniEntries' => array('', '3'),
'releases' => array('', '3'),
),
'mongo' => array(
'classes' => array('', '1'),
'constants' => array('1'),
'functions' => array('1'),
'iniEntries' => array(''),
'interfaces' => array('1'),
'releases' => array('', '1'),
'const' => array('', '1'),
'methods' => array('', '1'),
),
'msgpack' => array(
'classes' => array(''),
'constants' => array('2'),
'functions' => array(''),
'iniEntries' => array(''),
'releases' => array('', '2'),
'const' => array(''),
'methods' => array(''),
),
'mysqli' => array(
'releases' => array('', '70', '71'),
),
'openssl' => array(
'constants' => array('', '71'),
'functions' => array('', '72', '73'),
'releases' => array('', '70', '71'),
),
'oauth' => array(
'classes' => array('', '1'),
'constants' => array('', '1'),
'functions' => array(''),
'releases' => array('', '1', '2'),
'methods' => array('', '1'),
),
'pcre' => array(
'iniEntries' => array('', '70'),
'functions' => array('', '70'),
),
'pcntl' => array(
'functions' => array('', '70', '71'),
),
'posix' => array(
'functions' => array('', '70'),
),
'pdflib' => array(
'classes' => array('2'),
'functions' => array('2', '3'),
'releases' => array('1', '2', '3'),
'methods' => array('2', '3'),
),
'pgsql' => array(
'constants' => array('', '71'),
'releases' => array('', '70', '71'),
),
'pthreads' => array(
'classes' => array('', '1', '2'),
'constants' => array('', '2'),
'releases' => array('', '1', '2', '3'),
'methods' => array('', '1', '2', '3'),
),
'raphf' => array(
'iniEntries' => array('2'),
'functions' => array('2'),
'releases' => array('2'),
),
'rar' => array(
'classes' => array('2'),
'constants' => array('2'),
'functions' => array('2', '3'),
'releases' => array('', '1', '2', '3', '4'),
'const' => array('', '2', '4'),
'methods' => array('', '2', '3', '4'),
),
'redis' => array(
'classes' => array('2'),
'iniEntries' => array('2', '3', '4'),
'releases' => array('2', '3', '4'),
'const' => array('2', '4'),
'methods' => array('2', '3'),
),
'riak' => array(
'classes' => array('', '1'),
'iniEntries' => array('', '1'),
'interfaces' => array('', '1'),
'releases' => array('', '1'),
'methods' => array('', '1'),
),
'session' => array(
'interfaces' => array('', '70'),
'functions' => array('', '71'),
'iniEntries' => array('', '70', '71', '73'),
'releases' => array('', '70', '71'),
),
'shmop' => array(
'releases' => array('', '70', '71'),
),
'soap' => array(
'methods' => array(''),
'releases' => array('', '70', '71'),
),
'sockets' => array(
'constants' => array('', '70'),
'functions' => array('', '70', '72'),
'releases' => array('', '70', '71'),
),
'solr' => array(
'classes' => array('', '1', '2'),
'constants' => array(''),
'functions' => array(''),
'releases' => array('', '1', '2'),
'const' => array('', '2'),
'methods' => array('', '1', '2'),
),
'sphinx' => array(
'classes' => array(''),
'constants' => array('', '1'),
'releases' => array('', '1'),
'methods' => array(''),
),
'spl' => array(
'functions' => array('', '72'),
'methods' => array('5', '70'),
'releases' => array('', '70', '71'),
),
'sqlite3' => array(
'constants' => array('', '71'),
'methods' => array(''),
'releases' => array('', '70', '71'),
),
'ssh2' => array(
'releases' => array('', '1'),
),
'stomp' => array(
'classes' => array(''),
'iniEntries' => array('', '1'),
'functions' => array('', '1'),
'releases' => array('', '1', '2'),
'methods' => array('', '1'),
),
'svn' => array(
'classes' => array(''),
'constants' => array('', '1'),
'functions' => array(''),
'releases' => array('', '1'),
),
'tidy' => array(
'releases' => array('', '70', '71'),
'methods' => array(''),
),
'tokenizer' => array(
'constants' => array('', '70')
),
'uopz' => array(
'constants' => array('2'),
'functions' => array('2', '5'),
'iniEntries' => array('2', '5', '6'),
'releases' => array('2', '5', '6'),
),
'uploadprogress' => array(
'functions' => array(''),
'iniEntries' => array(''),
'releases' => array('', '1'),
),
'varnish' => array(
'classes' => array(''),
'constants' => array(''),
'releases' => array('', '1'),
'methods' => array('', '1'),
),
'xdebug' => array(
'constants' => array('2'),
'functions' => array('1', '2'),
'iniEntries' => array('1', '2'),
'releases' => array('1', '2'),
),
'xmldiff' => array(
'classes' => array(''),
'releases' => array('', '1'),
'methods' => array(''),
),
'xmlrpc' => array(
'releases' => array('', '70', '71'),
),
'xsl' => array(
'releases' => array('', '70', '71'),
),
'zendopcache' => array(
'functions' => array('7'),
'iniEntries' => array('', '7', '71'),
'releases' => array('', '7', '71'),
),
'zip' => array(
'functions' => array('1'),
'releases' => array('1'),
'classes' => array('1'),
'methods' => array('1'),
'const' => array('1'),
),
'zlib' => array(
'functions' => array('', '72'),
'releases' => array(''),
),
);
if (array_key_exists($refName, $majorReleases)) {
$iterations = $majorReleases[$refName];
if (array_key_exists($ext, $iterations)) {
$iterations = $iterations[$ext];
} else {
$iterations = array('');
}
} else {
$iterations = array('');
}
$data = array();
foreach ($iterations as $major) {
$temp = $this->jsonFileHandler->read($refName, $ext, $major);
if (!$temp) {
if (json_last_error() == JSON_ERROR_NONE) {
// missing files are optional until all extensions are fully documented
continue;
} else {
$error = sprintf('Cannot decode file %s%s.%s.json', $refName, $major, $ext);
}
throw new \RuntimeException($error);
}
$data = array_merge($data, $temp);
}
return $data;
} | Reads splitted JSON data files | entailment |
public function convertToString($dom){
$html = $this->html5->saveHTML($dom);
$html = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'."\n".$html;
// Library HTML5 always drop xmlns.
$html = str_replace('<html', '<html xmlns="http://www.w3.org/1999/xhtml"', $html);
// Convert entities
$html = str_replace(' ', ' ', $html);
// Remove srcset
$html = preg_replace('/srcset="[^"]*"/', '', $html);
// Remove rt
$html = preg_replace('/<rp>[^<]*?<\/rp>/', '', $html);
// Remove align
$html = preg_replace('/align="(center|right|left)"/', 'class="text-$1"', $html);
// fix close tag
$html = preg_replace('/<(meta|link|img|br|param|hr)([^>]*)?>/u', '<$1$2 />', $html);
return $html;
} | Get HTML5 string
@return string | entailment |
public function saveDom( \DOMDocument $dom, $name ){
return $this->distributor->write($this->convertToString($dom), "OEBPS/Text/{$name}");
} | Save Dom as XHTML file.
@param \DOMDocument $dom
@param string $name
@return bool|string | entailment |
public function extractAssets(\DomDocument &$dom, $tag, $attr, $url_base, $doc_root ){
$paths = [];
foreach( $dom->getElementsByTagName($tag) as $elem ){
list($value) = explode('?', $elem->getAttribute($attr));
if( preg_match($url_base, $value) ){
$path = preg_replace($url_base, $doc_root, $value);
if( file_exists($path) ){
$dir = 'Asset/';
$new_path = ltrim(str_replace($doc_root, $dir, $path), DIRECTORY_SEPARATOR);
$elem->setAttribute($attr, '../'.$new_path);
// If this is CSS, extract assets
if( false !== strpos($path, '.css') ){
// Load all url context and copy them
$css = preg_replace_callback('/url\w*?\(([^)]*)\)/', function($matches) use ($path, $doc_root, $dir, &$paths){
list($asset) = explode('?', ltrim(trim(trim($matches[1]), '"'), '/'));
$asset = realpath(dirname($path).DIRECTORY_SEPARATOR.$asset);
if( file_exists($asset) ){
$asset_src = str_replace($doc_root, $dir, $asset);
if( $this->distributor->copy($asset, 'OEBPS/'.$asset_src) ){
$paths[] = $asset_src;
}
}
return $matches[0];
}, file_get_contents($path));
// Save CSS
if( $this->distributor->write($css, 'OEBPS/'.$new_path) ){
$paths[] = $new_path;
}
}else{
// Copy it
if( $this->distributor->copy($path, 'OEBPS/'.$new_path) ){
$paths[] = $new_path;
}
}
}
}
}
return $paths;
} | Extract assets
@param \DomDocument $dom
@param string $tag
@param string $attr
@param string $url_base URL base to be replaced with $doc_root
@param string $doc_root
@return array | entailment |
public function pullRemoteAssets(\DomDocument &$dom){
$paths = [];
foreach(['img' => 'src', 'script' => 'src', 'link' => 'href'] as $tag => $attr){
foreach( $dom->getElementsByTagName($tag) as $elem ){
$url = $elem->getAttribute($attr);
if( !preg_match('/^(https?:)?\/\//', $url) ){
continue;
}
// Get remote resource
if( !($resource = $this->getRemote($url)) ){
continue;
}
// Let's detect file mime
list($basename) = explode('?', basename($url));
$dir = Mime::getDestinationFolder($basename);
if( 'Misc' === $dir ){
// Oh, it might not have extension...
if( $resource['info'] ){
list($mime, $type) = explode('/', $resource['info']['content_type']);
list($ext) = explode(';', $type);
$new_dir = Mime::getDestinationFolder("hoge.{$ext}");
if( $new_dir != $dir ){
$dir = $new_dir;
$basename = "{$basename}.{$ext}";
}
}
}
// O.K.
$new_path = $dir.'/'.$basename;
$elem->setAttribute($attr, '../'.$new_path);
if( $this->distributor->write($resource['body'], 'OEBPS/'.$new_path) ){
$paths[] = $new_path;
}
}
}
return $paths;
} | Extract remote assets and save it
@param \DomDocument $dom
@return array | entailment |
public function grabHeaders(Toc &$toc, &$dom, $add_id = true, $max_depth = 3, $min_level = 1){
$headers = [];
$max_depth = max(1, min($max_depth, 6));
$min_level = max(1, $min_level);
$xpath = new \DOMXPath($dom);
$query = sprintf("//*[%s]", implode(' or ', array_map(function($depth){
return sprintf("name()='h%d'", $depth);
}, range($min_level, $max_depth))));
$counter = 0;
foreach( $xpath->query($query) as $header ){
$counter++;
/** @var \DomElement $header */
$tag_level = intval(preg_replace('/[^0-9]/u', '', $header->tagName));
if( $header->hasAttribute('id') ){
$header_id = (string)$header->getAttribute('id');
}else{
$header_id = sprintf('header%d-%03d', $tag_level, $counter);
if( $add_id ){
$header->setAttribute('id', $header_id);
}
}
$headers[$header_id] = [
'level' => $tag_level,
'content' => $header->textContent,
'children' => []
];
}
if( !$headers ){
return [];
}
$arranged = [];
foreach( $headers as $key => $header ){
if( !$this->digToc($key, $header, $arranged) ){
$arranged[$key] = $header;
}
}
$this->recursiveToc($toc, $toc->link, $arranged);
return $toc;
} | @param Toc $toc
@param $dom
@param bool|true $add_id
@param int $max_depth
@param int $min_level
@return array|Toc | entailment |
private function recursiveToc(Toc &$toc, $src, array $headers){
foreach( $headers as $id => $header ){
$child = $toc->addChild($header['content'], $src.'#'.$id);
if( $header['children'] ){
$this->recursiveToc($child, $src, $header['children']);
}
}
} | Recursively add toc
@param Toc $toc
@param string $src
@param array $headers | entailment |
private function digToc($id, array $header, array &$headers){
$keys = array_keys($headers);
krsort($keys);
$done = false;
foreach( $keys as $key ){
if( $headers[$key]['level'] < $header['level'] ){
if( !$this->digToc($id, $header, $headers[$key]['children']) ){
$headers[$key]['children'][$id] = $header;
}
return true;
}
}
return false;
} | Arrange toc elements
@param string $id
@param array $header
@param array $headers
@return bool | entailment |
public function retrieveBody($dom){
if( preg_match('/<body>(.*)<\/body>/s', $this->html5->saveHTML($dom), $match) ){
return $match[1];
}else{
return null;
}
} | @param $dom
@return null | entailment |
public function format($content){
// Add tcy
$content = $this->tcyiz($content);
// Add auto indent
$dom = $this->getDomFromString($content);
foreach( $dom->getElementsByTagName('p') as $p ){
if( !$this->need_indent($p->nodeValue) ){
$this->add_class($p, 'no-indent');
}
}
// Remove all tt, big, acronym, strike, abbr
$node_to_remove = array();
foreach( ['tt', 'big', 'acronym', 'abbr', 'strike'] as $tag){
foreach( $dom->getElementsByTagName($tag) as $elem ) {
/** @var \DOMElement $elem */
$new_elem = $dom->createElement( 'span' );
// Copy all attributes
if ( $elem->attributes ) {
foreach ( $elem->attributes as $attr ) {
$new_elem->setAttribute( $attr->nodeName, $attr->nodeValue );
}
}
// Add original tag name as class
$this->add_class($new_elem, $tag);
// Copy all nodes
foreach ( $elem->childNodes as $child ) {
$new_elem->appendChild( $elem->removeChild( $child ) );
}
$node_to_remove[] = $elem;
$elem->parentNode->replaceChild( $new_elem, $elem );
}
}
return $this->retrieveBody($dom);
} | Convert xml
@param string $content
@return mixed | entailment |
public function need_indent($string){
$first_letter = mb_substr($string, 0, 1, 'UTF-8');
$match = !preg_match('/[ 【《〔〝『「(”"\'’—\(\)]/u', $first_letter, $matches);
return (bool)$match;
} | Detect if auto-indent required
@param string $string
@return bool | entailment |
public function add_class( \DOMElement &$node, $classes){
$classes = (array)$classes;
if( $node->hasAttribute('class') ){
$classes = array_merge($classes, explode(' ', $node->getAttribute('classs')));
}
$node->setAttribute('class', implode(' ', $classes));
} | Add class to element
@param \DOMElement $node
@param array|string $classes | entailment |
public function getRemote($url){
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FAILONERROR => true,
]);
$result = curl_exec($ch);
if( false === $result ){
return false;
}
$return = [
'info' => curl_getinfo($ch),
'body' => $result,
];
curl_close($ch);
return $return;
} | Get remote assets
@param string $url
@return array|false | entailment |
public function parseFromString($string){
$dom = $this->html5->loadHTML($string);
if( is_a($dom, 'DOMDocument') ){
return $dom;
}else{
return false;
}
} | Parse HTML5 and convert to Dom document
@param $string
@return false|\DomDocument | entailment |
function nextRaw()
{
if ($this->type == self::SOURCE_FILE) {
$record = stream_get_line($this->source, File_MARC::MAX_RECORD_LENGTH, File_MARC::END_OF_RECORD);
// Remove illegal stuff that sometimes occurs between records
$record = preg_replace('/^[\\x0a\\x0d\\x00]+/', "", $record);
} elseif ($this->type == self::SOURCE_STRING) {
$record = array_shift($this->source);
}
// Exit if we are at the end of the file
if (!$record) {
return false;
}
// Append the end of record we lost during stream_get_line() or explode()
$record .= File_MARC::END_OF_RECORD;
return $record;
} | Return the next raw MARC record
Returns the next raw MARC record, unless all records already have
been read.
@return string Either a raw record or false | entailment |
private function _decode($text)
{
$marc = new $this->record_class($this);
// fallback on the actual byte length
$record_length = strlen($text);
$matches = array();
if (preg_match("/^(\d{5})/", $text, $matches)) {
// Store record length
$record_length = $matches[1];
if ($record_length != strlen($text)) {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INCORRECT_LENGTH], array("record_length" => $record_length, "actual" => strlen($text))));
// Real beats declared byte length
$record_length = strlen($text);
}
} else {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_NONNUMERIC_LENGTH], array("record_length" => substr($text, 0, 5))));
}
if (substr($text, -1, 1) != File_MARC::END_OF_RECORD)
throw new File_MARC_Exception(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_TERMINATOR], File_MARC_Exception::ERROR_INVALID_TERMINATOR);
// Store leader
$marc->setLeader(substr($text, 0, File_MARC::LEADER_LEN));
// bytes 12 - 16 of leader give offset to the body of the record
$data_start = 0 + substr($text, 12, 5);
// immediately after the leader comes the directory (no separator)
$dir = substr($text, File_MARC::LEADER_LEN, $data_start - File_MARC::LEADER_LEN - 1); // -1 to allow for \x1e at end of directory
// character after the directory must be \x1e
if (substr($text, $data_start-1, 1) != File_MARC::END_OF_FIELD) {
$marc->addWarning(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_NO_DIRECTORY]);
}
// All directory entries 12 bytes long, so length % 12 must be 0
if (strlen($dir) % File_MARC::DIRECTORY_ENTRY_LEN != 0) {
$marc->addWarning(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_LENGTH]);
}
// go through all the fields
$nfields = strlen($dir) / File_MARC::DIRECTORY_ENTRY_LEN;
for ($n=0; $n<$nfields; $n++) {
// As pack returns to key 1, leave place 0 in list empty
list(, $tag) = unpack("A3", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
list(, $len) = unpack("A3/A4", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
list(, $offset) = unpack("A3/A4/A5", substr($dir, $n*File_MARC::DIRECTORY_ENTRY_LEN, File_MARC::DIRECTORY_ENTRY_LEN));
// Check directory validity
if (!preg_match("/^[0-9A-Za-z]{3}$/", $tag)) {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG], array("tag" => $tag)));
}
if (!preg_match("/^\d{4}$/", $len)) {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_TAG_LENGTH], array("tag" => $tag, "len" => $len)));
}
if (!preg_match("/^\d{5}$/", $offset)) {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY_OFFSET], array("tag" => $tag, "offset" => $offset)));
}
if ($offset + $len > $record_length) {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_DIRECTORY], array("tag" => $tag)));
}
$tag_data = substr($text, $data_start + $offset, $len);
if (substr($tag_data, -1, 1) == File_MARC::END_OF_FIELD) {
/* get rid of the end-of-tag character */
$tag_data = substr($tag_data, 0, -1);
$len--;
} else {
$marc->addWarning(File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_FIELD_EOF], array("tag" => $tag)));
}
if (preg_match("/^\d+$/", $tag) and ($tag < 10)) {
$marc->appendField(new File_MARC_Control_Field($tag, $tag_data));
} else {
$subfields = explode(File_MARC::SUBFIELD_INDICATOR, $tag_data);
$indicators = array_shift($subfields);
if (strlen($indicators) != 2) {
$errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_INVALID_INDICATORS], array("tag" => $tag, "indicators" => $indicators));
$marc->addWarning($errorMessage);
// Do the best with the indicators we've got
if (strlen($indicators) == 1) {
$ind1 = $indicators;
$ind2 = " ";
} else {
list($ind1,$ind2) = array(" ", " ");
}
} else {
$ind1 = substr($indicators, 0, 1);
$ind2 = substr($indicators, 1, 1);
}
// Split the subfield data into subfield name and data pairs
$subfield_data = array();
foreach ($subfields as $subfield) {
if (strlen($subfield) > 0) {
$subfield_data[] = new File_MARC_Subfield(substr($subfield, 0, 1), substr($subfield, 1));
} else {
$errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_EMPTY_SUBFIELD], array("tag" => $tag));
$marc->addWarning($errorMessage);
}
}
if (!isset($subfield_data)) {
$errorMessage = File_MARC_Exception::formatError(File_MARC_Exception::$messages[File_MARC_Exception::ERROR_EMPTY_SUBFIELD], array("tag" => $tag));
$marc->addWarning($errorMessage);
}
// If the data is invalid, let's just ignore the one field
try {
$new_field = new File_MARC_Data_Field($tag, $subfield_data, $ind1, $ind2);
$marc->appendField($new_field);
} catch (Exception $e) {
$marc->addWarning($e->getMessage());
}
}
}
return $marc;
} | Decode a given raw MARC record
Port of Andy Lesters MARC::File::USMARC->decode() Perl function into PHP.
@param string $text Raw MARC record
@return File_MARC_Record Decoded File_MARC_Record object | entailment |
function toXMLFooter()
{
$this->xmlwriter->endElement(); // end collection
$this->xmlwriter->endDocument();
return $this->xmlwriter->outputMemory();
} | Returns the MARCXML collection footer
This method produces an XML representation of a MARC record that
attempts to adhere to the MARCXML standard documented at
http://www.loc.gov/standards/marcxml/
@return string representation of MARC record in MARCXML format | entailment |
public function set($file, $url, $title, $titles, $tocs, $ctime, array $depends)
{
foreach ($tocs as $toc) {
foreach ($toc as $child) {
$this->parents[$child] = $file;
if (isset($this->entries[$child])) {
$this->entries[$child]['parent'] = $file;
}
}
}
$this->entries[$file] = array(
'file' => $file,
'url' => $url,
'title' => $title,
'titles' => $titles,
'tocs' => $tocs,
'ctime' => $ctime,
'depends' => $depends
);
if (isset($this->parents[$file])) {
$this->entries[$file]['parent'] = $this->parents[$file];
}
} | Sets the meta for url, giving the title, the modification time and
the dependencies list | entailment |
public function get($url)
{
if (isset($this->entries[$url])) {
return $this->entries[$url];
} else {
return null;
}
} | Gets the meta for a given document reference url | entailment |
protected function render()
{
$this->display('* Rendering documents');
foreach ($this->documents as $file => &$document) {
$this->display(' -> Rendering '.$file.'...');
$target = $this->getTargetOf($file);
$directory = dirname($target);
if (!is_dir($directory)) {
mkdir($directory, 0755, true);
}
file_put_contents($target, $document->renderDocument());
}
} | Renders all the pending documents | entailment |
protected function addToParseQueue($file)
{
$this->states[$file] = self::PARSE;
if (!isset($this->documents[$file])) {
$this->parseQueue[$file] = $file;
}
} | Adding a file to the parse queue | entailment |
protected function parseAll()
{
$this->display('* Parsing files');
while ($file = $this->getFileToParse()) {
$this->display(' -> Parsing '.$file.'...');
// Process the file
$rst = $this->getRST($file);
$parser = new Parser(null, $this->kernel);
$environment = $parser->getEnvironment();
$environment->setMetas($this->metas);
$environment->setCurrentFilename($file);
$environment->setCurrentDirectory($this->directory);
$environment->setTargetDirectory($this->targetDirectory);
$environment->setErrorManager($this->errorManager);
$environment->setUseRelativeUrls($this->relativeUrls);
foreach ($this->beforeHooks as $hook) {
$hook($parser);
}
if (!file_exists($rst)) {
$this->errorManager->error('Can\'t parse the file '.$rst);
continue;
}
$document = $this->documents[$file] = $parser->parseFile($rst);
// Calling all the post-process hooks
foreach ($this->hooks as $hook) {
$hook($document);
}
// Calling the kernel document tweaking
$this->kernel->postParse($document);
$dependencies = $document->getEnvironment()->getDependencies();
if ($dependencies) {
$this->display(' -> Scanning dependencies of '.$file.'...');
// Scan the dependencies for this document
foreach ($dependencies as $dependency) {
$this->scan($dependency);
}
}
// Append the meta for this document
$this->metas->set(
$file,
$this->getUrl($document),
$document->getTitle(),
$document->getTitles(),
$document->getTocs(),
filectime($rst),
$dependencies
);
}
} | Parses all the document that need to be parsed | entailment |
public function scan($file)
{
// If no decision is already made about this file
if (!isset($this->states[$file])) {
$this->display(' -> Scanning '.$file.'...');
$this->states[$file] = self::NO_PARSE;
$entry = $this->metas->get($file);
$rst = $this->getRST($file);
if (!$entry || !file_exists($rst) || $entry['ctime'] < filectime($rst)) {
// File was never seen or changed and thus need to be parsed
$this->addToParseQueue($file);
} else {
// Have a look to the file dependencies to knoww if you need to parse
// it or not
$depends = $entry['depends'];
if (isset($entry['parent'])) {
$depends[] = $entry['parent'];
}
foreach ($depends as $dependency) {
$this->scan($dependency);
// If any dependency needs to be parsed, this file needs also to be
// parsed
if ($this->states[$dependency] == self::PARSE) {
$this->addToParseQueue($file);
}
}
}
}
} | Scans a file, this will check the status of the file and tell if it
needs to be parsed or not | entailment |
public function scanMetas()
{
$entries = $this->metas->getAll();
foreach ($entries as $file => $infos) {
$this->scan($file);
}
} | Scans all the metas | entailment |
protected function saveMetas()
{
$metas = '<?php return '.var_export($this->metas->getAll(), true).';';
file_put_contents($this->getMetaFile(), $metas);
} | Saving the meta files | entailment |
public function getTargetOf($file)
{
$meta = $this->metas->get($file);
return $this->getTargetFile($meta['url']);
} | Gets the name of a target for a file, for instance /introduction/part1 could
be resolved into /path/to/introduction/part1.html | entailment |
public function getUrl($document)
{
$environment = $document->getEnvironment();
return $environment->getUrl() . '.' . $this->kernel->getFileExtension();
} | Gets the URL of a target file | entailment |
public function doCopy()
{
foreach ($this->toCopy as $copy) {
list($source, $destination) = $copy;
if (!$this->isAbsolute($source)) {
$source = $this->getSourceFile($source);
}
$destination = $this->getTargetFile($destination);
if (is_dir($source) && is_dir($destination)) {
$destination = dirname($destination);
}
shell_exec('cp -R '.$source.' '.$destination);
}
} | Run the copy | entailment |
public function copy($source, $destination = null)
{
if ($destination === null) {
$destination = basename($source);
}
$this->toCopy[] = array($source, $destination);
return $this;
} | Add a file to copy | entailment |
public function doMkdir()
{
foreach ($this->toMkdir as $mkdir) {
$dir = $this->getTargetFile($mkdir);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
}
} | Run the directories creation | entailment |
public function run()
{
Yii::$app->response->format = Response::FORMAT_RAW;
(new \elFinderConnector(new \elFinder($this->options)))->run();
} | {@inheritdoc} | entailment |
public function disconnect()
{
if (!$this->isConnected || $this->isDisconnecting) {
return new RejectedPromise(new \LogicException('The client is not connected.'));
}
$this->isDisconnecting = true;
$deferred = new Deferred();
$this->startFlow(new OutgoingDisconnectFlow($this->connection), true)
->then(function (Connection $connection) use ($deferred) {
$this->isDisconnecting = false;
$this->isConnected = false;
$this->emit('disconnect', [$connection, $this]);
$deferred->resolve($connection);
if ($this->stream !== null) {
$this->stream->close();
}
})
->otherwise(function () use ($deferred) {
$this->isDisconnecting = false;
$deferred->reject($this->connection);
});
return $deferred->promise();
} | Disconnects from a broker.
@return ExtendedPromiseInterface | entailment |
public function subscribe(Subscription $subscription)
{
if (!$this->isConnected) {
return new RejectedPromise(new \LogicException('The client is not connected.'));
}
return $this->startFlow(new OutgoingSubscribeFlow([$subscription], $this->identifierGenerator));
} | Subscribes to a topic filter.
@param Subscription $subscription
@return ExtendedPromiseInterface | entailment |
public function unsubscribe(Subscription $subscription)
{
if (!$this->isConnected) {
return new RejectedPromise(new \LogicException('The client is not connected.'));
}
return $this->startFlow(new OutgoingUnsubscribeFlow([$subscription], $this->identifierGenerator));
} | Unsubscribes from a topic filter.
@param Subscription $subscription
@return ExtendedPromiseInterface | entailment |
public function publish(Message $message)
{
if (!$this->isConnected) {
return new RejectedPromise(new \LogicException('The client is not connected.'));
}
return $this->startFlow(new OutgoingPublishFlow($message, $this->identifierGenerator));
} | Publishes a message.
@param Message $message
@return ExtendedPromiseInterface | entailment |
public function publishPeriodically($interval, Message $message, callable $generator)
{
if (!$this->isConnected) {
return new RejectedPromise(new \LogicException('The client is not connected.'));
}
$deferred = new Deferred();
$this->timer[] = $this->loop->addPeriodicTimer(
$interval,
function () use ($message, $generator, $deferred) {
$this->publish($message->withPayload($generator($message->getTopic())))->then(
function ($value) use ($deferred) {
$deferred->notify($value);
},
function (\Exception $e) use ($deferred) {
$deferred->reject($e);
}
);
}
);
return $deferred->promise();
} | Calls the given generator periodically and publishes the return value.
@param int $interval
@param Message $message
@param callable $generator
@return ExtendedPromiseInterface | entailment |
private function establishConnection($host, $port, $timeout)
{
$deferred = new Deferred();
$timer = $this->loop->addTimer(
$timeout,
function () use ($deferred, $timeout) {
$exception = new \RuntimeException(sprintf('Connection timed out after %d seconds.', $timeout));
$deferred->reject($exception);
}
);
$this->connector->connect($host.':'.$port)
->always(function () use ($timer) {
$this->loop->cancelTimer($timer);
})
->then(function (DuplexStreamInterface $stream) use ($deferred) {
$stream->on('data', function ($data) {
$this->handleReceive($data);
});
$stream->on('close', function () {
$this->handleClose();
});
$stream->on('error', function (\Exception $e) {
$this->handleError($e);
});
$deferred->resolve($stream);
})
->otherwise(function (\Exception $e) use ($deferred) {
$deferred->reject($e);
});
return $deferred->promise();
} | Establishes a network connection to a server.
@param string $host
@param int $port
@param int $timeout
@return ExtendedPromiseInterface | entailment |
private function registerClient(Connection $connection, $timeout)
{
$deferred = new Deferred();
$responseTimer = $this->loop->addTimer(
$timeout,
function () use ($deferred, $timeout) {
$exception = new \RuntimeException(sprintf('No response after %d seconds.', $timeout));
$deferred->reject($exception);
}
);
$this->startFlow(new OutgoingConnectFlow($connection, $this->identifierGenerator), true)
->always(function () use ($responseTimer) {
$this->loop->cancelTimer($responseTimer);
})->then(function (Connection $connection) use ($deferred) {
$this->timer[] = $this->loop->addPeriodicTimer(
floor($connection->getKeepAlive() * 0.75),
function () {
$this->startFlow(new OutgoingPingFlow());
}
);
$deferred->resolve($connection);
})->otherwise(function (\Exception $e) use ($deferred) {
$deferred->reject($e);
});
return $deferred->promise();
} | Registers a new client with the broker.
@param Connection $connection
@param int $timeout
@return ExtendedPromiseInterface | entailment |
private function handleReceive($data)
{
if (!$this->isConnected && !$this->isConnecting) {
return;
}
$flowCount = count($this->receivingFlows);
$packets = $this->parser->push($data);
foreach ($packets as $packet) {
$this->handlePacket($packet);
}
if ($flowCount > count($this->receivingFlows)) {
$this->receivingFlows = array_values($this->receivingFlows);
}
$this->handleSend();
} | Handles incoming data.
@param string $data | entailment |
private function handlePacket(Packet $packet)
{
switch ($packet->getPacketType()) {
case Packet::TYPE_PUBLISH:
/* @var PublishRequestPacket $packet */
$message = new DefaultMessage(
$packet->getTopic(),
$packet->getPayload(),
$packet->getQosLevel(),
$packet->isRetained(),
$packet->isDuplicate()
);
$this->startFlow(new IncomingPublishFlow($message, $packet->getIdentifier()));
break;
case Packet::TYPE_CONNACK:
case Packet::TYPE_PINGRESP:
case Packet::TYPE_SUBACK:
case Packet::TYPE_UNSUBACK:
case Packet::TYPE_PUBREL:
case Packet::TYPE_PUBACK:
case Packet::TYPE_PUBREC:
case Packet::TYPE_PUBCOMP:
$flowFound = false;
foreach ($this->receivingFlows as $index => $flow) {
if ($flow->accept($packet)) {
$flowFound = true;
unset($this->receivingFlows[$index]);
$this->continueFlow($flow, $packet);
break;
}
}
if (!$flowFound) {
$this->emitWarning(
new \LogicException(sprintf('Received unexpected packet of type %d.', $packet->getPacketType()))
);
}
break;
default:
$this->emitWarning(
new \LogicException(sprintf('Cannot handle packet of type %d.', $packet->getPacketType()))
);
}
} | Handles an incoming packet.
@param Packet $packet | entailment |
private function handleSend()
{
$flow = null;
if ($this->writtenFlow !== null) {
$flow = $this->writtenFlow;
$this->writtenFlow = null;
}
if (count($this->sendingFlows) > 0) {
$this->writtenFlow = array_shift($this->sendingFlows);
$this->stream->write($this->writtenFlow->getPacket());
}
if ($flow !== null) {
if ($flow->isFinished()) {
$this->loop->nextTick(function () use ($flow) {
$this->finishFlow($flow);
});
} else {
$this->receivingFlows[] = $flow;
}
}
} | Handles outgoing packets. | entailment |
private function handleClose()
{
foreach ($this->timer as $timer) {
$this->loop->cancelTimer($timer);
}
$connection = $this->connection;
$this->isConnecting = false;
$this->isDisconnecting = false;
$this->isConnected = false;
$this->connection = null;
$this->stream = null;
if ($connection !== null) {
$this->emit('close', [$connection, $this]);
}
} | Handles closing of the stream. | entailment |
private function startFlow(Flow $flow, $isSilent = false)
{
try {
$packet = $flow->start();
} catch (\Exception $e) {
$this->emitError($e);
return new RejectedPromise($e);
}
$deferred = new Deferred();
$internalFlow = new ReactFlow($flow, $deferred, $packet, $isSilent);
if ($packet !== null) {
if ($this->writtenFlow !== null) {
$this->sendingFlows[] = $internalFlow;
} else {
$this->stream->write($packet);
$this->writtenFlow = $internalFlow;
$this->handleSend();
}
} else {
$this->loop->nextTick(function () use ($internalFlow) {
$this->finishFlow($internalFlow);
});
}
return $deferred->promise();
} | Starts the given flow.
@param Flow $flow
@param bool $isSilent
@return ExtendedPromiseInterface | entailment |
private function continueFlow(ReactFlow $flow, Packet $packet)
{
try {
$response = $flow->next($packet);
} catch (\Exception $e) {
$this->emitError($e);
return;
}
if ($response !== null) {
if ($this->writtenFlow !== null) {
$this->sendingFlows[] = $flow;
} else {
$this->stream->write($response);
$this->writtenFlow = $flow;
$this->handleSend();
}
} elseif ($flow->isFinished()) {
$this->loop->nextTick(function () use ($flow) {
$this->finishFlow($flow);
});
}
} | Continues the given flow.
@param ReactFlow $flow
@param Packet $packet | entailment |
private function finishFlow(ReactFlow $flow)
{
if ($flow->isSuccess()) {
if (!$flow->isSilent()) {
$this->emit($flow->getCode(), [$flow->getResult(), $this]);
}
$flow->getDeferred()->resolve($flow->getResult());
} else {
$result = new \RuntimeException($flow->getErrorMessage());
$this->emitWarning($result);
$flow->getDeferred()->reject($result);
}
} | Finishes the given flow.
@param ReactFlow $flow | entailment |
public function elementValue(FormRuntime $formRuntime, RootRenderableInterface $element)
{
$request = $formRuntime->getRequest();
/** @var Result $validationResults */
$validationResults = $formRuntime->getRequest()->getInternalArgument('__submittedArgumentValidationResults');
if ($validationResults !== null && $validationResults->forProperty($element->getIdentifier())->hasErrors()) {
return $this->getLastSubmittedFormData($request, $element->getIdentifier());
}
return ObjectAccess::getPropertyPath($formRuntime, $element->getIdentifier());
} | Returns the value of a given Form Element.
If there are validation errors for the element, the previously submitted value will be returned.
@param FormRuntime $formRuntime The current FormRuntime instance
@param RootRenderableInterface $element The element to fetch the value for
@return mixed|null | entailment |
private function getLastSubmittedFormData(ActionRequest $request, string $propertyPath)
{
$submittedArguments = $request->getInternalArgument('__submittedArguments');
if ($submittedArguments === null) {
return null;
}
return ObjectAccess::getPropertyPath($submittedArguments, $propertyPath);
} | Return the submitted data for a given $propertyPath
@see elementValue()
@param ActionRequest $request
@param string $propertyPath
@return mixed|null | entailment |
public function hasValidationErrors(FormRuntime $formRuntime, RootRenderableInterface $element): bool
{
return $this->getValidationResult($formRuntime, $element)->hasErrors();
} | Whether the given Form Element has validation errors
@param FormRuntime $formRuntime
@param RootRenderableInterface $element
@return bool | entailment |
public function validationErrors(FormRuntime $formRuntime, RootRenderableInterface $element): array
{
return $this->getValidationResult($formRuntime, $element)->getErrors();
} | Returns all validation errors for a given Form Element
@param FormRuntime $formRuntime
@param RootRenderableInterface $element
@return array | entailment |
private function getValidationResult(FormRuntime $formRuntime, RootRenderableInterface $element): Result
{
/** @var Result $validationResults */
$validationResults = $formRuntime->getRequest()->getInternalArgument('__submittedArgumentValidationResults');
if ($validationResults === null) {
return new Result();
}
return $validationResults->forProperty($element->getIdentifier());
} | Retrieves the validation result object for a given Form Element
@see hasValidationErrors()
@see validationErrors()
@param FormRuntime $formRuntime
@param RootRenderableInterface $element
@return Result | entailment |
public function identifier($object): string
{
if (is_array($object) && isset($object['__identity'])) {
return $object['__identity'];
}
if (is_string($object)) {
return $object;
}
if (!is_object($object)) {
return '';
}
return (string)$this->persistenceManager->getIdentifierByObject($object);
} | Returns the persistence identifier for a given object (Or an empty string if the given $object is no entity)
@param mixed $object
@return string | entailment |
public function translateAndEscapeProperty(AbstractRenderable $element, string $property): string
{
return $this->escape($this->translateProperty($element, $property));
} | Translates the property of a given Form Element and htmlspecialchar's the result
@param AbstractRenderable $element
@param string $property
@return string | entailment |
public function translateProperty(AbstractRenderable $element, string $property): string
{
if ($property === 'label') {
$defaultValue = $element->getLabel();
if ($defaultValue === null) {
$defaultValue = '';
}
} elseif ($element instanceof FormElementInterface) {
$defaultValue = isset($element->getProperties()[$property]) ? (string)$element->getProperties()[$property] : '';
} else {
$defaultValue = '';
}
$translationId = sprintf('forms.elements.%s.%s', $element->getIdentifier(), $property);
return $this->translate($element, $translationId, $defaultValue);
} | Translates the property of a given Form Element
@param AbstractRenderable $element
@param string $property
@return string | entailment |
public function translate(RootRenderableInterface $element, string $translationId, string $defaultValue): string
{
$renderingOptions = $element->getRenderingOptions();
if (!isset($renderingOptions['translationPackage'])) {
return $defaultValue;
}
try {
$translation = $this->translator->translateById($translationId, [], null, null, 'Main', $renderingOptions['translationPackage']);
} catch (ResourceException $exception) {
return $defaultValue;
}
return $translation ?? $defaultValue;
} | Translates arbitrary $tanslationIds using the package configured in the Form Element's renderingOptions
@param RootRenderableInterface $element
@param string $translationId
@param string $defaultValue
@return string | entailment |
public function run()
{
$id = Yii::$app->request->getQueryParam('id');
$id = Html::encode($id);
$multiple = Yii::$app->request->getQueryParam('multiple');
if (!empty($multiple)) {
$this->settings['commandsOptions']['getfile']['multiple'] = true;
$callback = <<<JSEXP
function (files) {
var urls = [], separator = "{$this->separator}", el = window.opener.jQuery("#$id"), value = el.val();
for (var i in files) {
urls.push(files[i].url);
}
if (el.prop("tagName").toLowerCase() == "textarea") separator = "{$this->textareaSeparator}";
if (value) {
el.val(value + separator + urls.join(separator)).trigger("change");
} else {
el.val(urls.join(separator)).trigger("change");
}
window.close();
}
JSEXP;
} else {
$callback = <<<JSEXP
function (file) {
window.opener.jQuery("#$id").val(file.url).trigger("change");
window.close();
}
JSEXP;
}
$this->settings['getFileCallback'] = new JsExpression($callback);
return parent::run();
} | {@inheritdoc} | entailment |
public static function getFilePickerCallback($url, $popupSettings = [], $view = null)
{
$default = [
'title' => 'elFinder',
'width' => 900,
'height' => 500,
];
$settings = array_merge($default, $popupSettings);
$settings['file'] = Url::to($url);
$encodedSettings = Json::htmlEncode($settings);
if ($view === null) {
$view = Yii::$app->view;
}
HelperAsset::register($view);
return new JsExpression("alexantr.elFinder.filePickerCallback($encodedSettings)");
} | Callback for TinyMCE 4 file_picker_callback
@param array|string $url Url to TinyMCEAction
@param array $popupSettings TinyMCE popup settings
@param \yii\web\View|null $view
@return JsExpression | entailment |
public function generate($random = null) {
$results = [];
$plaintext = $this->_convert($random ?: $this->_random(8));
// String is already normalized by used alphabet.
$part = $try = 0;
while (count($results) < $this->_parts) {
$result = substr($plaintext, $try * $this->_partLength, $this->_partLength - 1);
if (!$result || strlen($result) !== $this->_partLength - 1) {
throw new Exception('Ran out of plaintext.');
}
$result .= $this->_checkdigitAlg1($part + 1, $result);
$try++;
if ($this->_isBadWord($result) || $this->_isValidWhenSwapped($result)) {
continue;
}
$part++;
$results[] = $result;
}
return implode('-', $results);
} | Generates a coupon code using the format `XXXX-XXXX-XXXX`.
The 4th character of each part is a checkdigit.
Not all letters and numbers are used, so if a person enters the letter 'O' we
can automatically correct it to the digit '0' (similarly for I => 1, S => 5, Z
=> 2).
The code generation algorithm avoids 'undesirable' codes. For example any code
in which transposed characters happen to result in a valid checkdigit will be
skipped. Any generated part which happens to spell an 'inappropriate' 4-letter
word (e.g.: 'P00P') will also be skipped.
@param string $random Allows to directly support a plaintext i.e. for testing.
@return string Dash separated and normalized code. | entailment |
public function validate($code) {
$code = $this->_normalize($code, ['clean' => true, 'case' => true]);
if (strlen($code) !== ($this->_parts * $this->_partLength)) {
return false;
}
$parts = str_split($code, $this->_partLength);
foreach ($parts as $number => $part) {
$expected = substr($part, -1);
$result = $this->_checkdigitAlg1($number + 1, $x = substr($part, 0, strlen($part) - 1));
if ($result !== $expected) {
return false;
}
}
return true;
} | Validates given code. Codes are not case sensitive and
certain letters i.e. `O` are converted to digit equivalents
i.e. `0`.
@param $code string Potentially unnormalized code.
@return boolean | entailment |
protected function _checkdigitAlg1($partNumber, $value) {
$symbolsFlipped = array_flip($this->_symbols);
$result = $partNumber;
foreach (str_split($value) as $char) {
$result = $result * 19 + $symbolsFlipped[$char];
}
return $this->_symbols[$result % (count($this->_symbols) - 1)];
} | Implements the checkdigit algorithm #1 as used by the original library.
@param integer $partNumber Number of the part.
@param string $value Actual part without the checkdigit.
@return string The checkdigit symbol. | entailment |
public function normalize($string) {
$string = $this->_normalize($string, ['clean' => true, 'case' => true]);
return implode('-', str_split($string, $this->_partLength));
} | Normalizes a given code using dash separators.
@param string $string
@return string | entailment |
protected function _convert($string) {
$symbols = $this->_symbols;
$result = array_map(function($value) use ($symbols) {
return $symbols[ord($value) & (count($symbols) - 1)];
}, str_split(hash('sha1', $string)));
return implode('', $result);
} | Converts givens string using symbols.
@param string $string
@return string | entailment |
protected function _normalize($string, array $options = []) {
$options += [
'clean' => false,
'case' => false
];
if ($options['case']) {
$string = strtoupper($string);
}
$string = strtr($string, [
'I' => 1,
'O' => 0,
'S' => 5,
'Z' => 2,
]);
if ($options['clean']) {
$string = preg_replace('/[^0-9A-Z]+/', '', $string);
}
return $string;
} | Internal method to normalize given strings.
@param string $string
@param array $options
@return string | entailment |
protected function _random($bytes) {
if (is_readable('/dev/urandom')) {
$stream = fopen('/dev/urandom', 'rb');
$result = fread($stream, $bytes);
fclose($stream);
return $result;
}
if (function_exists('mcrypt_create_iv')) {
return mcrypt_create_iv($bytes, MCRYPT_DEV_RANDOM);
}
throw new Exception("No source for generating a cryptographically secure seed found.");
} | Generates a cryptographically secure sequence of bytes.
@param integer $bytes Number of bytes to return.
@return string | entailment |
public function process($data)
{
$self = $this;
$environment = $this->parser->getEnvironment();
$span = $this->escape($data);
// Emphasis
$span = preg_replace_callback('/\*\*(.+)\*\*/mUsi', function ($matches) use ($self) {
return $self->strongEmphasis($matches[1]);
}, $span);
$span = preg_replace_callback('/\*(.+)\*/mUsi', function ($matches) use ($self) {
return $self->emphasis($matches[1]);
}, $span);
// Nbsp
$span = preg_replace('/~/', $this->nbsp(), $span);
// Replacing variables
$span = preg_replace_callback('/\|(.+)\|/mUsi', function($match) use ($environment) {
return $environment->getVariable($match[1]);
}, $span);
// Adding brs when a space is at the end of a line
$span = preg_replace('/ \n/', $this->br(), $span);
return $span;
} | Processes some data in the context of the span, this will process the
**emphasis**, the nbsp, replace variables and end-of-line brs | entailment |
public function render()
{
$environment = $this->parser->getEnvironment();
$span = $this->process($this->span);
// Replacing tokens
if ($this->tokens) {
foreach ($this->tokens as $id => $value) {
switch ($value['type']) {
case 'raw':
$span = str_replace($id, $value['text'], $span);
break;
case 'literal':
$span = str_replace($id, $this->literal($value['text']), $span);
break;
case 'reference':
$reference = $environment->resolve($value['section'], $value['url']);
$link = $this->reference($reference, $value);
$span = str_replace($id, $link, $span);
break;
case 'link':
if ($value['url']) {
if ($environment->useRelativeUrls()) {
$url = $environment->relativeUrl($value['url']);
} else {
$url = $value['url'];
}
} else {
$url = $environment->getLink($value['link']);
}
$link = $this->link($url, $this->process($value['link']));
$span = str_replace($id, $link, $span);
break;
}
}
}
return $span;
} | Renders the span | entailment |
public function getHolidaysByYear($year)
{
$easter = $this->getEasterDates($year);
return array(
'01-01' => $this->createData('1. nyttårsdag'),
'05-01' => $this->createData('1. mai'),
'05-17' => $this->createData('Grunnlovsdagen'),
'12-25' => $this->createData('1. juledag'),
'12-26' => $this->createData('2. juledag'),
// Variable dates
$easter['maundyThursday']->format(self::DATE_FORMAT) => $this->createData('Skjærtorsdag'),
$easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Langfredag'),
$easter['easterSunday']->format(self::DATE_FORMAT) => $this->createData('1. påskedag'),
$easter['easterMonday']->format(self::DATE_FORMAT) => $this->createData('2. påskedag'),
$easter['ascensionDay']->format(self::DATE_FORMAT) => $this->createData('Kristi Himmelfartsdag'),
$easter['pentecostMonday']->format(self::DATE_FORMAT) => $this->createData('2. pinsedag'),
);
} | @param int $year
@return mixed | entailment |
private function createSunday($year)
{
$easterSunday = new \DateTime('21.03.' . $year);
$easterSunday->modify(sprintf('+%d days', easter_days($year)));
return $easterSunday;
} | Creating easter sunday
@param $year
@return \DateTime | entailment |
private function createOrthodoxSunday($year)
{
$a = $year % 4;
$b = $year % 7;
$c = $year % 19;
$d = (19 * $c + 15) % 30;
$e = (2 * $a + 4 * $b - $d + 34) % 7;
$month = floor(($d + $e + 114) / 31);
$day = (($d + $e + 114) % 31) + 1;
$sunday = mktime(0, 0, 0, $month, $day + 13, $year);
return new \DateTime(date('Y-m-d', $sunday));
} | Creating Orthodox easter sunday
@param $year
@return \DateTime | entailment |
protected function getEasterDates($year, $orthodox = false)
{
$easterSunday = $orthodox ? $this->createOrthodoxSunday($year) : $this->createSunday($year);
$easterSunday->setTimezone(new \DateTimeZone(date_default_timezone_get()));
$easterMonday = clone $easterSunday;
$easterMonday->modify('+1 day');
$maundyThursday = clone $easterSunday;
$maundyThursday->modify('-3 days');
$goodFriday = clone $easterSunday;
$goodFriday->modify('-2 days');
$saturday = clone $easterSunday;
$saturday->modify('-1 days');
$ascensionDay = clone $easterSunday;
$ascensionDay->modify('+39 days');
$shroveTuesday = clone $easterSunday;
$shroveTuesday->modify('-47 days');
$pentecostSunday = clone $easterSunday;
$pentecostSunday->modify('+49 days');
$pentecostMonday = clone $pentecostSunday;
$pentecostMonday->modify('+1 days');
$pentecostSaturday = clone $pentecostSunday;
$pentecostSaturday->modify('-1 days');
$corpusChristi = clone $easterSunday;
$corpusChristi->modify('+60 days');
return array(
'shroveTuesday' => $shroveTuesday,
'maundyThursday' => $maundyThursday,
'easterSunday' => $easterSunday,
'easterMonday' => $easterMonday,
'saturday' => $saturday,
'goodFriday' => $goodFriday,
'ascensionDay' => $ascensionDay,
'pentecostSaturday' => $pentecostSaturday,
'pentecostSunday' => $pentecostSunday,
'pentecostMonday' => $pentecostMonday,
'corpusChristi' => $corpusChristi
);
} | Returns all dates calculated by easter sunday
@param int $year
@param boolean $orthodox
@return \DateTime[] | entailment |
public function getParent()
{
if (!$this->currentFileName || !$this->metas) {
return null;
}
$meta = $this->metas->get($this->currentFileName);
if (!$meta || !isset($meta['parent'])) {
return null;
}
$parent = $this->metas->get($meta['parent']);
if (!$parent) {
return null;
}
return $parent;
} | Get my parent metas | entailment |
public function getMyToc()
{
$parent = $this->getParent();
if ($parent) {
foreach ($parent['tocs'] as $toc) {
if (in_array($this->currentFileName, $toc)) {
$before = array();
$after = $toc;
while ($after) {
$file = array_shift($after);
if ($file == $this->currentFileName) {
return array($before, $after);
}
$before[] = $file;
}
}
}
}
return null;
} | Get the docs involving this document | entailment |
public function registerReference(Reference $reference)
{
$name = $reference->getName();
$this->references[$name] = $reference;
} | Registers a new reference | entailment |
public function resolve($section, $data)
{
if (isset($this->references[$section])) {
$reference = $this->references[$section];
return $reference->resolve($this, $data);
}
$this->errorManager->error('Unknown reference section '.$section);
} | Resolves a reference | entailment |
public function createTitle($level)
{
for ($currentLevel=0; $currentLevel<16; $currentLevel++) {
if ($currentLevel > $level) {
$this->levels[$currentLevel] = 1;
$this->counters[$currentLevel] = 0;
}
}
$this->levels[$level] = 1;
$this->counters[$level]++;
$token = array('title');
for ($i=1; $i<=$level; $i++) {
$token[] = $this->counters[$i];
}
return implode('.', $token);
} | Title level | entailment |
public function setLink($name, $url)
{
$name = trim(strtolower($name));
if ($name == '_') {
$name = array_shift($this->anonymous);
}
$this->links[$name] = trim($url);
} | Set the link url | entailment |
public function getLink($name, $relative = true)
{
$name = trim(strtolower($name));
if (isset($this->links[$name])) {
$link = $this->links[$name];
if ($relative) {
return $this->relativeUrl($link);
}
return $link;
}
return null;
} | Get a link value | entailment |
public function relativeUrl($url)
{
// If string contains ://, it is considered as absolute
if (preg_match('/:\\/\\//mUsi', $url)) {
return $url;
}
// If string begins with "/", the "/" is removed to resolve the
// relative path
if (strlen($url) && $url[0] == '/') {
$url = substr($url, 1);
if ($this->samePrefix($url)) {
// If the prefix is the same, simply returns the file name
$relative = basename($url);
} else {
// Else, returns enough ../ to get upper
$relative = '';
for ($k=0; $k<$this->getDepth(); $k++) {
$relative .= '../';
}
$relative .= $url;
}
} else {
$relative = $url;
}
return $relative;
} | Resolves a relative URL using directories, for instance, if the
current directory is "path/to/something", and you want to get the
relative URL to "path/to/something/else.html", the result will
be else.html. Else, "../" will be added to go to the upper directory | entailment |
protected function samePrefix($url)
{
$partsA = explode('/', $url);
$partsB = explode('/', $this->currentFileName);
$n = count($partsA);
if ($n != count($partsB)) {
return false;
}
unset($partsA[$n-1]);
unset($partsB[$n-1]);
return $partsA == $partsB;
} | Returns true if the given url have the same prefix as the
current document | entailment |
protected function canonicalize($url)
{
$parts = explode('/', $url);
$stack = array();
foreach ($parts as $part) {
if ($part == '..') {
array_pop($stack);
} else {
$stack[] = $part;
}
}
return implode('/', $stack);
} | Canonicalize a path, a/b/c/../d/e will become
a/b/d/e | entailment |
public function canonicalUrl($url)
{
if (strlen($url)) {
if ($url[0] == '/') {
// If the URL begins with a "/", the following is the
// canonical URL
return substr($url, 1);
} else {
// Else, the canonical name is under the current dir
if ($this->getDirName()) {
return $this->canonicalize($this->getDirName() . '/' .$url);
} else {
return $this->canonicalize($url);
}
}
}
return null;
} | Gets a canonical URL from the given one | entailment |
public function init()
{
parent::init();
if ($this->connectorRoute === null) {
throw new InvalidConfigException('Connector route must be specified.');
}
$this->settings['url'] = Url::toRoute($this->connectorRoute);
if (!isset($this->settings['lang'])) {
$this->settings['lang'] = Yii::$app->language;
} elseif ($this->settings['lang'] === false) {
unset($this->settings['lang']);
}
$this->settings['customData'] = [
Yii::$app->request->csrfParam => Yii::$app->request->csrfToken,
];
} | {@inheritdoc}
@throws InvalidConfigException | entailment |
public function run()
{
$id = $this->getId();
$view = $this->getView();
if ($this->buttonNoConflict) {
$view->registerJs('if (jQuery.fn.button.noConflict) { jQuery.fn.btn = jQuery.fn.button.noConflict(); }');
}
$bundle = ElFinderAsset::register($view);
if (isset($this->settings['lang'])) {
$this->settings['lang'] = $this->checkLanguage($this->settings['lang']);
if (is_file($bundle->basePath . '/js/i18n/elfinder.' . $this->settings['lang'] . '.js')) {
$view->registerJsFile($bundle->baseUrl . '/js/i18n/elfinder.' . $this->settings['lang'] . '.js', [
'depends' => [ElFinderAsset::className()],
]);
} else {
unset($this->settings['lang']);
}
}
$this->settings['baseUrl'] = $bundle->baseUrl . '/';
$this->settings['soundPath'] = $bundle->baseUrl . '/sounds';
if (!isset($this->settings['height'])) {
$this->settings['height'] = '100%';
} elseif ($this->settings['height'] === false) {
unset($this->settings['height']);
}
$settings = Json::encode($this->settings);
$view->registerJs("jQuery('#$id').elfinder($settings);");
return "<div id=\"$id\"></div>";
} | {@inheritdoc} | entailment |
protected function checkLanguage($language)
{
$full_language = mb_strtolower($language);
$lang = substr($full_language, 0, 2);
if ($lang == 'jp') {
$lang = 'ja';
} elseif ($lang == 'pt') {
$lang = 'pt_BR';
} elseif ($lang == 'ug') {
$lang = 'ug_CN';
} elseif ($lang == 'zh') {
$lang = ($full_language == 'zh-tw' || $full_language == 'zh_tw') ? 'zh_TW' : 'zh_CN';
} elseif ($lang == 'be') {
// for belarusian use russian instead english
$lang = 'ru';
}
return $lang;
} | Set elFinder's correct "lang" param
@param string $language
@return string | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.