_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q264900 | BizDataObj_Lite._run_search | test | protected function _run_search($limit = null)
{
// get database connection
$db = $this->getDBConnection("READ");
$querySQL = $this->getSQLHelper()->buildQuerySQL($this);
$this->_fetch4countQuery = $querySQL;
if ($limit && count($limit) > 0 && $limit['count'] > 0) {
$sql = $db->limit($querySQL, $limit['count'], $limit['offset']);
} else {
$sql = $querySQL;
}
try {
if ($this->cacheLifeTime > 0) {
$cache_id = md5($this->objectName . $sql . serialize($bindValues));
//try to process cache service.
$cacheSvc = Openbizx::getService(CACHE_SERVICE, 1);
$cacheSvc->init($this->objectName, $this->cacheLifeTime);
if ($cacheSvc->test($cache_id)) {
//Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Cache Hit. Query Sql = ".$sql);
$resultSetArray = $cacheSvc->load($cache_id);
} else {
Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $sql);
$resultSet = $db->query($sql);
$resultSetArray = $resultSet->fetchAll();
$cacheSvc->save($resultSetArray, $cache_id);
}
} else {
Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $sql);
$resultSet = $db->query($sql);
$resultSetArray = $resultSet->fetchAll();
}
} catch (Exception $e) {
Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
$this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": " . $sql . ". " . $e->getMessage();
throw new \Openbizx\Data\Exception($this->errorMessage);
return null;
}
return $resultSetArray;
} | php | {
"resource": ""
} |
q264901 | BizDataObj_Lite._getNumberRecords | test | private function _getNumberRecords($db, $sql)
{
$has_subquery = false;
if (preg_match("/\(\s*?SELECT\s*?.+\)/si", $sql)) {
$has_subquery = true;
}
if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is', $sql)) {
// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _TABLE_ALIAS_";
} elseif ($has_subquery == false) {
// now replace SELECT ... FROM with SELECT COUNT(*) FROM
$rewritesql = preg_replace('/\s*?SELECT\s.*?\s+FROM\s/is', 'SELECT COUNT(*) FROM ', $sql);
// Because count(*) and 'order by' fails with mssql, access and postgresql.
// Also a good speedup optimization - skips sorting!
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is', '', $rewritesql);
} else {
$rewritesql = $sql;
}
try {
if ($this->cacheLifeTime > 0) {
$cache_id = md5($this->objectName . $rewritesql . serialize($bindValues));
//try to process cache service.
$cacheSvc = Openbizx::getService(CACHE_SERVICE);
$cacheSvc->init($this->objectName, $this->cacheLifeTime);
if ($cacheSvc->test($cache_id)) {
//Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", ". Query Sql = ".$rewritesql);
$resultArray = $cacheSvc->load($cache_id);
} else {
Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $rewritesql);
$result = $db->query($rewritesql);
$resultArray = $result->fetch();
$cacheSvc->save($resultArray, $cache_id);
}
} else {
Openbizx::$app->getLog()->log(LOG_DEBUG, "DATAOBJ", "Query Sql = " . $rewritesql);
$resultSet = $db->query($rewritesql);
$resultArray = $resultSet->fetch();
}
} catch (Exception $e) {
Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "Query Error: " . $e->getMessage());
$this->errorMessage = $this->getMessage("DATA_ERROR_QUERY") . ": Rewrite:" . $rewritesql . ". Raw:" . $sql . ". " . $e->getMessage();
throw new \Openbizx\Data\Exception($this->errorMessage);
return 0;
}
if ($has_subquery) {
$record_count = (int) $resultSet->rowCount();
} else {
$record_count = (int) $resultArray[0];
}
return (string) $record_count;
} | php | {
"resource": ""
} |
q264902 | BizDataObj_Lite._fetch_record | test | protected function _fetch_record(&$resultSet)
{
if (!is_array($resultSet)) {
return null;
}
$sqlArr = current($resultSet);
if ($sqlArr) {
$this->currentRecord = $this->bizRecord->convertSqlArrToRecArr($sqlArr);
$this->currentRecord = $this->bizRecord->getRecordArr($sqlArr);
$this->recordId = $this->currentRecord["Id"];
next($resultSet);
} else {
return null;
}
return $this->currentRecord;
} | php | {
"resource": ""
} |
q264903 | InputElement.addSCKeyScript | test | protected function addSCKeyScript()
{
$keyMap = $this->getSCKeyFuncMap();
if (count($keyMap) == 0) {
return "";
}
Openbizx::$app->getClientProxy()->appendScripts("shortcut", "shortcut.js");
$str = "<script>\n";
$formObj = $this->getFormObj();
if (!$formObj->removeall_sck) {
$str .= " shortcut.removeall(); \n";
$formObj->removeall_sck = true;
}
foreach ($keyMap as $key => $func) {
$str .= " shortcut.remove(\"$key\"); \n";
}
$str .= " shortcut.add(\"$key\",function() { $func }); \n";
$str .= "</script>\n";
return $str;
} | php | {
"resource": ""
} |
q264904 | Application.config | test | public function config(string $key, $default = null)
{
return $this->container->get(Config::class)->get($key, $default);
} | php | {
"resource": ""
} |
q264905 | Application.bootstrap | test | public function bootstrap(): void
{
foreach( $this->config('bootstrap', []) as $file ){
$bootstrap = require_once(path($file));
$bootstrap($this);
}
} | php | {
"resource": ""
} |
q264906 | authService.authDBUser | test | protected function authDBUser($userName, $password)
{
$boAuth = Openbizx::getObject($this->authticationDataObj);
if (!$boAuth)
return false;
$searchRule = "[login]='$userName'";
$recordList = array();
$boAuth->fetchRecords($searchRule, $recordList, 1);
$encType = $recordList[0]["enctype"];
$realPassword = $recordList[0]["password"];
if ($this->checkPassword($encType,$password,$realPassword))
return true;
return false;
} | php | {
"resource": ""
} |
q264907 | FileWrapper.setRequest | test | protected function setRequest($request): void
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
if (! is_null($request)) {
if (! is_string($request)) {
throw \AWonderPHP\FileWrapper\TypeErrorException::requestWrongType($request);
}
$request = trim(basename($request));
if (strlen($request) === 0) {
$request = null;
}
}
if (is_null($request)) {
$request = trim(basename($this->path));
}
$this->request = $request;
} | php | {
"resource": ""
} |
q264908 | FileWrapper.setMaxAge | test | protected function setMaxAge($maxage): void
{
$now = time();
if (is_int($maxage)) {
if ($maxage > $now) {
$this->maxage = $maxage - $now;
return;
}
if ($maxage >= 0) {
$this->maxage = $maxage;
return;
}
throw \AWonderPHP\FileWrapper\InvalidArgumentException::negativeMaxAge();
}
if ($maxage instanceof \DateInterval) {
$dt = new \DateTime();
$dt->add($maxage);
$ts = $dt->getTimestamp();
$seconds = $ts - $now;
if ($seconds >= 0) {
$this->maxage = $seconds;
return;
}
throw \AWonderPHP\FileWrapper\InvalidArgumentException::negativeMaxAge();
}
if (! is_string($maxage)) {
throw \AWonderPHP\FileWrapper\TypeErrorException::maxageWrongType($maxage);
}
if ($tstamp = strtotime($maxage, time())) {
$seconds = $tstamp - $now;
if ($seconds >= 0) {
$this->maxage = $seconds;
return;
}
throw \AWonderPHP\FileWrapper\InvalidArgumentException::negativeMaxAge();
}
throw \AWonderPHP\FileWrapper\InvalidArgumentException::invalidDateString();
} | php | {
"resource": ""
} |
q264909 | FileWrapper.mimeTypoFix | test | protected function mimeTypoFix($input): string
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
$input = trim($input);
$mime = $input;
switch ($input) {
case 'application/font-woff':
$mime = 'font/woff';
break;
case 'audio/m4a':
$mime = 'audio/mp4';
break;
case 'audio/matroska':
$mime = 'audio/x-matroska';
break;
case 'audio/mp3':
$mime = 'audio/mpeg';
break;
case 'audio/x-aiff':
$mime = 'audio/aiff';
break;
case 'audio/wav':
$mime = 'audio/x-wav';
break;
case 'audio/x-m4a':
$mime = 'audio/mp4';
break;
case 'audio/x-matroska':
$arr = explode('.', $this->path);
$ext = strtolower(end($arr));
switch ($ext) {
case 'weba':
$mime = 'audio/webm';
break;
}
break;
case 'image/jpg':
$mime = 'image/jpeg';
break;
case 'image/tif':
$mime = 'image/tiff';
break;
case 'video/matroska':
$mime = 'video/x-matroska';
// test the extension too so no break
case 'video/x-matroska':
$arr = explode('.', $this->path);
$ext = strtolower(end($arr));
switch ($ext) {
case 'mka':
$mime = 'audio/x-matroska';
break;
case 'weba':
$mime = 'audio/webm';
break;
case 'webm':
$mime = 'video/webm';
break;
case 'webm2':
$mime = 'video/webm';
break;
}
break;
case 'application/octet-stream':
$arr = explode('.', $this->path);
$ext = strtolower(end($arr));
switch ($ext) {
case 'opus':
$mime = 'audio/ogg';
break;
}
break;
case 'text/plain':
$arr = explode('.', $this->path);
$ext = strtolower(end($arr));
switch ($ext) {
case 'js':
$mime = 'application/javascript';
break;
case 'css':
$mime = 'text/css';
break;
case 'vtt':
$mime = 'text/vtt';
break;
}
break;
}
return $mime;
} | php | {
"resource": ""
} |
q264910 | FileWrapper.validMimeType | test | protected function validMimeType($input): void
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
if (! is_null($input)) {
if (! is_string($input)) {
throw \AWonderPHP\FileWrapper\TypeErrorException::mimeWrongType($input);
}
$input = trim(strtolower($input));
try {
$input = $this->mimeTypoFix($input);
} catch (\ErrorException $e) {
error_log($e->getMessage());
$this->internalError = true;
return;
}
if (in_array($input, $this->validMime)) {
$this->mime = $input;
return;
}
}
// do what we can
if ($input == "application/octet-stream") {
$input = null;
}
$error = false;
if (! is_null($input)) {
$arr = explode('/', $input);
if (count($arr) != 2) {
$error = true;
} elseif (! in_array($arr[0], array('application',
'audio',
'font',
'image',
'multipart',
'text',
'video'))) {
$error = true;
}
if ($error) {
if (function_exists('finfo_open')) {
if ($finfo = finfo_open(FILEINFO_MIME_TYPE)) {
if ($mime = finfo_file($finfo, $this->path)) {
try {
$this->mime = $this->mimeTypoFix($mime);
} catch (\ErrorException $e) {
error_log($e->getMessage());
$this->internalError = true;
}
finfo_close($finfo);
return;
}
finfo_close($finfo);
}
}
}
}
if (is_null($input)) {
$input = 'application/octet-stream';
}
$this->mime = $input;
} | php | {
"resource": ""
} |
q264911 | FileWrapper.textCheck | test | protected function textCheck(): void
{
if (is_null($this->mime)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('mime');
}
$test = substr($this->mime, 0, 5);
if ($test === 'text/') {
$this->istext = true;
return;
}
$test = substr($this->mime, -4);
if ($test === "+xml") {
$this->istext = true;
return;
}
if (in_array($this->mime, $this->textMIME)) {
$this->istext = true;
}
} | php | {
"resource": ""
} |
q264912 | FileWrapper.checkFullFile | test | protected function checkFullFile(): void
{
if (is_null($this->filesize)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('filesize');
}
$this->end = $this->filesize - 1;
$this->total = $this->filesize;
if ($this->istext) {
return;
}
if ($this->filesize > $this->chunksize) {
$this->ranges = 'bytes';
if (isset($_SERVER['HTTP_RANGE'])) {
list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if ($size_unit == 'bytes') {
$this->fullfile = false;
//below causes noise in log, so do w/ if then instead. Not using extra_ranges anyway
//list($range, $extra_ranges) = explode(',', $range_orig, 2);
$arr = explode(',', $range_orig, 2);
if (isset($arr[1])) {
$extra_ranges = $arr[1];
} else {
$extra_ranges = null;
}
$range = $arr[0];
list($start, $end) = explode('-', $range, 2);
} else {
$this->badrange = true;
}
$end = (empty($end)) ? ($this->filesize - 1) : min(abs(intval($end)), ($this->filesize - 1));
$start = (empty($start) || $end < abs(intval($start))) ? 0 : max(abs(intval($start)), 0);
if ($start > 0 || $end < ($this->filesize - 1)) {
$this->start = $start;
$this->end = $end;
$this->total = $this->end - $this->start + 1;
}
}
}
} | php | {
"resource": ""
} |
q264913 | FileWrapper.setFileProperties | test | protected function setFileProperties(): void
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
date_default_timezone_set('UTC');
$this->filesize = filesize($this->path);
$this->timestamp = filemtime($this->path);
$this->lastmod = preg_replace('/\+0000$/', 'GMT', date('r', $this->timestamp));
$inode = fileinode($this->path);
// The f4a24ef etc strings - my understand in that
// because of caching proxies, the Etag needs to be
// different for different types of transfer encoding
// (e.g. brotli, gzip, deflate) or content could be
// delivered to a client that the client can not
// decompress.
// This class assumes only text files will potentially
// be further compressed when serving.
$etagEnd = 'f4a24ef';
if ($this->istext) {
if (ini_get('zlib.output_compression')) {
$accept = 'identity';
if ($this->minify) {
$etagEnd = '3d';
} else {
$etagEnd = '4c';
}
if (isset($this->REQHEADERS['accept-encoding'])) {
$T = trim(strtolower($this->REQHEADERS['accept-encoding']));
if (strpos($T, 'gzip') !== false) {
$accept = 'gzip';
} elseif (strpos($T, 'deflate') !== false) {
$accept = 'deflate';
}
}
switch ($accept) {
case 'gzip':
$etagEnd .= '7aa23';
break;
case 'deflate':
$etagEnd .= '98db4';
break;
default:
$etagEnd .= 'c41ca';
}
}
}
$this->etag = sprintf("%x-%x-%x-%s", $inode, $this->filesize, $this->timestamp, $etagEnd);
try {
$this->checkFullFile();
} catch (\ErrorException $e) {
error_log($e->getMessage());
$this->internalError = true;
return;
}
} | php | {
"resource": ""
} |
q264914 | FileWrapper.cacheCheck | test | protected function cacheCheck()
{
if (is_null($this->etag)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('etag');
}
if (isset($this->REQHEADERS['if-none-match'])) {
$reqETAG=trim($this->REQHEADERS['if-none-match'], '\'"');
if (strcmp($reqETAG, $this->etag) == 0) {
$this->cacheok=true;
}
} elseif (isset($this->REQHEADERS['if-modified-since'])) {
$reqLMOD=strtotime(trim($this->REQHEADERS['if-modified-since']));
if ($reqLMOD == $this->timestamp) {
$this->cacheok=true;
}
}
} | php | {
"resource": ""
} |
q264915 | FileWrapper.readFromFilesystem | test | protected function readFromFilesystem(): void
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
$chunk = $this->chunksize;
$sent = 0;
$fp = fopen($this->path, 'rb');
fseek($fp, $this->start);
while (!feof($fp)) {
if (($this->total - $sent) < $chunk) {
$chunk = $this->total - $sent;
}
print(fread($fp, $chunk));
flush();
ob_flush();
$sent = $sent + $chunk;
if ($sent >= $this->total) {
break;
}
}
fclose($fp);
} | php | {
"resource": ""
} |
q264916 | FileWrapper.sendContent | test | protected function sendContent(): bool
{
if (is_null($this->path)) {
$this->sendInternalError();
return false;
}
if (is_null($this->request)) {
$this->sendInternalError();
return false;
}
if (is_null($this->etag)) {
$this->sendInternalError();
return false;
}
if (is_null($this->mime)) {
$this->sendInternalError();
return false;
}
if (is_null($this->filesize)) {
$this->sendInternalError();
return false;
}
//make sure zlib output compression turned off
ini_set("zlib.output_compression", "Off");
if ($this->attachment) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $this->request . '"');
}
if ($this->maxage == 0) {
header('Cache-Control: must-revalidate');
} else {
header('Cache-Control: max-age=' . $this->maxage);
}
header('Last-Modified: ' . $this->lastmod);
header('ETag: "' . $this->etag . '"');
header('Accept-Ranges: ' . $this->ranges);
if ($this->fullfile) {
header('Content-Length: ' . $this->filesize);
} else {
header('HTTP/1.1 206 Partial Content');
header('Content-Length: ' . $this->total);
header('Content-Range: bytes ' . $this->start . '-' . $this->end . '/' . $this->filesize);
}
if (! is_null($this->allowOrigin)) {
header('access-control-allow-origin: ' . $this->allowOrigin);
}
header('Content-Type: ' . $this->mime);
header_remove('X-Powered-By');
try {
$this->readFromFilesystem();
} catch (\Error $e) {
error_log($e->getMessage());
$this->sendInternalError();
return false;
}
return true;
} | php | {
"resource": ""
} |
q264917 | FileWrapper.cleanSource | test | protected function cleanSource($content): string
{
if (is_null($this->path)) {
throw \AWonderPHP\FileWrapper\NullPropertyException::propertyIsNull('path');
}
//nuke BOM when we definitely have UTF8
$bom = pack('H*', 'EFBBBF');
//DOS to UNIX
$content = str_replace("\r\n", "\n", $content);
//Classic Mac to UNIX
$content = str_replace("\r", "\n", $content);
if (function_exists('mb_detect_encoding')) {
if (mb_detect_encoding($content, 'UTF-8', true)) {
$this->charEnc="UTF-8";
$content = preg_replace("/^$bom/", '', $content);
} elseif ($ENC = mb_detect_encoding($content, $this->charsetlist, true)) {
$this->charEnc=$ENC;
if (function_exists('iconv')) {
if ($new = iconv($ENC, 'UTF-8', $content)) {
$this->charEnc="UTF-8";
$content = preg_replace("/^$bom/", '', $new);
} else {
//conversion failed
error_log('Could not convert ' . $this->path . ' to UTF-8');
}
}
} else {
//we could not detect character encoding
error_log('Could not identify character encoding for ' . $this->path);
}
}
return($content);
} | php | {
"resource": ""
} |
q264918 | FileWrapper.jsminify | test | protected function jsminify($content): string
{
$JSqueeze = new \Patchwork\JSqueeze();
return($JSqueeze->squeeze($content, true, false));
} | php | {
"resource": ""
} |
q264919 | FileWrapper.cssminify | test | protected function cssminify($content): string
{
$content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);
$content = str_replace(': ', ':', $content);
$content = str_replace(array("\r\n", "\r", "\n", "\t"), '', $content);
$content = preg_replace("/ {2,}/", ' ', $content);
$content = str_replace(array('} '), '}', $content);
$content = str_replace(array('{ '), '{', $content);
$content = str_replace(array('; '), ';', $content);
$content = str_replace(array(', '), ',', $content);
$content = str_replace(array(' }'), '}', $content);
$content = str_replace(array(' {'), '{', $content);
$content = str_replace(array(' ;'), ';', $content);
$content = str_replace(array(' ,'), ',', $content);
return $content;
} | php | {
"resource": ""
} |
q264920 | FileWrapper.textwordwrap | test | protected function textwordwrap($content): string
{
$tmp = explode("\n", $content);
$currmax = 0;
foreach ($tmp as $line) {
if (function_exists('mb_strlen')) {
$lw = mb_strlen($line);
if ($lw === false) {
$lw = strlen($line);
}
} else {
$lw = strlen($line);
}
if ($lw > $currmax) {
$currmax = $lw;
}
}
if ($currmax > 120) {
$n = count($tmp);
for ($i=0; $i<$n; $i++) {
if (function_exists('mbWordWrap')) {
$tmp[$i] = mbWordWrap($tmp[$i], 80, "\n", true);
} elseif (function_exists('mb_strlen')) {
$tmp[$i] = $this->mbWordWrap($tmp[$i], 80, "\n", true);
} else {
$tmp[$i] = wordwrap($tmp[$i], 80, "\n", true);
}
}
$content = implode("\n", $tmp);
}
return $content;
} | php | {
"resource": ""
} |
q264921 | FileWrapper.getTextContent | test | protected function getTextContent(): bool
{
if (is_null($this->path)) {
$this->sendInternalError();
return false;
}
if (is_null($this->mime)) {
$this->sendInternalError();
return false;
}
$content = file_get_contents($this->path);
if ($this->toUTF8) {
try {
$content = $this->cleanSource($content);
} catch (\ErrorException $e) {
error_log($e->getMessage());
$this->sendInternalError();
return false;
}
}
if ($this->minify) {
switch ($this->mime) {
case "application/javascript":
$content=$this->jsminify($content);
break;
case "text/css":
$content=$this->cssminify($content);
break;
default:
$content=$this->textwordwrap($content);
break;
}
}
$charset='';
if (! is_null($this->charEnc)) {
$charset='; charset=' . $this->charEnc;
} elseif (function_exists('mb_detect_encoding')) {
if ($ENC = mb_detect_encoding($content, $this->charsetlist, true)) {
$charset='; charset=' . $ENC;
}
}
header('Content-Type: ' . $this->mime . $charset);
header_remove('X-Powered-By');
print($content);
return true;
} | php | {
"resource": ""
} |
q264922 | FileWrapper.serveText | test | protected function serveText(): bool
{
// move this to a class property in future FIXME
$vary = array();
if (is_null($this->request)) {
$this->sendInternalError();
return false;
}
if (is_null($this->etag)) {
$this->sendInternalError();
return false;
}
if ($this->attachment) {
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $this->request . '"');
}
if ($this->maxage == 0) {
header('Cache-Control: must-revalidate');
} else {
header('Cache-Control: max-age=' . $this->maxage);
}
header('Last-Modified: ' . $this->lastmod);
header('ETag: "' . $this->etag . '"');
if (ini_get('zlib.output_compression')) {
$vary[] = 'Accept-Encoding';
}
if (! is_null($this->allowOrigin)) {
if ($this->allowOrigin !== '*') {
$vary[] = 'Origin';
}
}
if (count($vary) > 0) {
$string = 'Vary: ' . implode(',', $vary);
header($string);
}
if (! is_null($this->allowOrigin)) {
header('access-control-allow-origin: ' . $this->allowOrigin);
}
return $this->getTextContent();
} | php | {
"resource": ""
} |
q264923 | FileWrapper.setAllowOrigin | test | public function setAllowOrigin($origin): void
{
$origin = trim($origin);
// fixme - send catchable error if origin isn't valid
// possibly could check with filter_var
if (strlen($origin) > 0) {
$this->allowOrigin = $origin;
}
} | php | {
"resource": ""
} |
q264924 | FileWrapper.sendfile | test | public function sendfile(): bool
{
if ($this->internalError) {
$this->sendInternalError();
return false;
}
if ($this->cacheok) {
header("HTTP/1.1 304 Not Modified");
return true;
}
if (is_null($this->path)) {
header("HTTP/1.0 404 Not Found");
return false;
}
if ($this->badrange) {
header("HTTP/1.1 416 Range Not Satisfiable");
return false;
}
if ($this->istext) {
return $this->serveText();
}
return $this->sendContent();
} | php | {
"resource": ""
} |
q264925 | AbstractTextingManager.registerProvider | test | public function registerProvider(TextingProviderInterface $provider)
{
if (!$this->defaultProvider) {
$this->defaultProvider = &$provider;
}
$this->providers[$provider->getName()] = $provider;
} | php | {
"resource": ""
} |
q264926 | ExplicitNormalizer.denormalize | test | public function denormalize($data, $class, $format = null, array $context = [])
{
$reflection = new ReflectionClass($class);
$instance = $reflection->newInstanceWithoutConstructor();
foreach ($data as $key => $value) {
$property = $reflection->getProperty($key);
$property->setAccessible(true);
$property->setValue($instance, $value);
}
return $instance;
} | php | {
"resource": ""
} |
q264927 | ExplicitNormalizer.supportsDenormalization | test | public function supportsDenormalization($data, $type, $format = null)
{
return in_array(AbstractExplicitMessage::class, class_parents($type, true), true);
} | php | {
"resource": ""
} |
q264928 | RulesValidator.validate | test | final public function validate(array $data, $rules, string $type = null)
{
try {
$this->setMessages($rules);
} catch (\TypeError $e) {
}
try {
$this->setCustomAttributes($rules);
} catch (\TypeError $e) {
}
try {
$validator = app('validator')->make(
array_filter($data),
$rules->getRules($type),
$this->messages,
$this->customAttributes
);
$this->validating($validator, $rules, $type);
} catch (\TypeError $e) {
}
if (isset($validator) && $validator->fails()) {
throw new ValidationException($validator);
}
} | php | {
"resource": ""
} |
q264929 | RulesValidator.validateModel | test | public function validateModel(Model $model, Validation\Rules $rules, string $type = null)
{
try {
$this->setModel($rules, $model);
} catch (\TypeError $e) {
}
$this->validate($model->getAttributes(), $rules, $type);
} | php | {
"resource": ""
} |
q264930 | MenuItemTrait.getActionAttribute | test | public function getActionAttribute($value)
{
switch ($this->type) {
case MenuItemContract::TYPE_ROUTE:
return trans('menu::menu.type.route');
case MenuItemContract::TYPE_URL:
return trans('menu::menu.type.url');
default:
return trans('menu::menu.type.unknown');
}
} | php | {
"resource": ""
} |
q264931 | MenuItemTrait.getUrlAttribute | test | public function getUrlAttribute($value)
{
if ($this->hasChildren()) {
return MenuItemContract::URL_EMPTY;
}
switch ($this->type) {
case MenuItemContract::TYPE_ROUTE:
return $this->routeGracefulOnError($this->target, $this->parameters);
case MenuItemContract::TYPE_URL:
return $this->target;
default:
return;
}
} | php | {
"resource": ""
} |
q264932 | EasyFormWizard.goNext | test | public function goNext($commit=false)
{
// call ValidateForm()
$recArr = $this->readInputRecord();
$this->setActiveRecord($recArr);
try
{
if ($this->ValidateForm() == false)
return;
}catch (Openbizx\Validation\Exception $e)
{
$this->processFormObjError($e->errors);
return;
}
$this->activeRecord = $this->readInputRecord();
$viewObj = $this->getWebpageObject();
// get the step
if($viewObj->getCurrentStep()){
$step = $viewObj->getCurrentStep();
}else{
$step = $_GET['step'];
}
if (!$step || $step=="")
$step=1;
// redirect the prev step
/* @var $viewObj WebPageWizard */
$viewObj->renderStep($step+1);
} | php | {
"resource": ""
} |
q264933 | EasyFormWizard.skip | test | public function skip()
{
$viewObj = $this->getWebpageObject();
// get the step
if($viewObj->getCurrentStep()){
$step = $viewObj->getCurrentStep();
}else{
$step = $_GET['step'];
}
if (!$step || $step=="")
$step=1;
$viewObj->renderStep($step+2);
} | php | {
"resource": ""
} |
q264934 | EasyFormWizard.goBack | test | public function goBack()
{
$recArr = $this->readInputRecord();
$this->setActiveRecord($recArr);
$this->activeRecord = $this->readInputRecord();
$viewObj = $this->getWebpageObject();
// get the step
if($viewObj->getCurrentStep()){
$step = $viewObj->getCurrentStep();
}else{
$step = $_GET['step'];
}
// redirect the prev step
/* @var $viewObj WebPageWizard */
$viewObj->renderStep($step-1);
} | php | {
"resource": ""
} |
q264935 | EasyFormWizard.doFinish | test | public function doFinish() //- call FinishWizard() by default
{
// call ValidateForm()
$recArr = $this->readInputRecord();
$this->setActiveRecord($recArr);
$this->setFormInputs($this->formInputs);
try
{
if ($this->ValidateForm() == false)
return;
}catch (Openbizx\Validation\Exception $e)
{
$this->processFormObjError($e->errors);
return;
}
$this->activeRecord = $this->readInputRecord();
/* @var $viewObj WebPageWizard */
$viewObj = $this->getWebpageObject();
$r = $viewObj->commit();
if (!$r)
return;
$this->processPostAction();
} | php | {
"resource": ""
} |
q264936 | EasyFormWizard.cancel | test | public function cancel()
{
// clean the session record
$this->dropSession = true;
Openbizx::$app->getSessionContext()->cleanObj($this->objectName, true);
} | php | {
"resource": ""
} |
q264937 | EasyFormWizard.render | test | public function render()
{
$viewobj = $this->getWebpageObject();
$viewobj->setFormState($this->objectName, 'visited', 1);
return parent::render();
} | php | {
"resource": ""
} |
q264938 | TOTPKeyGenerator.generate | test | public static function generate($length = null)
{
if ($length === null) {
$length = self::DEFAULT_LENGTH;
}
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
$randomString = '';
for ($i = 0; $i < $length; ++$i) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
} | php | {
"resource": ""
} |
q264939 | ExpressionUtil.isEmpty | test | public static function isEmpty(callable $callback, Context $context): bool
{
$policy = $context->setAccessPolicy(Context::ACCESS_POLICY_RETURN_NULL);
try {
$val = $callback($context);
} finally {
$context->setAccessPolicy($policy);
}
if ($val instanceof \Countable) {
return $val->count() == 0;
}
return empty($val);
} | php | {
"resource": ""
} |
q264940 | ExpressionUtil.ternaryShortcut | test | public static function ternaryShortcut(callable $a, callable $b, Context $context)
{
$policy = $context->setAccessPolicy(Context::ACCESS_POLICY_RETURN_NULL);
try {
$val = $a($context);
} finally {
$context->setAccessPolicy($policy);
}
if ($val instanceof \Countable) {
if ($val->count()) {
return $val;
}
return $b($context);
}
return empty($val) ? $b($context) : $val;
} | php | {
"resource": ""
} |
q264941 | ExpressionUtil.contains | test | public static function contains($container, $val): bool
{
if (\is_array($container)) {
return \in_array($val, $container, true);
}
if ($container instanceof \Traversable) {
foreach ($container as $tmp) {
if ($tmp === $val) {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q264942 | MetaIterator.merge | test | public function merge(&$anotherMIObj)
{
$old_varValue = $this->varValue;
$this->varValue = array();
foreach ($anotherMIObj as $key => $value) {
if (!$old_varValue[$key]) {
$this->varValue[$key] = $value;
} else {
$this->varValue[$key] = $old_varValue[$key];
}
}
foreach ($old_varValue as $key => $value) {
if (!isset($this->varValue[$key])) {
$this->varValue[$key] = $value;
}
}
} | php | {
"resource": ""
} |
q264943 | AppFactory.create | test | public static function create(
$containerConfig = null,
?RouterInterface $router = null,
?DispatcherInterface $dispatcher = null,
?ResponseInterface $defaultResponse = null
): App {
$container = self::buildContainer($containerConfig);
$dispatcher = $dispatcher ?: new Dispatcher();
$defaultResponse = $defaultResponse ?: new Response();
$router = $router ?: new Router(
[],
($container->has('router.options') ? $container->get('router.options') : [])
);
if ($container->has('router.routes') && is_array($container->get('router.routes'))) {
$router->addRoutes($container->get('router.routes'));
}
$container->set(Dispatcher::class, $dispatcher);
$container->set(Router::class, $router);
$container->set(Response::class, $defaultResponse);
$app = new App($container, $router, $dispatcher, $defaultResponse);
if ($container->has('app.env') && is_string($container->get('app.env'))) {
$app->setEnv($container->get('app.env'));
}
if ($container->has('app.error.handler') && true === (bool) $container->get('app.error.handler')) {
$app->enableErrorHandler();
}
return $app;
} | php | {
"resource": ""
} |
q264944 | GenericDocumentManager.dispatch | test | public function dispatch($key, $arguments)
{
$event = new GenericEvent(
$key,
$arguments
);
$this->eventDispatcher->dispatch($key, $event);
return $event;
} | php | {
"resource": ""
} |
q264945 | GenericDocumentManager.countByGroup | test | public function countByGroup($fieldGroup, $match = [], $query = null, $sort = null, $limit = null)
{
$group = [
'_id' => '$'.$fieldGroup,
'count' => [ '$sum' => 1]
];
return $this->aggregateGroup($group, $match, $query, $sort, $limit);
} | php | {
"resource": ""
} |
q264946 | GenericDocumentManager.aggregateGroup | test | public function aggregateGroup($group, $match = [], $query = null, $sort = null, $limit = null)
{
$query = $this->getDefault('query', $query);
$collection = $this->dm->getDocumentCollection($this->document);
$pipeline = [];
if ($query) {
$query = $this->addNativeQuery($this->queryFields, $query);
$match = array_merge($match, $query);
}
if (count($match)) {
$pipeline[] = [
'$match' => $match
];
}
$pipeline[] = [
'$group' => $group
];
if ($sort) {
$pipeline[] = [
'$sort' => $sort
];
}
if ($limit) {
$pipeline[] = [
'$limit' => $limit
];
}
$return = $collection->aggregate($pipeline);
return iterator_to_array($return);
} | php | {
"resource": ""
} |
q264947 | GenericDocumentManager.find | test | public function find($id, array $filters = [])
{
$qb = $this->dm->createQueryBuilder($this->document);
if (count($filters)) {
$qb = $this->addFilters($qb, $filters);
}
$qb->field('_id')->equals(new \MongoId($id));
return $qb->getQuery()->getSingleResult();
} | php | {
"resource": ""
} |
q264948 | GenericDocumentManager.getMongoIds | test | public function getMongoIds($objects)
{
$ids = [];
foreach ($objects as $object) {
$ids[] = new \MongoId($object->getId());
}
return $ids;
} | php | {
"resource": ""
} |
q264949 | GenericDocumentManager.normalizeDate | test | public function normalizeDate($date)
{
if ($date instanceof \DateTime) {
return $date;
}
$date = preg_replace('/\.[0-9]+/', '', $date);
return \DateTime::createFromFormat(\DateTime::ISO8601, $date);
} | php | {
"resource": ""
} |
q264950 | WebPage.isInFormRefLibs | test | public function isInFormRefLibs($formName)
{
if ($this->formRefLibs) {
$this->formRefLibs->rewind();
while ($this->formRefLibs->valid()) {
$reference = $this->formRefLibs->current();
if ($reference->objectName == $formName) {
return true;
}
$this->formRefLibs->next();
}
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q264951 | WebPage.render | test | public function render()
{
if (!$this->allowAccess()) {
$accessDenyWebpage = Openbizx::getObject(OPENBIZ_ACCESS_DENIED_WEBPAGE);
return $accessDenyWebpage->render();
}
$this->initAllForms();
// check the "fld_..." arg in url and put it in the search rule
$this->processRequest();
return $this->_render();
} | php | {
"resource": ""
} |
q264952 | WebPage.getCurrentPageUrl | test | public function getCurrentPageUrl()
{
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
} | php | {
"resource": ""
} |
q264953 | WebPage.initAllForms | test | protected function initAllForms()
{
foreach ($this->formRefs as $formRef) {
$formRef->setViewName($this->objectName);
$formName = $formRef->objectName;
$formObj = Openbizx::getObject($formName);
if ($formRef->subForms && method_exists($formObj, "SetSubForms")) {
$formObj->setSubForms($formRef->subForms);
}
}
} | php | {
"resource": ""
} |
q264954 | PhpSettingCheck.compareIntegers | test | public static function compareIntegers($value, $setting_value)
{
$okay = false;
$actual = self::getIntegerValue($value);
$operator = self::getOperator($setting_value);
$expected = self::getIntegerValue($setting_value);
switch ($operator) {
case '>':
$okay = $actual > $expected;
break;
case '>=':
$okay = $actual >= $expected;
break;
case '<':
$okay = $actual < $expected;
break;
case '<=':
$okay = $actual <= $expected;
break;
case '!=':
$okay = $actual != $expected;
break;
case '=':
default:
$okay = $actual == $expected;
break;
}
return $okay;
} | php | {
"resource": ""
} |
q264955 | PhpSettingCheck.getIntegerValue | test | public static function getIntegerValue($value)
{
if (!is_numeric($value)) {
// strip excessive whitespace
$value = trim($value);
// strip comparison operator
$value = ltrim($value, '<>!=');
// remove the K|M|G suffix if necessary
$len = strlen($value);
if (!is_numeric($value)) {
$quantity = substr($value, 0, $len - 1);
// we need this, as PHP sets a memory_limit of 0 if the ini value is 0.25M
// another example: 2.75M will be 2M for PHP (e.g. on post_max_size)
$quantity = intval($quantity);
} else {
$quantity = $value;
}
// get unit if this string represents a byte value
$unit = strtolower(substr($value, $len - 1));
switch ($unit) {
case 'k':
$quantity *= 1024;
break;
case 'm':
$quantity *= 1048576;
break;
case 'g':
$quantity *= 1073741824;
break;
}
return $quantity;
}
return intval($value);
} | php | {
"resource": ""
} |
q264956 | Autoloader.findSourceFiles | test | public static function findSourceFiles(string $path)
{
$result = array();
$reader = dir($path);
while ($file = $reader->read())
{
if ($file === '.' || $file === '..')
continue;
$file = $path . '/' . $file;
if (substr($file, -4) === ".php")
{
$result[] = $file;
}
elseif (is_dir($file))
{
$sub = self::findSourceFiles($file);
foreach ($sub as $f)
$result[] = $f;
}
}
return $result;
} | php | {
"resource": ""
} |
q264957 | Autoloader.registerNS | test | public function registerNS(string $ns, string $path, $standard = Autoloader::PSR4)
{
if (!file_exists($path) || !is_dir($path) || !is_readable($path))
throw new \InvalidArgumentException("Path $path is not readable");
if ($standard !== Autoloader::PSR0 && $standard !== Autoloader::PSR4 && !is_callable($standard))
throw new \InvalidArgumentException("Invalid standard: $standard");
// Strip a leading namespace separator
$ns = trim($ns, '\\');
// Get the namespace parts
$parts = explode('\\', $ns);
$this->registered_namespaces[$ns] = true;
// Make sure there is a trailing namespace separator
if ($ns !== "" && substr($ns, -1, 1) !== '\\')
$ns .= '\\';
$ref = &$this->root_namespace;
foreach ($parts as $part)
{
// Registering empty namespace
if ($part === "")
break;
if (!isset($ref['sub_ns'][$part]))
$ref['sub_ns'][$part] = ['loaders' => [], 'sub_ns' => []];
$ref = &$ref['sub_ns'][$part];
}
$ref['loaders'][] = [
'ns' => $ns,
'path' => $path,
'std' => $standard
];
} | php | {
"resource": ""
} |
q264958 | Autoloader.buildCache | test | public function buildCache()
{
if ($this->cache === null)
throw new \LogicException("Cannot build cache without a cache instance");
$this->cache->set('cache_built', false);
$this->cache->set('classpaths', array());
$stack = array($this->root_namespace);
while (!empty($stack))
{
$ref = array_pop($stack);
foreach ($ref['loaders'] as $loader)
{
if ($loader['std'] !== Autoloader::PSR4)
throw new \LogicException("Cache builder only works with pure PSR4-based namespaces");
$class_count = 0;
$root = $loader['path'] . DIRECTORY_SEPARATOR;
$ns = $loader['ns'];
$php_files = self::findSourceFiles($loader['path']);
foreach ($php_files as $file)
{
$rel_file = substr($file, strlen($root));
// Store absolute resolved paths when not using stream wrappers
if (strpos($file, '://') === false) $file = realpath($file);
$parts = explode(DIRECTORY_SEPARATOR, $rel_file);
$class_name = substr($ns . implode('\\', $parts), 0, -4);
if ($this->cache->has('classpaths', $class_name))
{
$conflict = $this->cache->get('classpaths', $class_name);
throw new \LogicException(sprintf(
"Duplicate class definition in file %s and %s (conflicting namespace: %s)",
$file,
$conflict,
$ns
));
}
$this->cache->set('classpaths', $class_name, $file);
++$class_count;
}
self::getLogger()->info('Found {0} classes in namespace {1}', [$class_count, $ns]);
}
foreach ($ref['sub_ns'] as $sub_ns)
array_push($stack, $sub_ns);
}
$this->cache->set('cache_built', true);
self::getLogger()->info('Class cache built');
} | php | {
"resource": ""
} |
q264959 | Autoloader.findComposerAutoloader | test | public static function findComposerAutoloader()
{
// Find the Composer Autoloader class using its (generated) name
$list = get_declared_classes();
foreach ($list as $cl)
if (substr($cl, 0, 18) === "ComposerAutoloader")
return $cl;
// @codeCoverageIgnoreStart
// Tests run using composer autoloader
return null;
// @codeCoverageIgnoreEnd
} | php | {
"resource": ""
} |
q264960 | Autoloader.findComposerAutoloaderVendorDir | test | public static function findComposerAutoloaderVendorDir(string $composer_loader_class)
{
$ref = new \ReflectionClass($composer_loader_class);
// Composer is located at MyProject/vendor/composer
$path = dirname($ref->getFileName());
return dirname($path);
} | php | {
"resource": ""
} |
q264961 | Autoloader.getClassLoaders | test | public function getClassLoaders(string $class)
{
$parts = explode("\\", $class);
$result = array();
$ref = &$this->root_namespace;
$sub_ns = "";
foreach ($parts as $part)
{
foreach ($ref['loaders'] as $loader)
$result[] = $loader;
if (!isset($ref['sub_ns'][$part]))
break;
$ref = &$ref['sub_ns'][$part];
}
// Reverse the result, because the last one is the most specific
// namespace, which would be the one to try first.
return array_reverse($result);
} | php | {
"resource": ""
} |
q264962 | HasAttrWithMiddleware.getMiddlewareOrFallback | test | public function getMiddlewareOrFallback(string $name, $middleMan, $result = null)
{
// asserts instead of type-hints because this is a trait and another trait uses it.
assert($middleMan instanceof MiddlewareDispatcher);
if (! $middleMan->groupIsEmpty('getters')) {
$result = $middleMan->callGetters($name, $result);
} elseif (is_object($result)) {
$result = $result->$name;
} else {
$result = $this->getVisibleAttribute($name);
}
return $result;
} | php | {
"resource": ""
} |
q264963 | HasAttrWithMiddleware.setMiddlewareOrFallback | test | public function setMiddlewareOrFallback(string $name, $value, $middleMan, $result = null)
{
// asserts instead of type-hints because this is a trait and another trait uses it.
assert($middleMan instanceof MiddlewareDispatcher);
if (! $middleMan->groupIsEmpty('setters')) {
$result = $middleMan->callSetters($name, $value, $result);
} elseif (is_object($result)) {
$result = $result->$name = $value;
} else {
$result = $this->setVisibleAttribute($name, $value);
}
return $result;
} | php | {
"resource": ""
} |
q264964 | Printable.withStringLimit | test | public function withStringLimit(int $strlim): Printable
{
return new Printable($this->value, $this->callable, $strlim, $this->arrlim);
} | php | {
"resource": ""
} |
q264965 | Printable.withArrayLimit | test | public function withArrayLimit(int $arrlim): Printable
{
return new Printable($this->value, $this->callable, $this->strlim, $arrlim);
} | php | {
"resource": ""
} |
q264966 | Printable.string | test | private function string(string $value): string
{
if ($this->callable && is_callable($value)) {
return sprintf('function %s()', $value);
}
return strlen($value) > $this->strlim
? $this->quoted(substr($value, 0, $this->strlim) . '...')
: $this->quoted($value);
} | php | {
"resource": ""
} |
q264967 | Printable.array | test | private function array(array $value): string
{
if ($this->callable && is_callable($value)) {
$class = ! is_string($value[0])
? $this->classname($value[0])
: $value[0];
$method = $value[1];
return sprintf('function %s::%s()', $class, $method);
}
$slice = array_slice($value, 0, $this->arrlim, true);
$elems = $this->isAssociative($slice)
? array_map([$this, 'arrayPair'], array_keys($slice), $slice)
: array_map([$this, 'arrayValue'], $slice);
return vsprintf('[%s%s]', [
implode(', ', $elems),
count($value) > $this->arrlim ? ', ...' : '',
]);
} | php | {
"resource": ""
} |
q264968 | Printable.arrayPair | test | private function arrayPair($key, $val): string
{
$key_str = is_int($key) ? $key : $this->quoted($key);
$val_str = $this->arrayValue($val);
return sprintf('%s => %s', $key_str, $val_str);
} | php | {
"resource": ""
} |
q264969 | Printable.arrayValue | test | private function arrayValue($val): string
{
return ! is_array($val)
? (string) new Printable($val, $this->callable, $this->strlim)
: '[...]';
} | php | {
"resource": ""
} |
q264970 | Printable.object | test | private function object($value): string
{
$class = $this->classname($value);
if ($class == \Closure::class) {
return 'function {closure}()';
}
return ($this->callable && is_callable($value))
? sprintf('function %s::__invoke()', $class)
: sprintf('Object(%s)', $class);
} | php | {
"resource": ""
} |
q264971 | NewrelicBackgroundTransaction.reject | test | public function reject(RejectEnvelopeEvent $event)
{
if (!function_exists('newrelic_end_transaction')) {
return;
}
newrelic_notice_error($event->getEnvelope()->getName(), $event->getException());
newrelic_end_transaction();
} | php | {
"resource": ""
} |
q264972 | LaravelcpServiceProvider.boot | test | public function boot(\Illuminate\Routing\Router $router)
{
Config::set('auth.model', 'Askedio\Laravelcp\Models\User');
Config::set('auth.password.email', 'lcp::emails.password');
$router->middleware('auth', 'Askedio\Laravelcp\Http\Middleware\Authenticate');
$router->middleware('auth.basic', 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth');
$router->middleware('guest', 'Askedio\Laravelcp\Http\Middleware\RedirectIfAuthenticated');
$router->middleware('role', 'Askedio\Laravelcp\Http\Middleware\VerifyRole');
$router->middleware('permission', 'Askedio\Laravelcp\Http\Middleware\VerifyPermission');
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Nav', 'Askedio\Laravelcp\Helpers\NavigationHelper');
$loader->alias('Hook', 'Askedio\Laravelcp\Helpers\HookHelper');
$loader->alias('Search', 'Askedio\Laravelcp\Helpers\SearchHelper');
NavigationHelper::Initialize();
HookHelper::Initialize();
SearchHelper::Initialize();
if (! $this->app->routesAreCached()) {
require realpath(__DIR__.'/../Http/routes.php');
}
$this->loadTranslationsFrom(realpath(__DIR__.'/../Resources/Lang'), 'lcp');
$this->loadViewsFrom(realpath(__DIR__.'/../Resources/Views'), 'lcp');
NavigationHelper::Add(['nav' => 'main', 'sort' => '0', 'link' => url('/dashboard'), 'title' => trans('lcp::nav.dashboard'), 'icon' => 'fa-dashboard']);
$this->publishes([
realpath(__DIR__.'/../Resources/Views') => base_path('resources/views/vendor/askedio/laravelcp'),
], 'views');
$this->publishes([
realpath(__DIR__.'/../Resources/Assets') => public_path('assets'),
], 'public');
$this->publishes([
realpath(__DIR__.'/../Resources/Config') => config_path('')
], 'config');
$this->publishes([
realpath(__DIR__.'/../Database/Migrations') => database_path('migrations')
], 'migrations');
$this->publishes([
realpath(__DIR__.'/../Database/Seeds') => database_path('seeds')
], 'seeds');
} | php | {
"resource": ""
} |
q264973 | ViewRenderer.render | test | static public function render($webpage)
{
$tplEngine = $webpage->templateEngine;
$tplAttributes = ViewRenderer::buildTemplateAttributes($webpage);
ob_start();
if ($tplEngine == "Smarty" || $tplEngine == null) {
ViewRenderer::renderSmarty($webpage, $tplAttributes);
} else {
ViewRenderer::renderPHP($webpage, $tplAttributes);
}
$html = ob_get_contents();
ob_end_clean();
if (defined("OPENBIZ_PAGE_MINIFY") && OPENBIZ_PAGE_MINIFY == 1) {
$html = self::MinifyOutput($html);
}
return $html;
} | php | {
"resource": ""
} |
q264974 | ViewRenderer.renderSmarty | test | static protected function renderSmarty($webpage, $tplAttributes = Array())
{
$smarty = TemplateHelper::getSmartyTemplate();
$viewOutput = $webpage->outputAttrs();
foreach ($viewOutput as $k => $v) {
$smarty->assign($k, $v);
}
// render the formobj attributes
$smarty->assign("view", $viewOutput);
//Translate Array of template variables to \Zend template object
foreach ($tplAttributes as $key => $value) {
$smarty->assign($key, $value);
}
self::registerSmartyPlugin($smarty);
//if ($webpage->consoleOutput) {
$smarty->display(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
//} else {
// return $smarty->fetch(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
//}
} | php | {
"resource": ""
} |
q264975 | ViewRenderer.renderPHP | test | static protected function renderPHP($viewObj, $tplAttributes = Array())
{
$view = TemplateHelper::getZendTemplate();
$tplFile = TemplateHelper::getTplFileWithPath($viewObj->templateFile, $viewObj->package);
$view->addScriptPath(dirname($tplFile));
//Translate Array of template variables to \Zend template object
foreach ($tplAttributes as $key => $value) {
if ($value == NULL) {
$view->$key = '';
} else {
$view->$key = $value;
}
}
if ($viewObj->consoleOutput) {
echo $view->render($viewObj->templateFile);
} else {
return $view->render($viewObj->templateFile);
}
} | php | {
"resource": ""
} |
q264976 | ViewRenderer.setHeaders | test | static protected function setHeaders($viewObj)
{
// get the cache attribute
// if cache = browser, set the cache control in headers
header('Pragma:', true);
header('Cache-Control: max-age=3600', true);
$offset = 60 * 60 * 24 * - 1;
$ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($ExpStr, true);
} | php | {
"resource": ""
} |
q264977 | CommentFactory.create | test | public function create(IssueInterface $issue, UserInterface $user)
{
$comment = new $this->className();
return $comment
->setIssue($issue)
->setWrittenBy($user);
} | php | {
"resource": ""
} |
q264978 | Router.listDir | test | public static function listDir(string $dir, bool $recursive = true)
{
$contents = array();
$subdirs = array();
$reader = dir($dir);
while ($entry = $reader->read())
{
if ($entry === "." || $entry === "..")
continue;
$entry = $dir . DIRECTORY_SEPARATOR . $entry;
if (substr($entry, -4) === ".php")
{
$contents[] = $entry;
}
elseif (is_dir($entry) && $recursive)
{
$subdirs = array_merge($subdirs, self::listDir($entry));
}
}
// Sort the direct contents of the directory so that index.php comes first
usort($contents, function ($a, $b) {
$sla = strlen($a);
$slb = strlen($b);
// index files come first
$a_idx = substr($a, -10) === "/index.php";
$b_idx = substr($b, -10) === "/index.php";
if ($a_idx !== $b_idx)
return $a_idx ? -1 : 1;
// sort the rest alphabetically
return strcasecmp($a, $b);
});
// Add the contents of subdirectories to the direct contents
return array_merge($contents, $subdirs);
} | php | {
"resource": ""
} |
q264979 | Router.sortModules | test | protected function sortModules()
{
parent::sortModules();
if ($this->root !== null && $this->root_search_path !== $this->search_path)
{
$this->root = null;
$this->root_search_path = null;
}
} | php | {
"resource": ""
} |
q264980 | Router.getRoutes | test | public function getRoutes()
{
if (!$this->sorted)
$this->sortModules();
$cache = $this->getCachedData();
if ($cache !== null && $this->root === null)
{
$root = $cache->get('data');
if ($root instanceof Route)
{
$this->root = $root;
$this->root_search_path = $cache->get('search_path');
}
}
if ($this->root !== null)
return $this->root;
$this->root = new Route('/', 0);
$this->root_search_path = $this->search_path;
foreach ($this->search_path as $module => $info)
{
$app_path = $info['path'];
$files = self::listDir($app_path);
foreach ($files as $path)
{
$file = str_replace($app_path, "", $path);
$parts = array_filter(explode("/", $file));
$ptr = $this->root;
$cnt = 0;
$l = count($parts);
foreach ($parts as $part)
{
$last = $cnt === $l - 1;
if ($last)
{
if ($part === "index.php")
{
// Only store if empty -
$ptr->addApp($path, '', $module);
}
else
{
$app_name = substr($part, 0, -4);
// Strip file extension
$ext = "";
$ext_pos = strrpos($app_name, '.');
if (!empty($ext_pos))
{
$ext = substr($app_name, $ext_pos);
$app_name = substr($app_name, 0, $ext_pos);
}
$app = $ptr->getSubRoute($app_name);
$app->addApp($path, $ext, $module);
}
break;
}
// Move the pointer deeper
$ptr = $ptr->getSubRoute($part);
++$cnt;
}
}
}
if ($cache !== null)
$cache->set('data', $this->root);
return $this->root;
} | php | {
"resource": ""
} |
q264981 | HTMLMenus.renderMenuItems | test | protected function renderMenuItems(&$menuItemArray)
{
$sHTML = "";
if (isset($menuItemArray["ATTRIBUTES"])) {
$sHTML .= $this->renderSingleMenuItem($menuItemArray);
} else {
foreach ($menuItemArray as $menuItem) {
$sHTML .= $this->renderSingleMenuItem($menuItem);
}
}
return $sHTML;
} | php | {
"resource": ""
} |
q264982 | HTMLMenus.renderSingleMenuItem | test | protected function renderSingleMenuItem(&$menuItem)
{
$profile = Openbizx::$app->getUserProfile();
$svcobj = Openbizx::getService(ACCESS_SERVICE);
$role = isset($profile["ROLE"]) ? $profile["ROLE"] : null;
if ( isset($menuItem["ATTRIBUTES"]['URL']) ) {
$url = $menuItem["ATTRIBUTES"]["URL"];
} elseif ( isset($menuItem["ATTRIBUTES"]['VIEW']) ) {
$view = $menuItem["ATTRIBUTES"]["VIEW"];
// menuitem's containing VIEW attribute is renderd if access is granted in accessservice.xml
// menuitem's are rendered if no definition is found in accessservice.xml (default)
if ($svcobj->allowViewAccess($view, $role)) {
$url = "javascript:GoToView('" . $view . "')";
} else {
return '';
}
}
$caption = $this->translate($menuItem["ATTRIBUTES"]["CAPTION"]);
$target = $menuItem["ATTRIBUTES"]["TARGET"];
$icon = $menuItem["ATTRIBUTES"]["ICON"];
$img = $icon ? "<img src='" . Openbizx::$app->getImageUrl() . "/$icon' class=menu_img> " : "";
if ($view)
$url = "javascript:GoToView('" . $view . "')";
if ($target)
$sHTML .= "<li><a href=\"" . $url . "\" target='$target'>$img" . $caption . "</a>";
else
$sHTML .= "<li><a href=\"" . $url . "\">$img" . $caption . "</a>";
if ($menuItem["MENUITEM"]) {
$sHTML .= "\n<ul>\n";
$sHTML .= $this->renderMenuItems($menuItem["MENUITEM"]);
$sHTML .= "</ul>";
}
$sHTML .= "</li>\n";
return $sHTML;
} | php | {
"resource": ""
} |
q264983 | TempFile.writeCsv | test | public function writeCsv(array $data): self
{
fputcsv($this->handler, $data, $this->delimiter, $this->enclosure, $this->escapeChar);
return $this;
} | php | {
"resource": ""
} |
q264984 | CheckCommand.configure | test | protected function configure()
{
parent::configure();
$this->setName('check');
$this->addOption(
'config',
'c',
InputOption::VALUE_OPTIONAL,
'Path to config file that defines the checks to process.'
);
$this->addOption(
'config-handler',
null,
InputOption::VALUE_OPTIONAL,
'Classname of a custom config handler implementing Environaut\Config\IConfigHandler.'
);
$this->addOption(
'cache-location',
null,
InputOption::VALUE_OPTIONAL,
'File path and name for the cache location to read from. Overrides defaults and config file value.'
);
$this->addOption(
'no-cache',
null,
InputOption::VALUE_NONE,
'Disables the use of caching (reading/writing). Remember, that the old cache file still survives!'
);
$this->setDescription('Check environment according to a set of checks.');
$this->setHelp(
<<<EOT
<info>This command checks the environment according to the checks from the configuration file.</info>
By default the <comment>current working directory</comment> will be used to find the configuration file and
all defined classes (checks and validators etc.).
Use
<comment>--autoload-dir [path/to/src]</comment> to change the autoload directory or
<comment>--config [path/to/environaut.(json|xml|php)]</comment> to set the configuration file lookup path or
<comment>--no-cache</comment> to disable to usage of a cache file.
EOT
);
} | php | {
"resource": ""
} |
q264985 | CheckCommand.readConfig | test | protected function readConfig()
{
$this->config = $this->getConfigHandler()->getConfig();
if ($this->config->has('introduction')) {
$this->output->writeln($this->config->get('introduction'));
$this->output->writeln('');
}
} | php | {
"resource": ""
} |
q264986 | CheckCommand.runChecks | test | protected function runChecks()
{
$runner_impl = $this->config->getRunnerImplementor();
$runner = new $runner_impl();
if (!$runner instanceof IRunner) {
throw new \InvalidArgumentException('The given runner "' . $runner_impl . '" must implement IRunner.');
}
$runner->setConfig($this->config);
$runner->setCommand($this);
$runner->setParameters(new Parameters($this->config->get('runner', array())));
$runner->setCache($this->getLoadedCache());
$run_was_successful = $runner->run();
$this->report = $runner->getReport();
$this->writeCache($run_was_successful);
} | php | {
"resource": ""
} |
q264987 | CheckCommand.runExport | test | protected function runExport()
{
$export_impl = $this->config->getExportImplementor();
$exporter = new $export_impl();
if (!$exporter instanceof IExport) {
throw new \InvalidArgumentException('The given exporter "' . $export_impl . '" must implement IExport.');
}
$exporter->setCommand($this);
$exporter->setReport($this->report);
$exporter->setParameters(new Parameters($this->config->get('export', array())));
$exporter->run();
} | php | {
"resource": ""
} |
q264988 | CheckCommand.writeCache | test | protected function writeCache($run_was_successful)
{
$disable_caching = $this->input->getOption('no-cache');
if (!empty($disable_caching)) {
return;
}
$cache_implementor = $this->config->getCacheImplementor();
$cache = new $cache_implementor();
if (!$cache instanceof ICache) {
throw new \InvalidArgumentException(
'The given cache class "' . $cache_implementor . '" does not implement ICache.'
);
}
$cache_params = new Parameters($this->config->get('cache', array()));
$cache->setParameters($cache_params);
// TODO use something like getenv('ENVIRONAUT_CACHE_DIR')?
$cache_location = $this->input->getOption('cache-location');
if (!empty($cache_location)) {
$cache->setLocation($cache_location);
}
$cache->addAll(
$this->report->getCachableSettings() // gets only cachable settings from successful checks
);
if ($cache->save()) {
$this->output->writeln(
PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
'</comment>" for subsequent runs...<info>ok</info>.' . PHP_EOL
);
} else {
$this->output->writeln(
PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
'</comment>" for subsequent runs...<error>FAILED</error>.' . PHP_EOL
);
}
} | php | {
"resource": ""
} |
q264989 | CheckCommand.getLoadedCache | test | protected function getLoadedCache()
{
if ($this->input->getOption('no-cache')) {
$this->readonly_cache = new ReadOnlyCache();
return $this->readonly_cache;
}
$cache_implementor = $this->config->getReadOnlyCacheImplementor();
$cache = new $cache_implementor();
if (!$cache instanceof IReadOnlyCache) {
throw new \InvalidArgumentException(
'The given cache class "' . $cache_implementor . '" does not implement IReadOnlyCache.'
);
}
$cache_params = new Parameters($this->config->get('cache', array()));
$cache_location = $this->input->getOption('cache-location');
$this->readonly_cache = $cache;
$this->readonly_cache->setParameters($cache_params);
if (!empty($cache_location)) {
if (is_readable($cache_location)) {
$this->readonly_cache->setLocation($cache_location);
} else {
$this->output->writeln(
'<comment>Given cache location could not be read. ' .
'Using fallback from config or default location.</comment>'
);
}
}
$this->readonly_cache->load();
$this->output->writeln(
'<info>Loaded <comment>' . count($cache->getAll()) . '</comment> cached settings from:</info> ' .
$cache->getLocation()
);
$this->output->writeln('');
return $this->readonly_cache;
} | php | {
"resource": ""
} |
q264990 | CheckCommand.initialize | test | protected function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output); // necessary to register autoloader
$config = $input->getOption('config');
if (!empty($config)) {
if (!is_readable($config)) {
throw new \InvalidArgumentException('Config file path "' . $config . '" is not readable.');
}
$this->config_path = $config;
if ($input->getOption('verbose')) {
$output->writeln('<comment>Config file path specified: ' . $this->config_path . '</comment>');
}
} else {
$this->config_path = $this->getCurrentWorkingDirectory();
if ($input->getOption('verbose')) {
$output->writeln(
'<comment>Config file path not specified, using "' . $this->config_path .
'" as default lookup location.</comment>'
);
}
}
$config_handler_implementor = $input->getOption('config-handler');
if (empty($config_handler_implementor)) {
$config_handler_implementor = 'Environaut\Config\ConfigHandler';
}
$this->config_handler = new $config_handler_implementor();
$this->config_handler->addLocation($this->config_path);
// TODO allow multiple locations for config option?
// $config_reader->setLocations(array($this->config_path));
} | php | {
"resource": ""
} |
q264991 | Executor.read | test | public function read($command, $eol = PHP_EOL)
{
exec($command, $output);
return implode($eol, $output);
} | php | {
"resource": ""
} |
q264992 | Executor.flush | test | public function flush(
$command,
array $streams,
array &$pipes = [],
$cwd = null,
array $env = null,
array $options = []
) {
$process = proc_open($command, $streams, $pipes, $cwd, $env, $options);
if (!is_resource($process)) {
throw new \RuntimeException('Error to open the process');
}
return proc_close($process);
} | php | {
"resource": ""
} |
q264993 | ChainsResults.valueIsChainable | test | protected function valueIsChainable($value): bool
{
$chainableObjects = $this->getChainableObjects();
if (! is_object($value)) {
return false;
} elseif (in_array('object', $chainableObjects)) {
return true;
} else {
$isInstanceOf = function (string $chainable) use ($value) {
return $value instanceof $chainable;
};
return count(array_filter($chainableObjects, $isInstanceOf)) !== 0;
}
} | php | {
"resource": ""
} |
q264994 | InputForm.validateForm | test | protected function validateForm($cleanError = true)
{
if($cleanError == true)
{
$this->validateErrors = array();
}
$this->dataPanel->rewind();
while($this->dataPanel->valid())
{
/* @var $element Element */
$element = $this->dataPanel->current();
if($element->label)
{
$elementName = $element->label;
}
else
{
$elementName = $element->text;
}
if ($element->checkRequired() === true &&
($element->value==null || $element->value == ""))
{
$errorMessage = $this->getMessage("FORM_ELEMENT_REQUIRED",array($elementName));
$this->validateErrors[$element->objectName] = $errorMessage;
//return false;
}
elseif ($element->value!==null && $element->Validate() == false)
{
$validateService = Openbizx::getService(VALIDATE_SERVICE);
$errorMessage = $this->getMessage("FORM_ELEMENT_INVALID_INPUT",array($elementName,$value,$element->validator));
if ($errorMessage == false)
{ //Couldn't get a clear error message so let's try this
$errorMessage = $validateService->getErrorMessage($element->validator, $elementName);
}
$this->validateErrors[$element->objectName] = $errorMessage;
//return false;
}
$this->dataPanel->next() ;
}
if (count($this->validateErrors) > 0)
{
throw new Openbizx\Validation\Exception($this->validateErrors);
return false;
}
return true;
} | php | {
"resource": ""
} |
q264995 | GroupSpecificationEq.isSatisfiedBy | test | public function isSatisfiedBy(GroupItem $item)
{
$field_name = $this->field_name;
if(in_array($item->$field_name, $this->val)){
return ($item->$field_name == $this->val);
}else{
return ($item->$field_name == $this->val);
}
} | php | {
"resource": ""
} |
q264996 | ClientCredentialsGrant.completeFlow | test | public function completeFlow(ClientEntity $client)
{
// Validate any scopes that are in the request
$scopeParam = $this->server->getRequestHandler()->getParam('scope');
$scopes = $this->validateScopes($scopeParam, $client);
// Create a new session
$session = new SessionEntity($this->server);
$session->setOwner('client', $client->getId());
$session->associateClient($client);
// Generate an access token
$accessToken = new AccessTokenEntity($this->server);
$accessToken->setId();
$accessToken->setExpireTime($this->getAccessTokenTTL() + time());
// Associate scopes with the session and access token
foreach ($scopes as $scope) {
$session->associateScope($scope);
}
foreach ($session->getScopes() as $scope) {
$accessToken->associateScope($scope);
}
// Save everything
$session->save();
$accessToken->setSession($session);
$accessToken->save();
$this->server->getTokenType()->setSession($session);
$this->server->getTokenType()->setParam('access_token', $accessToken->getId());
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
return $this->server->getTokenType()->generateResponse();
} | php | {
"resource": ""
} |
q264997 | BizField.getSqlValue | test | public function getSqlValue($input = null)
{
$value = ($input !== null) ? $input : $this->value;
if ($value === null) {
return "";
}
/*
if ($this->type != 'Number')
{
if (get_magic_quotes_gpc() == 0) {
$val = addcslashes($value, "\000\n\r\\'\"\032");
}
return "'$value'";
}
*/
return $value;
} | php | {
"resource": ""
} |
q264998 | BizField.getValue | test | public function getValue($formatted = true)
{
// need to ensure that value are retrieved from source/cache
//if ($this->getDataObj()->CheckDataRetrieved() == false)
//$this->getDataObj()->getActiveRecord();
if ($this->_prevValue == $this->value) {
return $this->_getValueCache;
}
//$value = stripcslashes($this->value);
$value = $this->value;
if ($this->valueExpression && trim($this->column) == "") {
$value = Expression::evaluateExpression($this->valueExpression, $this->getDataObj());
}
if ($this->format && $formatted) {
$value = Openbizx::$app->getTypeManager()->valueToFormattedString($this->type, $this->format, $value);
}
$this->_prevValue = $this->value;
$this->_getValueCache = $value;
return $value;
} | php | {
"resource": ""
} |
q264999 | BizField.saveOldValue | test | public function saveOldValue($value = null)
{
if ($value) {
$this->oldValue = $value;
} else {
$this->oldValue = $this->value;
}
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.