_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q245600 | Utf8.addSpecial | validation | public static function addSpecial($special)
{
$special = (array) $special;
foreach ($special as $char) {
self::$special[] = $char;
}
} | php | {
"resource": ""
} |
q245601 | Utf8.dump | validation | public static function dump($str, $useHtml = false, $sanitizeNonBinary = false)
{
self::$useHtml = $useHtml;
self::$sanitizeNonBinary = $sanitizeNonBinary;
self::setStr($str);
$controlCharAs = 'other'; // how should we treat ascii control chars?
$curBlockType = 'utf8'; // utf8, utf8special, other
$newBlockType = null;
$curBlockStart = 0; // string offset
$strNew = '';
while (self::$curI < self::$stats['strLen']) {
$curI = self::$curI;
$isUtf8 = self::isOffsetUtf8($isSpecial, true);
if ($isUtf8 && $isSpecial && $controlCharAs !== 'utf8special' && \ord($str[$curI]) < 0x80) {
if ($controlCharAs == 'other') {
$isUtf8 = false;
} elseif ($controlCharAs == 'utf8') {
$isSpecial = false;
}
}
if ($isUtf8) {
if ($isSpecial) {
// control-char or special
if ($curBlockType !== 'utf8special') {
$newBlockType = 'utf8special';
}
} else {
// plain-ol-utf8
if ($curBlockType !== 'utf8') {
$newBlockType = 'utf8';
}
}
} else {
// not a valid utf-8 character
if ($curBlockType !== 'other') {
$newBlockType = 'other';
}
}
if ($newBlockType) {
$len = $curI - $curBlockStart;
self::incStat($curBlockType, $len);
$subStr = \substr(self::$str, $curBlockStart, $len);
$strNew .= self::dumpBlock($subStr, $curBlockType);
$curBlockStart = $curI;
$curBlockType = $newBlockType;
$newBlockType = null;
}
}
$len = self::$stats['strLen'] - $curBlockStart;
self::incStat($curBlockType, $len);
if (self::$stats['strLen']) {
$percentOther = (self::$stats['bytesOther']) / self::$stats['strLen'] * 100;
if ($percentOther > 33) {
$strNew = self::dumpBlock($str, 'other', array('prefix'=>false));
} else {
$subStr = \substr(self::$str, $curBlockStart, $len);
$strNew .= self::dumpBlock($subStr, $curBlockType);
}
}
return $strNew;
} | php | {
"resource": ""
} |
q245602 | Utf8.isUtf8 | validation | public static function isUtf8($str, &$special = false)
{
self::setStr($str);
$special = false;
while (self::$curI < self::$stats['strLen']) {
$isUtf8 = self::isOffsetUtf8($isSpecial); // special is only checking control chars
if (!$isUtf8) {
return false;
}
if ($isSpecial) {
$special = true;
}
}
$special = $special || self::hasSpecial($str);
return true;
} | php | {
"resource": ""
} |
q245603 | Utf8.ordUtf8 | validation | public static function ordUtf8($str, &$offset = 0, &$char = null)
{
$code = \ord($str[$offset]);
$numBytes = 1;
if ($code >= 0x80) { // otherwise 0xxxxxxx
if ($code < 0xe0) { // 110xxxxx
$numBytes = 2;
$code -= 0xC0;
} elseif ($code < 0xf0) { // 1110xxxx
$numBytes = 3;
$code -= 0xE0;
} elseif ($code < 0xf8) {
$numBytes = 4; // 11110xxx
$code -= 0xF0;
}
for ($i = 1; $i < $numBytes; $i++) {
$code2 = \ord($str[$offset + $i]) - 0x80; // 10xxxxxx
$code = $code * 64 + $code2;
}
}
$char = \substr($str, $offset, $numBytes);
$offset = $offset + $numBytes;
return $code;
} | php | {
"resource": ""
} |
q245604 | Utf8.toUtf8 | validation | public static function toUtf8($str)
{
if (\extension_loaded('mbstring') && \function_exists('iconv')) {
$encoding = \mb_detect_encoding($str, \mb_detect_order(), true);
if (!$encoding) {
$str_conv = false;
if (\function_exists('iconv')) {
$str_conv = \iconv('cp1252', 'UTF-8', $str);
}
if ($str_conv === false) {
$str_conv = \htmlentities($str, ENT_COMPAT);
$str_conv = \html_entity_decode($str_conv, ENT_COMPAT, 'UTF-8');
}
$str = $str_conv;
} elseif (!\in_array($encoding, array('ASCII','UTF-8'))) {
$str_new = \iconv($encoding, 'UTF-8', $str);
if ($str_new !== false) {
$str = $str_new;
}
}
}
return $str;
} | php | {
"resource": ""
} |
q245605 | Utf8.setStr | validation | private static function setStr($str)
{
self::$str = $str;
self::$curI = 0;
self::$stats = array(
'bytesOther' => 0,
'bytesSpecial' => 0, // special UTF-8
'bytesUtf8' => 0, // includes ASCII
'strLen' => \strlen($str),
);
} | php | {
"resource": ""
} |
q245606 | ErrorEmailer.onErrorHighPri | validation | public function onErrorHighPri(Event $error)
{
$this->throttleDataRead();
$hash = $error['hash'];
$error['email'] = ($error['type'] & $this->cfg['emailMask'])
&& $error['isFirstOccur']
&& $this->cfg['emailTo'];
$error['stats'] = array(
'tsEmailed' => 0,
'countSince' => 0,
'emailedTo' => '',
);
if (isset($this->throttleData['errors'][$hash])) {
$stats = \array_intersect_key($this->throttleData['errors'][$hash], $error['stats']);
$error['stats'] = \array_merge($error['stats'], $stats);
}
return;
} | php | {
"resource": ""
} |
q245607 | ErrorEmailer.backtraceStr | validation | protected function backtraceStr(Event $error)
{
$backtrace = $error['backtrace']
? $error['backtrace'] // backtrace provided
: $error->getSubject()->backtrace();
if (\count($backtrace) < 2) {
return '';
}
if ($backtrace && $error['vars']) {
$backtrace[0]['vars'] = $error['vars'];
}
if ($this->cfg['emailBacktraceDumper']) {
$str = \call_user_func($this->cfg['emailBacktraceDumper'], $backtrace);
} else {
$search = array(
")\n\n",
);
$replace = array(
")\n",
);
$str = \print_r($backtrace, true);
$str = \preg_replace('#\bArray\n\(#', 'array(', $str);
$str = \preg_replace('/\barray\s+\(\s+\)/s', 'array()', $str); // single-lineify empty arrays
$str = \str_replace($search, $replace, $str);
$str = \substr($str, 0, -1);
}
return $str;
} | php | {
"resource": ""
} |
q245608 | ErrorEmailer.emailErr | validation | protected function emailErr(Event $error)
{
$dateTimeFmt = 'Y-m-d H:i:s (T)';
$errMsg = $error['message'];
if ($error['isHtml']) {
$errMsg = \strip_tags($errMsg);
$errMsg = \htmlspecialchars_decode($errMsg);
}
$countSince = $error['stats']['countSince'];
$isCli = $this->isCli();
$subject = $isCli
? 'Error: '.\implode(' ', $_SERVER['argv'])
: 'Website Error: '.$_SERVER['SERVER_NAME'];
$subject .= ': '.$errMsg.($countSince ? ' ('.$countSince.'x)' : '');
$emailBody = '';
if (!empty($countSince)) {
$dateTimePrev = \date($dateTimeFmt, $error['stats']['tsEmailed']);
$emailBody .= 'Error has occurred '.$countSince.' times since last email ('.$dateTimePrev.').'."\n\n";
}
$emailBody .= ''
.'datetime: '.\date($dateTimeFmt)."\n"
.'errormsg: '.$errMsg."\n"
.'errortype: '.$error['type'].' ('.$error['typeStr'].')'."\n"
.'file: '.$error['file']."\n"
.'line: '.$error['line']."\n"
.'';
if (!$isCli) {
$emailBody .= ''
.'remote_addr: '.$_SERVER['REMOTE_ADDR']."\n"
.'http_host: '.$_SERVER['HTTP_HOST']."\n"
.'referer: '.(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'null')."\n"
.'request_uri: '.$_SERVER['REQUEST_URI']."\n"
.'';
}
if (!empty($_POST)) {
$emailBody .= 'post params: '.\var_export($_POST, true)."\n";
}
if ($error['type'] & $this->cfg['emailTraceMask']) {
$backtraceStr = $this->backtraceStr($error);
$emailBody .= "\n".($backtraceStr
? 'backtrace: '.$backtraceStr
: 'no backtrace');
}
$this->email($this->cfg['emailTo'], $subject, $emailBody);
return;
} | php | {
"resource": ""
} |
q245609 | Event.& | validation | public function &offsetGet($key)
{
if ($this->hasValue($key)) {
return $this->values[$key];
}
$null = null;
return $null;
} | php | {
"resource": ""
} |
q245610 | Html.buildTable | validation | public function buildTable($rows, $options = array())
{
$options = \array_merge(array(
'attribs' => array(),
'caption' => null,
'columns' => array(),
'totalCols' => array(),
), $options);
if (\is_string($options['attribs'])) {
$options['attribs'] = array(
'class' => $options['attribs'],
);
}
if ($this->debug->abstracter->isAbstraction($rows) && $rows['traverseValues']) {
$options['caption'] .= ' ('.$this->markupClassname(
$rows['className'],
'span',
array(
'title' => $rows['phpDoc']['summary'] ?: null,
)
).')';
$options['caption'] = \trim($options['caption']);
$rows = $rows['traverseValues'];
}
$keys = $options['columns'] ?: $this->debug->methodTable->colKeys($rows);
$this->tableInfo = array(
'colClasses' => \array_fill_keys($keys, null),
'haveObjRow' => false,
'totals' => \array_fill_keys($options['totalCols'], null),
);
$tBody = '';
foreach ($rows as $k => $row) {
$tBody .= $this->buildTableRow($row, $keys, $k);
}
if (!$this->tableInfo['haveObjRow']) {
$tBody = \str_replace('<td class="t_classname"></td>', '', $tBody);
}
return $this->debug->utilities->buildTag(
'table',
$options['attribs'],
"\n"
.($options['caption'] ? '<caption>'.$options['caption'].'</caption>'."\n" : '')
.$this->buildTableHeader($keys)
.'<tbody>'."\n".$tBody.'</tbody>'."\n"
.$this->buildTableFooter($keys)
);
} | php | {
"resource": ""
} |
q245611 | Html.dump | validation | public function dump($val, $sanitize = true, $tagName = 'span')
{
$this->wrapAttribs = array(
'class' => array(),
'title' => null,
);
$this->sanitize = $sanitize;
$val = parent::dump($val);
if ($tagName && !\in_array($this->dumpType, array('recursion'))) {
$wrapAttribs = $this->debug->utilities->arrayMergeDeep(
array(
'class' => array(
't_'.$this->dumpType,
$this->dumpTypeMore,
),
),
$this->wrapAttribs
);
$val = $this->debug->utilities->buildTag($tagName, $wrapAttribs, $val);
}
$this->wrapAttribs = array();
return $val;
} | php | {
"resource": ""
} |
q245612 | Html.markupClassname | validation | public function markupClassname($str, $tagName = 'span', $attribs = array())
{
if (\preg_match('/^(.+)(::|->)(.+)$/', $str, $matches)) {
$classname = $matches[1];
$opMethod = '<span class="t_operator">'.\htmlspecialchars($matches[2]).'</span>'
. '<span class="method-name">'.$matches[3].'</span>';
} else {
$classname = $str;
$opMethod = '';
}
$idx = \strrpos($classname, '\\');
if ($idx) {
$classname = '<span class="namespace">'.\substr($classname, 0, $idx + 1).'</span>'
. \substr($classname, $idx + 1);
}
$attribs = \array_merge(array(
'class' => 't_classname',
), $attribs);
return $this->debug->utilities->buildTag($tagName, $attribs, $classname)
.$opMethod;
} | php | {
"resource": ""
} |
q245613 | Html.onOutput | validation | public function onOutput(Event $event)
{
$this->data = $this->debug->getData();
$this->channels = array();
$str = '<div'.$this->debug->utilities->buildAttribString(array(
'class' => 'debug',
// channel list gets built as log processed... we'll str_replace this...
'data-channels' => '{{channels}}',
'data-channel-root' => $this->channelNameRoot,
)).">\n";
if ($this->debug->getCfg('output.outputCss')) {
$str .= '<style type="text/css">'."\n"
.$this->debug->output->getCss()."\n"
.'</style>'."\n";
}
if ($this->debug->getCfg('output.outputScript')) {
$str .= '<script type="text/javascript">'
.\file_get_contents($this->debug->getCfg('filepathScript'))
.'</script>'."\n";
}
$str .= '<div class="debug-bar"><h3>Debug Log</h3></div>'."\n";
$str .= $this->processAlerts();
/*
If outputing script, initially hide the output..
this will help page load performance (fewer redraws)... by magnitudes
*/
if ($this->debug->getCfg('output.outputScript')) {
$str .= '<div class="loading">Loading <i class="fa fa-spinner fa-pulse fa-2x fa-fw" aria-hidden="true"></i></div>'."\n";
}
$str .= '<div class="debug-header m_group"'.($this->debug->getCfg('outputScript') ? ' style="display:none;"' : '').'>'."\n";
$str .= $this->processSummary();
$str .= '</div>'."\n";
$str .= '<div class="debug-content m_group"'.($this->debug->getCfg('outputScript') ? ' style="display:none;"' : '').'>'."\n";
$str .= $this->processLog();
$str .= '</div>'."\n"; // close .debug-content
$str .= '</div>'."\n"; // close .debug
$str = \strtr($str, array(
'{{channels}}' => \htmlspecialchars(\json_encode($this->buildChannelTree(), JSON_FORCE_OBJECT)),
));
$this->data = array();
$event['return'] .= $str;
} | php | {
"resource": ""
} |
q245614 | Html.buildArgString | validation | protected function buildArgString($args, $sanitize = true)
{
$glue = ', ';
$glueAfterFirst = true;
if (\is_string($args[0])) {
if (\preg_match('/[=:] ?$/', $args[0])) {
// first arg ends with "=" or ":"
$glueAfterFirst = false;
} elseif (\count($args) == 2) {
$glue = ' = ';
}
}
foreach ($args as $i => $v) {
$args[$i] = $i > 0
? $this->dump($v, $sanitize)
: $this->dump($v, false);
}
if (!$glueAfterFirst) {
return $args[0].\implode($glue, \array_slice($args, 1));
} else {
return \implode($glue, $args);
}
} | php | {
"resource": ""
} |
q245615 | Html.buildChannelTree | validation | protected function buildChannelTree()
{
if ($this->channels == array($this->channelNameRoot)) {
return array();
}
\sort($this->channels);
// move root to the top
$rootKey = \array_search($this->channelNameRoot, $this->channels);
if ($rootKey !== false) {
unset($this->channels[$rootKey]);
\array_unshift($this->channels, $this->channelName);
}
$tree = array();
foreach ($this->channels as $channel) {
$ref = &$tree;
$path = \explode('.', $channel);
foreach ($path as $k) {
if (!isset($ref[$k])) {
$ref[$k] = array();
}
$ref = &$ref[$k];
}
}
return $tree;
} | php | {
"resource": ""
} |
q245616 | Html.buildGroupMethod | validation | protected function buildGroupMethod($method, $args = array(), $meta = array())
{
$str = '';
if (\in_array($method, array('group','groupCollapsed'))) {
$label = \array_shift($args);
$levelClass = isset($meta['level'])
? 'level-'.$meta['level']
: null;
if (!empty($meta['isMethodName'])) {
$label = $this->markupClassname($label);
}
foreach ($args as $k => $v) {
$args[$k] = $this->dump($v);
}
$argStr = \implode(', ', $args);
/*
Header
*/
$str .= $this->debug->utilities->buildTag(
'div',
array(
'class' => array(
'group-header',
$method == 'groupCollapsed'
? 'collapsed'
: 'expanded',
$levelClass,
),
'data-channel' => $meta['channel'],
),
'<span class="group-label">'
.$label
.(!empty($argStr)
? '(</span>'.$argStr.'<span class="group-label">)'
: '')
.'</span>'
)."\n";
/*
Group open
*/
$str .= '<div'.$this->debug->utilities->buildAttribString(array(
'class' => array(
'm_group',
$levelClass,
),
)).'>';
} elseif ($method == 'groupEnd') {
$str = '</div>';
}
return $str;
} | php | {
"resource": ""
} |
q245617 | Html.buildTableFooter | validation | protected function buildTableFooter($keys)
{
$haveTotal = false;
$cells = array();
foreach ($keys as $key) {
$colHasTotal = isset($this->tableInfo['totals'][$key]);
$cells[] = $colHasTotal
? $this->dump(\round($this->tableInfo['totals'][$key], 6), true, 'td')
: '<td></td>';
$haveTotal = $haveTotal || $colHasTotal;
}
if (!$haveTotal) {
return '';
}
return '<tfoot>'."\n"
.'<tr><td> </td>'
.($this->tableInfo['haveObjRow'] ? '<td> </td>' : '')
.\implode('', $cells)
.'</tr>'."\n"
.'</tfoot>'."\n";
} | php | {
"resource": ""
} |
q245618 | Html.buildTableHeader | validation | protected function buildTableHeader($keys)
{
$headers = array();
foreach ($keys as $key) {
$headers[$key] = $key === MethodTable::SCALAR
? 'value'
: \htmlspecialchars($key);
if ($this->tableInfo['colClasses'][$key]) {
$headers[$key] .= ' '.$this->markupClassname($this->tableInfo['colClasses'][$key]);
}
}
return '<thead>'."\n"
.'<tr><th> </th>'
.($this->tableInfo['haveObjRow'] ? '<th> </th>' : '')
.'<th>'.\implode('</th><th scope="col">', $headers).'</th>'
.'</tr>'."\n"
.'</thead>'."\n";
} | php | {
"resource": ""
} |
q245619 | Html.buildTableRow | validation | protected function buildTableRow($row, $keys, $rowKey)
{
$str = '';
$values = $this->debug->methodTable->keyValues($row, $keys, $objInfo);
$parsed = $this->debug->utilities->parseTag($this->dump($rowKey));
$str .= '<tr>';
$str .= $this->debug->utilities->buildTag(
'th',
array(
'class' => 't_key text-right '.$parsed['attribs']['class'],
'scope' => 'row',
),
$parsed['innerhtml']
);
if ($objInfo['row']) {
$str .= $this->markupClassname($objInfo['row']['className'], 'td', array(
'title' => $objInfo['row']['phpDoc']['summary'] ?: null,
));
$this->tableInfo['haveObjRow'] = true;
} else {
$str .= '<td class="t_classname"></td>';
}
foreach ($values as $v) {
$str .= $this->dump($v, true, 'td');
}
$str .= '</tr>'."\n";
$str = \str_replace(' title=""', '', $str);
foreach (\array_keys($this->tableInfo['totals']) as $k) {
$this->tableInfo['totals'][$k] += $values[$k];
}
foreach ($objInfo['cols'] as $k2 => $classname) {
if ($this->tableInfo['colClasses'][$k2] === false) {
// column values not of the same type
continue;
}
if ($this->tableInfo['colClasses'][$k2] === null) {
$this->tableInfo['colClasses'][$k2] = $classname;
}
if ($this->tableInfo['colClasses'][$k2] !== $classname) {
$this->tableInfo['colClasses'][$k2] = false;
}
}
return $str;
} | php | {
"resource": ""
} |
q245620 | Html.dumpArray | validation | protected function dumpArray($array)
{
if (empty($array)) {
$html = '<span class="t_keyword">array</span>'
.'<span class="t_punct">()</span>';
} else {
$displayKeys = $this->debug->getCfg('output.displayListKeys') || !$this->debug->utilities->isList($array);
$html = '<span class="t_keyword">array</span>'
.'<span class="t_punct">(</span>'."\n";
if ($displayKeys) {
$html .= '<span class="array-inner">'."\n";
foreach ($array as $key => $val) {
$html .= "\t".'<span class="key-value">'
.'<span class="t_key'.(\is_int($key) ? ' t_int' : '').'">'
.$this->dump($key, true, false) // don't wrap it
.'</span> '
.'<span class="t_operator">=></span> '
.$this->dump($val)
.'</span>'."\n";
}
$html .= '</span>';
} else {
// display as list
$html .= '<ul class="array-inner list-unstyled">'."\n";
foreach ($array as $val) {
$html .= $this->dump($val, true, 'li');
}
$html .= '</ul>';
}
$html .= '<span class="t_punct">)</span>';
}
return $html;
} | php | {
"resource": ""
} |
q245621 | Html.visualWhiteSpace | validation | protected function visualWhiteSpace($str)
{
// display \r, \n, & \t
$str = \preg_replace_callback('/(\r\n|\r|\n)/', array($this, 'visualWhiteSpaceCallback'), $str);
$str = \preg_replace('#(<br />)?\n$#', '', $str);
$str = \str_replace("\t", '<span class="ws_t">'."\t".'</span>', $str);
return $str;
} | php | {
"resource": ""
} |
q245622 | Html.visualWhiteSpaceCallback | validation | protected function visualWhiteSpaceCallback($matches)
{
$strBr = $this->debug->getCfg('addBR') ? '<br />' : '';
$search = array("\r","\n");
$replace = array('<span class="ws_r"></span>','<span class="ws_n"></span>'.$strBr."\n");
return \str_replace($search, $replace, $matches[1]);
} | php | {
"resource": ""
} |
q245623 | Text.onOutput | validation | public function onOutput(Event $event)
{
$this->channelName = $this->debug->getCfg('channel');
$this->data = $this->debug->getData();
$str = '';
$str .= $this->processAlerts();
$str .= $this->processSummary();
$str .= $this->processLog();
$this->data = array();
$event['return'] .= $str;
} | php | {
"resource": ""
} |
q245624 | Text.buildArgString | validation | protected function buildArgString($args)
{
$numArgs = \count($args);
if ($numArgs == 1 && \is_string($args[0])) {
$args[0] = \strip_tags($args[0]);
}
foreach ($args as $k => $v) {
if ($k > 0 || !\is_string($v)) {
$args[$k] = $this->dump($v);
}
$this->valDepth = 0;
}
$glue = ', ';
$glueAfterFirst = true;
if ($numArgs && \is_string($args[0])) {
if (\preg_match('/[=:] ?$/', $args[0])) {
// first arg ends with "=" or ":"
$glueAfterFirst = false;
} elseif (\count($args) == 2) {
$glue = ' = ';
}
}
if (!$glueAfterFirst) {
return $args[0].\implode($glue, \array_slice($args, 1));
} else {
return \implode($glue, $args);
}
} | php | {
"resource": ""
} |
q245625 | Text.dumpArray | validation | protected function dumpArray($array)
{
$isNested = $this->valDepth > 0;
$this->valDepth++;
$array = parent::dumpArray($array);
$str = \trim(\print_r($array, true));
$str = \preg_replace('#^Array\n\(#', 'array(', $str);
$str = \preg_replace('#^array\s*\(\s+\)#', 'array()', $str); // single-lineify empty array
if ($isNested) {
$str = \str_replace("\n", "\n ", $str);
}
return $str;
} | php | {
"resource": ""
} |
q245626 | Text.dumpObject | validation | protected function dumpObject($abs)
{
$isNested = $this->valueDepth > 0;
$this->valueDepth++;
if ($abs['isRecursion']) {
$str = '(object) '.$abs['className'].' *RECURSION*';
} elseif ($abs['isExcluded']) {
$str = '(object) '.$abs['className'].' (not inspected)';
} else {
$str = '(object) '.$abs['className']."\n";
$str .= $this->dumpProperties($abs);
if ($abs['collectMethods'] && $this->debug->output->getCfg('outputMethods')) {
$str .= $this->dumpMethods($abs['methods']);
}
}
$str = \trim($str);
if ($isNested) {
$str = \str_replace("\n", "\n ", $str);
}
return $str;
} | php | {
"resource": ""
} |
q245627 | Text.dumpMethods | validation | protected function dumpMethods($methods)
{
$str = '';
if (!empty($methods)) {
$counts = array(
'public' => 0,
'protected' => 0,
'private' => 0,
'magic' => 0,
);
foreach ($methods as $info) {
$counts[ $info['visibility'] ] ++;
}
$str .= ' Methods:'."\n";
foreach ($counts as $vis => $count) {
if ($count) {
$str .= ' '.$vis.': '.$count."\n";
}
}
} else {
$str .= ' Methods: none!'."\n";
}
return $str;
} | php | {
"resource": ""
} |
q245628 | NovalnetSepa.getConfigFE | validation | public function getConfigFE( \Aimeos\MShop\Order\Item\Base\Iface $basket )
{
$list = [];
$feconfig = $this->feConfig;
try
{
$code = $this->getServiceItem()->getCode();
$service = $basket->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT, $code );
foreach( $service->getAttributeItems() as $item )
{
if( isset( $feconfig[$item->getCode()] ) ) {
$feconfig[$item->getCode()]['default'] = $item->getValue();
}
}
}
catch( \Aimeos\MShop\Order\Exception $e ) {; } // If payment isn't available yet
$addresses = $basket->getAddress( \Aimeos\MShop\Order\Item\Base\Address\Base::TYPE_PAYMENT );
if( ( $address = current( $addresses ) ) !== false )
{
if( $feconfig['novalnetsepa.holder']['default'] == ''
&& ( $fn = $address->getFirstname() ) !== '' && ( $ln = $address->getLastname() ) !== ''
) {
$feconfig['novalnetsepa.holder']['default'] = $fn . ' ' . $ln;
}
}
foreach( $feconfig as $key => $config ) {
$list[$key] = new \Aimeos\MW\Criteria\Attribute\Standard( $config );
}
return $list;
} | php | {
"resource": ""
} |
q245629 | NovalnetSepa.setConfigFE | validation | public function setConfigFE( \Aimeos\MShop\Order\Item\Base\Service\Iface $orderServiceItem, array $attributes )
{
$this->setAttributes( $orderServiceItem, $attributes, 'session' );
} | php | {
"resource": ""
} |
q245630 | Datatrans.repay | validation | public function repay( \Aimeos\MShop\Order\Item\Iface $order )
{
$base = $this->getOrderBase( $order->getBaseId() );
if( ( $cfg = $this->getCustomerData( $base->getCustomerId(), 'repay' ) ) === null )
{
$msg = sprintf( 'No reoccurring payment data available for customer ID "%1$s"', $base->getCustomerId() );
throw new \Aimeos\MShop\Service\Exception( $msg );
}
if( !isset( $cfg['token'] ) )
{
$msg = sprintf( 'No payment token available for customer ID "%1$s"', $base->getCustomerId() );
throw new \Aimeos\MShop\Service\Exception( $msg );
}
$data = array(
'transactionId' => $order->getId(),
'currency' => $base->getPrice()->getCurrencyId(),
'amount' => $this->getAmount( $base->getPrice() ),
'cardReference' => $cfg['token'],
'paymentPage' => false,
);
if( isset( $cfg['month'] ) && isset( $cfg['year'] ) )
{
$data['card'] = new \Omnipay\Common\CreditCard( [
'expiryMonth' => $cfg['month'],
'expiryYear' => $cfg['year'],
] );
}
$response = $this->getXmlProvider()->purchase( $data )->send();
if( $response->isSuccessful() )
{
$this->saveTransationRef( $base, $response->getTransactionReference() );
$order->setPaymentStatus( \Aimeos\MShop\Order\Item\Base::PAY_RECEIVED );
$this->saveOrder( $order );
}
else
{
$msg = ( method_exists( $response, 'getMessage' ) ? $response->getMessage() : '' );
throw new \Aimeos\MShop\Service\Exception( sprintf( 'Token based payment failed: %1$s', $msg ) );
}
} | php | {
"resource": ""
} |
q245631 | Datatrans.getXmlProvider | validation | protected function getXmlProvider()
{
$provider = OPay::create('Datatrans\Xml');
$provider->initialize( $this->getServiceItem()->getConfig() );
return $provider;
} | php | {
"resource": ""
} |
q245632 | OmniPay.getConfigBE | validation | public function getConfigBE()
{
$list = [];
foreach( $this->beConfig as $key => $config ) {
$list[$key] = new \Aimeos\MW\Criteria\Attribute\Standard( $config );
}
return $list;
} | php | {
"resource": ""
} |
q245633 | OmniPay.checkConfigBE | validation | public function checkConfigBE( array $attributes )
{
return array_merge( parent::checkConfigBE( $attributes ), $this->checkConfig( $this->beConfig, $attributes ) );
} | php | {
"resource": ""
} |
q245634 | OmniPay.cancel | validation | public function cancel( \Aimeos\MShop\Order\Item\Iface $order )
{
$provider = $this->getProvider();
if( !$provider->supportsVoid() ) {
return;
}
$base = $this->getOrderBase( $order->getBaseId() );
$data = array(
'transactionReference' => $this->getTransactionReference( $base ),
'currency' => $base->getPrice()->getCurrencyId(),
'amount' => $this->getAmount( $base->getPrice() ),
'transactionId' => $order->getId(),
);
$response = $provider->void( $data )->send();
if( $response->isSuccessful() )
{
$status = \Aimeos\MShop\Order\Item\Base::PAY_CANCELED;
$order->setPaymentStatus( $status );
$this->saveOrder( $order );
}
} | php | {
"resource": ""
} |
q245635 | OmniPay.capture | validation | public function capture( \Aimeos\MShop\Order\Item\Iface $order )
{
$provider = $this->getProvider();
if( !$provider->supportsCapture() ) {
return;
}
$base = $this->getOrderBase( $order->getBaseId() );
$data = array(
'transactionReference' => $this->getTransactionReference( $base ),
'currency' => $base->getPrice()->getCurrencyId(),
'amount' => $this->getAmount( $base->getPrice() ),
'transactionId' => $order->getId(),
);
$response = $provider->capture( $data )->send();
if( $response->isSuccessful() )
{
$status = \Aimeos\MShop\Order\Item\Base::PAY_RECEIVED;
$order->setPaymentStatus( $status );
}
} | php | {
"resource": ""
} |
q245636 | OmniPay.isImplemented | validation | public function isImplemented( $what )
{
$provider = $this->getProvider();
switch( $what )
{
case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_CAPTURE:
return $provider->supportsCapture();
case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_CANCEL:
return $provider->supportsVoid();
case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_REFUND:
return $provider->supportsRefund();
case \Aimeos\MShop\Service\Provider\Payment\Base::FEAT_REPAY:
return method_exists( $provider, 'createCard' );
}
return false;
} | php | {
"resource": ""
} |
q245637 | OmniPay.refund | validation | public function refund( \Aimeos\MShop\Order\Item\Iface $order )
{
$provider = $this->getProvider();
if( !$provider->supportsRefund() ) {
return;
}
$base = $this->getOrderBase( $order->getBaseId() );
$type = \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT;
$service = $this->getBasketService( $base, $type, $this->getServiceItem()->getCode() );
$data = array(
'transactionReference' => $this->getTransactionReference( $base ),
'currency' => $base->getPrice()->getCurrencyId(),
'amount' => $this->getAmount( $base->getPrice() ),
'transactionId' => $order->getId(),
);
$response = $provider->refund( $data )->send();
if( $response->isSuccessful() )
{
$attr = array( 'REFUNDID' => $response->getTransactionReference() );
$this->setAttributes( $service, $attr, 'payment/omnipay' );
$this->saveOrderBase( $base );
$status = \Aimeos\MShop\Order\Item\Base::PAY_REFUND;
$order->setPaymentStatus( $status );
$this->saveOrder( $order );
}
} | php | {
"resource": ""
} |
q245638 | OmniPay.getRedirectForm | validation | protected function getRedirectForm( \Omnipay\Common\Message\RedirectResponseInterface $response )
{
$list = [];
foreach( (array) $response->getRedirectData() as $key => $value )
{
$list[$key] = new \Aimeos\MW\Criteria\Attribute\Standard( array(
'label' => $key,
'code' => $key,
'type' => 'string',
'internalcode' => $key,
'internaltype' => 'string',
'default' => $value,
'public' => false,
) );
}
$url = $response->getRedirectUrl();
$method = $response->getRedirectMethod();
return new \Aimeos\MShop\Common\Helper\Form\Standard( $url, $method, $list );
} | php | {
"resource": ""
} |
q245639 | OmniPay.getTransactionReference | validation | protected function getTransactionReference( \Aimeos\MShop\Order\Item\Base\Iface $base )
{
$code = $this->getServiceItem()->getCode();
$service = $base->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT, $code );
return $service->getAttribute( 'TRANSACTIONID', 'payment/omnipay' );
} | php | {
"resource": ""
} |
q245640 | OmniPay.saveRepayData | validation | protected function saveRepayData( \Omnipay\Common\Message\ResponseInterface $response, $customerId )
{
$data = [];
if( method_exists( $response, 'getCardReference' ) ) {
$data['token'] = $response->getCardReference();
}
if( method_exists( $response, 'getExpiryMonth' ) ) {
$data['month'] = $response->getExpiryMonth();
}
if( method_exists( $response, 'getExpiryYear' ) ) {
$data['year'] = $response->getExpiryYear();
}
if( !empty( $data ) ) {
$this->setCustomerData( $customerId, 'repay', $data );
}
} | php | {
"resource": ""
} |
q245641 | OmniPay.saveTransationRef | validation | protected function saveTransationRef( \Aimeos\MShop\Order\Item\Base\Iface $baseItem, $ref )
{
$type = \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT;
$serviceItem = $this->getBasketService( $baseItem, $type, $this->getServiceItem()->getCode() );
$attr = array( 'TRANSACTIONID' => $ref );
$this->setAttributes( $serviceItem, $attr, 'payment/omnipay' );
$this->saveOrderBase( $baseItem );
} | php | {
"resource": ""
} |
q245642 | OmniPay.translateStatus | validation | protected function translateStatus( $status )
{
if( !interface_exists( '\Omnipay\Common\Message\NotificationInterface' ) ) {
return \Aimeos\MShop\Order\Item\Base::PAY_REFUSED;
}
switch( $status )
{
case \Omnipay\Common\Message\NotificationInterface::STATUS_COMPLETED:
return \Aimeos\MShop\Order\Item\Base::PAY_RECEIVED;
case \Omnipay\Common\Message\NotificationInterface::STATUS_PENDING:
return \Aimeos\MShop\Order\Item\Base::PAY_PENDING;
case \Omnipay\Common\Message\NotificationInterface::STATUS_FAILED:
return \Aimeos\MShop\Order\Item\Base::PAY_REFUSED;
}
} | php | {
"resource": ""
} |
q245643 | Stripe.getProvider | validation | protected function getProvider()
{
$config = $this->getServiceItem()->getConfig();
$config['apiKey'] = $this->getServiceItem()->getConfigValue( 'stripe.apiKey' );
if( !isset( $this->provider ) )
{
$this->provider = OPay::create( 'Stripe' );
$this->provider->setTestMode( (bool) $this->getValue( 'testmode', false ) );
$this->provider->initialize( $config );
}
return $this->provider;
} | php | {
"resource": ""
} |
q245644 | RelatedLayoutsLoader.loadRelatedLayouts | validation | public function loadRelatedLayouts(Location $location)
{
$query = $this->databaseConnection->createQueryBuilder();
$valueColumnName = class_exists('Netgen\BlockManager\Version') && Version::VERSION_ID < 1100
? 'value_id' :
'value';
$query->select('DISTINCT b.layout_id')
->from('ngbm_collection_item', 'ci')
->innerJoin(
'ci',
'ngbm_block_collection',
'bc',
$query->expr()->andX(
$query->expr()->eq('bc.collection_id', 'ci.collection_id'),
$query->expr()->eq('bc.collection_status', 'ci.status')
)
)
->innerJoin(
'bc',
'ngbm_block',
'b',
$query->expr()->andX(
$query->expr()->eq('b.id', 'bc.block_id'),
$query->expr()->eq('b.status', 'bc.block_status')
)
)
->where(
$query->expr()->andX(
$query->expr()->orX(
$query->expr()->andX(
$query->expr()->eq('ci.value_type', ':content_value_type'),
$query->expr()->eq('ci.' . $valueColumnName, ':content_id')
),
$query->expr()->andX(
$query->expr()->eq('ci.value_type', ':location_value_type'),
$query->expr()->eq('ci.' . $valueColumnName, ':location_id')
)
),
$query->expr()->eq('ci.status', ':status')
)
)
->setParameter('status', Value::STATUS_PUBLISHED, Type::INTEGER)
->setParameter('content_value_type', 'ezcontent', Type::STRING)
->setParameter('location_value_type', 'ezlocation', Type::STRING)
->setParameter('content_id', $location->contentInfo->id, Type::INTEGER)
->setParameter('location_id', $location->id, Type::INTEGER);
$relatedLayouts = array_map(
function (array $dataRow) {
return $this->layoutService->loadLayout($dataRow['layout_id']);
},
$query->execute()->fetchAll(PDO::FETCH_ASSOC)
);
usort(
$relatedLayouts,
function (Layout $layout1, Layout $layout2) {
if ($layout1->getName() === $layout2->getName()) {
return 0;
}
return $layout1->getName() > $layout2->getName() ? 1 : -1;
}
);
return $relatedLayouts;
} | php | {
"resource": ""
} |
q245645 | PathHelper.getPath | validation | public function getPath($locationId)
{
$pathArray = array();
$startingLocation = $this->locationService->loadLocation($locationId);
$path = $startingLocation->path;
// Shift of location "1" from path as it is not
// a fully valid location and not readable by most users
array_shift($path);
$rootLocationFound = false;
foreach ($path as $index => $pathItem) {
if ((int) $pathItem === $this->rootLocationId) {
$rootLocationFound = true;
}
if (!$rootLocationFound) {
continue;
}
try {
$location = $this->locationService->loadLocation($pathItem);
} catch (UnauthorizedException $e) {
return array();
}
$pathArray[] = array(
'text' => $this->translationHelper->getTranslatedContentNameByContentInfo(
$location->contentInfo
),
'url' => $location->id !== $startingLocation->id ?
$this->router->generate($location) :
false,
'locationId' => $location->id,
'contentId' => $location->contentId,
);
}
return $pathArray;
} | php | {
"resource": ""
} |
q245646 | ConfigurationGenerator.generate | validation | public function generate(InputInterface $input, OutputInterface $output)
{
$fileSystem = $this->container->get('filesystem');
$configResolver = $this->container->get('ezpublish.config.resolver');
$kernelRootDir = $this->container->getParameter('kernel.root_dir');
$siteAccessGroup = $input->getOption('site-access-group');
$varDir = $configResolver->getParameter('var_dir', null, $siteAccessGroup);
$repository = $configResolver->getParameter('repository', null, $siteAccessGroup);
$configFile = $kernelRootDir . '/config/ngadminui.yml';
if ($fileSystem->exists($configFile)) {
if (
!$this->questionHelper->ask(
$input,
$output,
new ConfirmationQuestion(
'<info><comment>ngadminui.yml</comment> configuration file already exists. Do you want to overwrite it?</info> [<comment>no</comment>] ',
false
)
)
) {
return;
}
}
$siteAccessName = $input->getOption('site-access-name');
$languageService = $this->container->get('ezpublish.api.repository')->getContentLanguageService();
$languages = $languageService->loadLanguages();
$settings = array(
'parameters' => array(
'netgen_admin_ui.' . $siteAccessName . '.is_admin_ui_siteaccess' => true,
'eztags.' . $siteAccessName . '.routing.enable_tag_router' => false,
'ezsettings.' . $siteAccessName . '.treemenu.http_cache' => false,
),
'ezpublish' => array(
'siteaccess' => array(
'list' => array(
$siteAccessName,
),
'groups' => array(
'ngadminui' => array(
$siteAccessName,
),
),
'match' => array(
'Map\URI' => array(
$siteAccessName => $siteAccessName,
),
),
),
'system' => array(
$siteAccessName => array(
'user' => array(
'layout' => '@NetgenAdminUI/pagelayout_login.html.twig',
'login_template' => '@NetgenAdminUI/user/login.html.twig',
),
'languages' => array_map(
function (Language $language) {
return $language->languageCode;
},
$languages
),
'var_dir' => $varDir,
'repository' => $repository,
),
),
),
'ez_publish_legacy' => array(
'system' => array(
$siteAccessName => array(
'templating' => array(
'view_layout' => '@NetgenAdminUI/pagelayout_legacy.html.twig',
'module_layout' => '@NetgenAdminUI/pagelayout_module.html.twig',
),
),
),
),
);
file_put_contents($configFile, Yaml::dump($settings, 7));
$output->writeln(
array(
'',
'Generated <comment>ngadminui.yml</comment> configuration file!',
'',
)
);
} | php | {
"resource": ""
} |
q245647 | LegacyMenuPlugin.matches | validation | public function matches(Request $request)
{
return in_array(
$request->attributes->get('_route'),
array(FallbackRouter::ROUTE_NAME, UrlAliasRouter::URL_ALIAS_ROUTE_NAME),
true
);
} | php | {
"resource": ""
} |
q245648 | GlobalVariable.getCurrentMenuPlugin | validation | public function getCurrentMenuPlugin()
{
$currentRequest = $this->requestStack->getCurrentRequest();
if (!$currentRequest instanceof Request) {
return false;
}
foreach ($this->menuPluginRegistry->getMenuPlugins() as $identifier => $menuPlugin) {
if ($menuPlugin->matches($currentRequest)) {
return $identifier;
}
}
return false;
} | php | {
"resource": ""
} |
q245649 | ControllerListener.onKernelController | validation | public function onKernelController(FilterControllerEvent $event)
{
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
return;
}
if (!$this->isAdminSiteAccess) {
return;
}
$currentRoute = $event->getRequest()->attributes->get('_route');
foreach ($this->legacyRoutes as $legacyRoute) {
if (stripos($currentRoute, $legacyRoute) === 0) {
$event->getRequest()->attributes->set('_controller', 'ezpublish_legacy.controller:indexAction');
$event->setController($this->controllerResolver->getController($event->getRequest()));
return;
}
}
} | php | {
"resource": ""
} |
q245650 | Generator.render | validation | protected function render($template, $parameters)
{
$twig = new Twig_Environment(
new Twig_Loader_Filesystem($this->skeletonDirs),
array(
'debug' => true,
'cache' => false,
'strict_variables' => true,
'autoescape' => false,
)
);
return $twig->render($template, $parameters);
} | php | {
"resource": ""
} |
q245651 | IsEnterpriseVersionListener.onBuildView | validation | public function onBuildView(CollectViewParametersEvent $event)
{
$view = $event->getView();
if (!$view instanceof LayoutViewInterface && !$view instanceof RuleViewInterface) {
return;
}
if ($view->getContext() !== 'ngadminui') {
return;
}
$event->addParameter('is_enterprise', $this->isEnterpriseVersion);
} | php | {
"resource": ""
} |
q245652 | MenuPluginRegistryPass.process | validation | public function process(ContainerBuilder $container)
{
if (!$container->has('netgen_admin_ui.menu_plugin.registry')) {
return;
}
$menuPluginRegistry = $container->findDefinition('netgen_admin_ui.menu_plugin.registry');
$menuPlugins = $container->findTaggedServiceIds('netgen_admin_ui.menu_plugin');
$flattenedMenuPlugins = array();
foreach ($menuPlugins as $identifier => $menuPlugin) {
$flattenedMenuPlugins[$identifier] = isset($menuPlugin[0]['priority']) ? $menuPlugin[0]['priority'] : 0;
}
arsort($flattenedMenuPlugins);
foreach (array_keys($flattenedMenuPlugins) as $menuPlugin) {
$menuPluginRegistry->addMethodCall(
'addMenuPlugin',
array(new Reference($menuPlugin))
);
}
} | php | {
"resource": ""
} |
q245653 | NetgenAdminUIExtension.getLegacyPreference | validation | public function getLegacyPreference($name)
{
$legacyKernel = $this->legacyKernel;
return $legacyKernel()->runCallback(
function () use ($name) {
return eZPreferences::value($name);
}
);
} | php | {
"resource": ""
} |
q245654 | LegacyExceptionListener.onException | validation | public function onException(GetResponseForExceptionEvent $event)
{
if (!$this->isAdminSiteAccess) {
return;
}
$routeName = $event->getRequest()->attributes->get('_route');
if ($routeName !== FallbackRouter::ROUTE_NAME) {
return;
}
$exception = $event->getException();
if (!$exception instanceof NotFoundHttpException) {
return;
}
// We're supporting admin UI exception as well as Netgen
// internal exception
if (method_exists($exception, 'getOriginalResponse')) {
$event->setResponse($exception->getOriginalResponse());
}
} | php | {
"resource": ""
} |
q245655 | SetInformationCollectionAdminPageLayoutListener.onKernelRequest | validation | public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if (!$this->isAdminSiteAccess) {
return;
}
$currentRoute = $event->getRequest()->attributes->get('_route');
if (mb_stripos($currentRoute, 'netgen_information_collection') !== 0) {
return;
}
$this->globalVariable->setPageLayoutTemplate($this->pageLayoutTemplate);
} | php | {
"resource": ""
} |
q245656 | NgAdminUiTagsBundleOperator.modify | validation | public static function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
{
if ( $operatorName === 'has_tags_bundle' ) {
$operatorValue = class_exists('Netgen\TagsBundle\Version') && TagsBundleVersion::VERSION_ID >= 30000;
}
} | php | {
"resource": ""
} |
q245657 | LegacyResponseListener.onKernelResponse | validation | public function onKernelResponse(FilterResponseEvent $event)
{
$routeName = $event->getRequest()->attributes->get('_route');
if ($routeName !== FallbackRouter::ROUTE_NAME) {
return;
}
$response = $event->getResponse();
if (!$response instanceof LegacyResponse) {
return;
}
if (!$this->legacyMode && (int) $response->getStatusCode() === Response::HTTP_NOT_FOUND) {
$moduleResult = $response->getModuleResult();
$exception = new NotFoundHttpException(
isset($moduleResult['errorMessage']) ?
$moduleResult['errorMessage'] :
'Not Found'
);
$exception->setOriginalResponse($response);
throw $exception;
}
} | php | {
"resource": ""
} |
q245658 | LayoutsController.showLocationLayouts | validation | public function showLocationLayouts($locationId)
{
$repository = $this->getRepository();
$location = $repository->getLocationService()->loadLocation($locationId);
$content = $repository->getContentService()->loadContent($location->contentInfo->id);
$request = $this->createRequest($content, $location);
return $this->render(
'@NetgenAdminUI/layouts/location_layouts.html.twig',
array(
'rules' => $this->layoutResolver->resolveRules($request, array('ez_content_type')),
'related_layouts' => $this->relatedLayoutsLoader->loadRelatedLayouts($location),
'location' => $location,
)
);
} | php | {
"resource": ""
} |
q245659 | LayoutsController.createRequest | validation | protected function createRequest(Content $content, Location $location)
{
$request = Request::create('');
$request->attributes->set('content', $content);
$request->attributes->set('location', $location);
if (interface_exists('eZ\Publish\Core\MVC\Symfony\View\ContentValueView')) {
$contentView = new ContentView();
$contentView->setLocation($location);
$contentView->setContent($content);
$request->attributes->set('view', $contentView);
}
return $request;
} | php | {
"resource": ""
} |
q245660 | LayoutsController.checkPermissions | validation | protected function checkPermissions()
{
if ($this->isGranted('ROLE_NGBM_EDITOR')) {
return;
}
if ($this->isGranted('nglayouts:ui:access')) {
return;
}
$exception = $this->createAccessDeniedException();
$exception->setAttributes('nglayouts:ui:access');
throw $exception;
} | php | {
"resource": ""
} |
q245661 | SecurityListener.onKernelBuilt | validation | public function onKernelBuilt(PostBuildKernelEvent $event)
{
$currentRequest = $this->requestStack->getCurrentRequest();
// Ignore if not in web context, if legacy_mode is active or if user is not authenticated
if (
$currentRequest === null
|| !$event->getKernelHandler() instanceof ezpWebBasedKernelHandler
|| $this->configResolver->getParameter('legacy_mode') === true
|| !$this->isUserAuthenticated()
) {
return;
}
/*
Siteaccesses running with legacy_mode=false and RequireUserLogin=true have issues with
login redirects when protected legacy views are accessed via URL before the user is logged in.
This is because RequireUserLogin specific code in legacy kernel checks for existence of
'eZUserLoggedInID' DURING the legacy kernel initialization process. Since 'eZUserLoggedInID'
session variable can only be set AFTER the legacy kernel is built and initialized,
via runCallback method, the code always fails, causing repeated login screens.
This is a workaround to set the session variable after the kernel is built, but before
it's initialized, so the RequireUserLogin code should work fine.
*/
$currentRequest->getSession()->set(
'eZUserLoggedInID',
$this->repository->getCurrentUser()->id
);
} | php | {
"resource": ""
} |
q245662 | LegacySiteAccessGenerator.generate | validation | public function generate(InputInterface $input, OutputInterface $output)
{
$fileSystem = $this->container->get('filesystem');
$legacyRootDir = $this->container->getParameter('ezpublish_legacy.root_dir');
$siteAccessName = $input->getOption('site-access-name');
$languageCode = $input->getOption('language-code');
$siteAccessLocation = $legacyRootDir . '/settings/siteaccess/' . $siteAccessName;
$skeletonDir = __DIR__ . '/../_templates/legacy_siteaccess';
if ($fileSystem->exists($siteAccessLocation)) {
if (
!$this->questionHelper->ask(
$input,
$output,
new ConfirmationQuestion(
'<info><comment>' . $siteAccessName . '</comment> legacy siteaccess already exists. Do you want to overwrite it?</info> [<comment>no</comment>] ',
false
)
)
) {
return;
}
}
$fileSystem->remove($siteAccessLocation);
// Template variables
$languageService = $this->container->get('ezpublish.api.repository')->getContentLanguageService();
$relatedSiteAccessList = $this->container->getParameter('ezpublish.siteaccess.list');
$relatedSiteAccessList[] = $siteAccessName;
$availableLocales = array_map(
function (Language $language) {
return $language->languageCode;
},
$languageService->loadLanguages()
);
$availableLocales = array_values(array_diff($availableLocales, array($languageCode)));
// Place siteaccess locale at the top of site language list
$siteLanguageList = array_merge(array($languageCode), $availableLocales);
$translationList = implode(';', $availableLocales);
// Generating admin siteaccess
$fileSystem->mirror($skeletonDir, $siteAccessLocation);
$this->setSkeletonDirs($siteAccessLocation);
$this->renderFile(
'site.ini.append.php',
$siteAccessLocation . '/site.ini.append.php',
array(
'relatedSiteAccessList' => $relatedSiteAccessList,
'siteAccessLocale' => $languageCode,
'siteLanguageList' => $siteLanguageList,
'translationList' => $translationList,
)
);
$output->writeln(
array(
'',
'Generated <comment>' . $siteAccessName . '</comment> legacy siteaccess!',
'',
)
);
} | php | {
"resource": ""
} |
q245663 | InstallCommand.interact | validation | protected function interact(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->questionHelper = $this->getHelper('question');
if (Kernel::VERSION_ID < 20700) {
throw new RuntimeException(
'Installation is not possible. Netgen Admin UI requires Symfony 2.7 or later to work.'
);
}
if (!$this->getContainer()->hasParameter('ezpublish_legacy.root_dir')) {
throw new RuntimeException(
sprintf(
"%s\n%s",
'Installation is not possible because eZ Publish Legacy is not present.',
'Netgen Admin UI requires eZ Publish Community 2014.12 (Netgen Variant), eZ Publish 5.4.x or eZ Platform with Legacy Bridge to work.'
)
);
}
$this->writeSection('Welcome to the Netgen Admin UI installation');
while (!$this->doInteract()) {
}
return 0;
} | php | {
"resource": ""
} |
q245664 | InstallCommand.doInteract | validation | protected function doInteract()
{
$siteAccess = $this->askForData(
'site-access-name',
'Enter the name of the Netgen Admin UI siteaccess',
'ngadminui',
function ($siteaccess) {
if (!preg_match('/^[a-z][a-z0-9_]*$/', $siteaccess)) {
throw new InvalidArgumentException(
'Siteaccess name is not valid. It must start with a letter, followed by any combination of letters, numbers and underscore.'
);
}
$existingSiteAccesses = $this->getContainer()->getParameter('ezpublish.siteaccess.list');
if (in_array($siteaccess, $existingSiteAccesses, true)) {
throw new InvalidArgumentException(
sprintf('Siteaccess "%s" already exists.', $siteaccess)
);
}
return $siteaccess;
}
);
$this->output->writeln('');
$languageCode = $this->askForData(
'language-code',
'Enter the language code in which the Netgen Admin UI will be translated',
'eng-GB',
function ($languageCode) {
$languageService = $this->getContainer()->get('ezpublish.api.repository')->getContentLanguageService();
try {
$languageService->loadLanguage($languageCode);
} catch (NotFoundException $e) {
throw new InvalidArgumentException(
sprintf('Language code "%s" does not exist.', $languageCode)
);
}
return $languageCode;
}
);
$this->output->writeln('');
$availableGroups = array_keys($this->getContainer()->getParameter('ezpublish.siteaccess.groups'));
$availableGroups[] = 'default';
$siteAccessGroup = $this->askForChoiceData(
'site-access-group',
'Enter the siteaccess group name on which the Netgen Admin UI configuration will be based. This is usually the name of your frontend siteaccess group',
$availableGroups,
current($availableGroups)
);
$this->writeSection('Summary before installation');
$this->output->writeln(
array(
'You are going to generate legacy <info>' . $siteAccess . '</info> siteaccess with <info>' . $languageCode . '</info> language code based on <info>' . $siteAccessGroup . '</info> siteaccess group.',
'',
)
);
if (
!$this->questionHelper->ask(
$this->input,
$this->output,
$this->getConfirmationQuestion(
'Do you confirm installation (answering <comment>no</comment> will restart the process)',
true
)
)
) {
$this->output->writeln('');
return false;
}
return true;
} | php | {
"resource": ""
} |
q245665 | InstallCommand.execute | validation | protected function execute(InputInterface $input, OutputInterface $output)
{
if (!$input->isInteractive()) {
$output->writeln('<error>This command only supports interactive execution</error>');
return 1;
}
$this->writeSection('Installation');
// Generate legacy siteaccess
$legacySiteAccessGenerator = new LegacySiteAccessGenerator(
$this->getContainer(),
$this->questionHelper
);
$legacySiteAccessGenerator->generate($this->input, $this->output);
// Generate configuration
$configurationGenerator = new ConfigurationGenerator(
$this->getContainer(),
$this->questionHelper
);
$configurationGenerator->generate($this->input, $this->output);
$errors = array();
$runner = $this->getRunner($errors);
// Generate legacy autoloads
$runner($this->generateLegacyAutoloads());
$this->writeInstallerSummary($errors);
return 0;
} | php | {
"resource": ""
} |
q245666 | InstallCommand.generateLegacyAutoloads | validation | protected function generateLegacyAutoloads()
{
$this->output->writeln('');
$this->output->write('Generating legacy autoloads... ');
$currentWorkingDirectory = getcwd();
try {
chdir($this->getContainer()->getParameter('ezpublish_legacy.root_dir'));
$processBuilder = new ProcessBuilder(
array(
'php',
'bin/php/ezpgenerateautoloads.php',
'--quiet',
)
);
$process = $processBuilder->getProcess();
$process->setTimeout(3600);
$process->run(
function ($type, $buffer) {
echo $buffer;
}
);
chdir($currentWorkingDirectory);
if (!$process->isSuccessful()) {
return array(
'- Run the following command from your ezpublish_legacy root to generate legacy autoloads:',
'',
' <comment>php bin/php/ezpgenerateautoloads.php</comment>',
'',
);
}
} catch (Exception $e) {
chdir($currentWorkingDirectory);
return array(
'There was an error generating legacy autoloads: ' . $e->getMessage(),
'',
);
}
} | php | {
"resource": ""
} |
q245667 | InstallCommand.askForData | validation | protected function askForData($optionIdentifier, $optionName, $defaultValue, $validator = null)
{
$optionValue = $this->input->getOption($optionIdentifier);
$optionValue = !empty($optionValue) ? $optionValue :
$defaultValue;
$question = $this->getQuestion($optionName, $optionValue, $validator);
$optionValue = $this->questionHelper->ask(
$this->input,
$this->output,
$question
);
$this->input->setOption($optionIdentifier, $optionValue);
return $optionValue;
} | php | {
"resource": ""
} |
q245668 | InstallCommand.askForChoiceData | validation | protected function askForChoiceData($optionIdentifier, $optionName, array $choices, $defaultValue)
{
$optionValue = $this->input->getOption($optionIdentifier);
$optionValue = !empty($optionValue) ? $optionValue :
$defaultValue;
$question = $this->getChoiceQuestion($optionName, $optionValue, $choices);
$optionValue = $this->questionHelper->ask(
$this->input,
$this->output,
$question
);
$this->input->setOption($optionIdentifier, $optionValue);
return $optionValue;
} | php | {
"resource": ""
} |
q245669 | InstallCommand.getQuestion | validation | protected function getQuestion($questionName, $defaultValue = null, $validator = null)
{
$questionName = $defaultValue
? '<info>' . $questionName . '</info> [<comment>' . $defaultValue . '</comment>]: '
: '<info>' . $questionName . '</info>: ';
$question = new Question($questionName, $defaultValue);
if ($validator !== null) {
$question->setValidator($validator);
}
return $question;
} | php | {
"resource": ""
} |
q245670 | InstallCommand.getChoiceQuestion | validation | protected function getChoiceQuestion($questionName, $defaultValue = null, array $choices = array())
{
$questionName = $defaultValue
? '<info>' . $questionName . '</info> [<comment>' . $defaultValue . '</comment>]: '
: '<info>' . $questionName . '</info>: ';
return new ChoiceQuestion($questionName, $choices, $defaultValue);
} | php | {
"resource": ""
} |
q245671 | InstallCommand.writeInstallerSummary | validation | protected function writeInstallerSummary($errors)
{
if (!$errors) {
$this->writeSection('You can now continue installation as per instructions in the README.md file!');
return;
}
$this->writeSection(
array(
'The command was not able to install everything automatically.',
'You must do the following changes manually.',
),
'error'
);
$this->output->writeln($errors);
} | php | {
"resource": ""
} |
q245672 | InstallCommand.writeSection | validation | protected function writeSection($text, $style = 'bg=blue;fg=white')
{
$this->output->writeln(
array(
'',
$this->getHelper('formatter')->formatBlock($text, $style, true),
'',
)
);
} | php | {
"resource": ""
} |
q245673 | InstallCommand.getRunner | validation | protected function getRunner(&$errors)
{
$output = $this->output;
$runner = function ($err) use ($output, &$errors) {
if (!empty($err)) {
$output->writeln('<fg=red>FAILED</>');
$errors = array_merge($errors, $err);
} else {
$output->writeln('<info>OK</info>');
}
};
return $runner;
} | php | {
"resource": ""
} |
q245674 | Client.createSubscriber | validation | public function createSubscriber(array $channels): WatchdogSubscriber
{
$redis = clone $this->redis;
$redis->disconnect();
$redis->connect();
return new WatchdogSubscriber($redis, $channels);
} | php | {
"resource": ""
} |
q245675 | Client.call | validation | public function call(string $command, ...$arguments)
{
$arguments = func_get_args();
array_shift($arguments);
return $this->__call($command, $arguments);
} | php | {
"resource": ""
} |
q245676 | ExceptionFactory.fromErrorMessage | validation | public static function fromErrorMessage(string $error): QlessException
{
$area = null;
$message = $error;
if (preg_match(self::ERROR_MESSAGE_RE, $error, $matches) > 0) {
$area = $matches['area'];
$message = $matches['message'];
}
switch (true) {
case ($area === 'Requeue' && stripos($message, 'does not exist') !== false):
case (stripos($message, 'Job does not exist') !== false):
return new InvalidJobException($message, $area);
case (stripos($message, 'Job given out to another worker') !== false):
return new JobLostException($message, $area);
case (stripos($message, 'Job not currently running') !== false):
default:
return new QlessException($message, $area);
}
} | php | {
"resource": ""
} |
q245677 | Config.get | validation | public function get(string $name, $default = null)
{
$res = $this->client->call('config.get', $name);
return $res === null ? $default : $res;
} | php | {
"resource": ""
} |
q245678 | Config.set | validation | public function set(string $name, $value): void
{
$this->client->call('config.set', $name, $value);
} | php | {
"resource": ""
} |
q245679 | JobFactory.create | validation | public function create(string $className, string $performMethod = 'perform')
{
if (class_exists($className) == false) {
throw new InvalidArgumentException("Could not find job class {$className}.");
}
if (method_exists($className, $performMethod) == false) {
throw new InvalidArgumentException(
sprintf(
'Job class "%s" does not contain perform method "%s".',
$className,
$performMethod
)
);
}
$instance = new $className;
if ($instance instanceof EventsManagerAwareInterface) {
$instance->setEventsManager($this->getEventsManager());
}
return $instance;
} | php | {
"resource": ""
} |
q245680 | SignalHandler.unregister | validation | public static function unregister(?array $signals = null): void
{
if (empty($signals)) {
$signals = self::KNOWN_SIGNALS;
}
foreach ($signals as $signal) {
if (is_string($signal)) {
// skip missing signals, for example OSX does not have all signals
if (!defined($signal)) {
continue;
}
$signal = constant($signal);
}
pcntl_signal($signal, SIG_DFL);
}
} | php | {
"resource": ""
} |
q245681 | SignalHandler.sigName | validation | public static function sigName(int $signal): string
{
$signals = [
'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGIOT', 'SIGBUS',
'SIGFPE', 'SIGKILL', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGALRM', 'SIGTERM',
'SIGSTKFLT', 'SIGCLD', 'SIGCHLD', 'SIGCONT', 'SIGSTOP', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU',
'SIGURG', 'SIGXCPU', 'SIGXFSZ', 'SIGVTALRM', 'SIGPROF', 'SIGWINCH', 'SIGPOLL', 'SIGIO',
'SIGPWR', 'SIGSYS', 'SIGBABY',
];
foreach ($signals as $name) {
if (defined($name) && constant($name) === $signal) {
return $name;
}
}
return 'UNKNOWN';
} | php | {
"resource": ""
} |
q245682 | Collection.fromSubscriptions | validation | public function fromSubscriptions(string $topic): array
{
$response = [];
if (empty($topic)) {
return $response;
}
$subscriptions = $this->client->call('subscription', 'default', 'all', $topic);
$subscriptions = json_decode($subscriptions, true) ?: [];
foreach ($subscriptions as $subscription => $queues) {
$topicPattern = str_replace(['.', '*', '#'], ['\.', '[a-zA-z0-9^.]{1,}', '.*'], $subscription);
if (preg_match("/^$topicPattern$/", $topic)) {
$response = array_merge($response, $queues);
}
}
return array_unique($response);
} | php | {
"resource": ""
} |
q245683 | Collection.completed | validation | public function completed(int $offset = 0, int $count = 25)
{
return $this->client->jobs('complete', null, $offset, $count);
} | php | {
"resource": ""
} |
q245684 | Collection.multiget | validation | public function multiget(array $jids): array
{
if (empty($jids)) {
return [];
}
$results = call_user_func_array([$this->client, 'multiget'], $jids);
$jobs = json_decode($results, true) ?: [];
$ret = [];
foreach ($jobs as $data) {
$job = new BaseJob($this->client, $data);
$job->setEventsManager($this->client->getEventsManager());
$ret[$job->jid] = $job;
}
return $ret;
} | php | {
"resource": ""
} |
q245685 | Collection.failedForGroup | validation | public function failedForGroup($group, int $start = 0, int $limit = 25): array
{
$results = json_decode($this->client->failed($group, $start, $limit), true);
if (isset($results['jobs']) && !empty($results['jobs'])) {
$results['jobs'] = $this->multiget($results['jobs']);
}
return is_array($results) ? $results : [];
} | php | {
"resource": ""
} |
q245686 | Collection.failed | validation | public function failed(): array
{
$results = json_decode($this->client->failed(), true);
return is_array($results) ? $results : [];
} | php | {
"resource": ""
} |
q245687 | Collection.tagged | validation | public function tagged(string $tag, int $offset = 0, int $limit = 25): array
{
$response = json_decode($this->client->call('tag', 'get', $tag, $offset, $limit), true);
if (empty($response['jobs'])) {
$response['jobs'] = [];
}
return $response['jobs'];
} | php | {
"resource": ""
} |
q245688 | Collection.fromWorker | validation | public function fromWorker(string $worker, string $subTimeInterval = ''): array
{
try {
$now = new \DateTime();
$interval = date_interval_create_from_date_string($subTimeInterval);
$timestamp = $now->sub($interval)->getTimestamp();
} catch (\Exception $e) {
$timestamp = -1;
}
if ($subTimeInterval === '' || $timestamp === -1) {
$jids = json_decode($this->client->workerJobs($worker), true) ?: [];
} else {
$jids = json_decode($this->client->workerJobs($worker, $timestamp), true) ?: [];
}
return $this->multiget($jids);
} | php | {
"resource": ""
} |
q245689 | Queue.put | validation | public function put(
string $className,
array $data,
?string $jid = null,
?int $delay = null,
?int $retries = null,
?int $priority = null,
?array $tags = null,
?array $depends = null
) {
try {
$jid = $jid ?: str_replace('-', '', Uuid::uuid4()->toString());
} catch (\Exception $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
$data = new JobData($data);
$this->getEventsManager()->fire(new QueueEvent\BeforeEnqueue($this, $jid, $data, $className));
if (!$putData = json_encode($data, JSON_UNESCAPED_SLASHES)) {
throw new RuntimeException(
sprintf(
'Unable to encode payload to put the described job "%s" to the "%s" queue.',
$jid,
$this->name
)
);
}
$jid = $this->client->put(
'',
$this->name,
$jid,
$className,
$putData,
is_null($delay) ? 0 : $delay,
'priority',
is_null($priority) ? 0 : $priority,
'tags',
json_encode($tags ?: [], JSON_UNESCAPED_SLASHES),
'retries',
is_null($retries) ? 5 : $retries,
'depends',
json_encode($depends ?: [], JSON_UNESCAPED_SLASHES)
);
$this->getEventsManager()->fire(new QueueEvent\AfterEnqueue($this, $jid, $data->toArray(), $className));
return $jid;
} | php | {
"resource": ""
} |
q245690 | Queue.pop | validation | public function pop(?string $worker = null, ?int $numJobs = null)
{
$workerName = $worker ?: $this->client->getWorkerName();
$jids = json_decode($this->client->pop($this->name, $workerName, $numJobs ?: 1), true);
$jobs = [];
array_map(function (array $data) use (&$jobs) {
$job = new BaseJob($this->client, $data);
$job->setEventsManager($this->getEventsManager());
$jobs[] = $job;
}, $jids ?: []);
return $numJobs === null ? array_shift($jobs) : $jobs;
} | php | {
"resource": ""
} |
q245691 | Queue.popByJid | validation | public function popByJid(string $jid, ?string $worker = null): ?BaseJob
{
$workerName = $worker ?: $this->client->getWorkerName();
$data = json_decode($this->client->popByJid($this->name, $jid, $workerName), true);
$jobData = array_reduce($data, 'array_merge', []); //unwrap nested array
if (isset($jobData['jid']) === false) {
return null;
}
if ($jobData['jid'] === $jid) {
$job = new BaseJob($this->client, $jobData);
$job->setEventsManager($this->getEventsManager());
}
return $job ?? null;
} | php | {
"resource": ""
} |
q245692 | Queue.recur | validation | public function recur(
string $className,
array $data,
?int $interval = null,
?int $offset = null,
?string $jid = null,
?int $retries = null,
?int $priority = null,
?int $backlog = null,
?array $tags = null
) {
try {
$jid = $jid ?: Uuid::uuid4()->toString();
} catch (\Exception $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
if (empty($data)) {
throw new RuntimeException(
sprintf(
'Unable to encode payload to make a recurring job "%s" for the "%s" queue.',
$jid,
$this->name
)
);
}
return $this->client->recur(
$this->name,
$jid,
$className,
$data,
'interval',
is_null($interval) ? 60 : $interval,
is_null($offset) ? 0 : $offset,
'priority',
is_null($priority) ? 0 : $priority,
'tags',
json_encode($tags ?: [], JSON_UNESCAPED_SLASHES),
'retries',
is_null($retries) ? 5 : $retries,
'backlog',
is_null($backlog) ? 0 : $backlog
);
} | php | {
"resource": ""
} |
q245693 | Queue.stats | validation | public function stats(?int $date = null): array
{
$date = $date ?: time();
return json_decode($this->client->stats($this->name, $date), true);
} | php | {
"resource": ""
} |
q245694 | Queue.isPaused | validation | public function isPaused(): bool
{
$stat = json_decode($this->client->queues($this->name), true);
return isset($stat['name']) && $stat['name'] === $this->name && $stat['paused'] == true;
} | php | {
"resource": ""
} |
q245695 | Queue.registerSyncCompleteEvent | validation | private function registerSyncCompleteEvent(): void
{
$this->getEventsManager()
->attach(QueueEvent\AfterEnqueue::getName(), function (QueueEvent\AfterEnqueue $event) {
if (!$this->client->config->get('sync-enabled')) {
return;
}
$job = $this->popByJid($event->getJid());
if (!empty($job)) {
$job->perform();
}
});
} | php | {
"resource": ""
} |
q245696 | EventsManager.attach | validation | public function attach(string $eventName, $handler, int $priority = 100): void
{
if (is_object($handler) == false && is_callable($handler) == false) {
throw new InvalidArgumentException(
sprintf('Event handler must be either an object or a callable %s given.', gettype($handler))
);
}
$priorityQueue = $this->fetchQueue($eventName);
$priorityQueue->insert($handler, $priority);
} | php | {
"resource": ""
} |
q245697 | EventsManager.fetchQueue | validation | protected function fetchQueue(string $eventName): SplPriorityQueue
{
if (isset($this->events[$eventName]) == false) {
$this->events[$eventName] = $this->createQueue();
}
return $this->events[$eventName];
} | php | {
"resource": ""
} |
q245698 | EventsManager.detach | validation | public function detach(string $eventName, $handler): void
{
if (is_object($handler) == false && is_callable($handler) == false) {
throw new InvalidArgumentException(
sprintf('Event handler must be either an object or a callable %s given.', gettype($handler))
);
}
if (isset($this->events[$eventName]) == false) {
return;
}
$priorityQueue = $this->events[$eventName];
$priorityQueue->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
$priorityQueue->top();
$newPriorityQueue = $this->createQueue();
while ($priorityQueue->valid()) {
$data = $priorityQueue->current();
$priorityQueue->next();
if ($data['data'] !== $handler) {
$newPriorityQueue->insert($data['data'], $data['priority']);
}
}
$this->events[$eventName] = $newPriorityQueue;
} | php | {
"resource": ""
} |
q245699 | EventsManager.fire | validation | public function fire(AbstractUserEvent $event)
{
$status = null;
$type = $event::getEntityName();
if (isset($this->events[$type])) {
$queue = $this->events[$type];
$status = $this->fireQueue($queue, $event);
}
$eventName = $event->getName();
if (isset($this->events[$eventName])) {
$queue = $this->events[$eventName];
$status = $this->fireQueue($queue, $event);
}
return $status;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.