code stringlengths 31 2.05k | label_name stringclasses 5 values | label int64 0 4 |
|---|---|---|
function privWriteCentralFileHeader(&$p_header)
{
$v_result=1;
// TBC
//for(reset($p_header); $key = key($p_header); next($p_header)) {
//}
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
$p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
$v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
$p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
if ($p_header['comment_len'] != 0)
{
fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
}
// ----- Return
return $v_result;
}
| Base | 1 |
function privReadEndCentralDirZip4G(&$p_central_dir){
$zip = fopen($this->zipname,'rb');
$from = $p_central_dir['offset'];
$size = filesize($this->zipname);
while($from < $size){
fseek($zip,$from);
$sign = unpack('Vid',@fread($zip, 4));
//debug_out($from,$sign,0x02014b50);
if($sign['id'] == 0x02014b50){
$p_central_dir['offset'] = $from;
break;
}else{
$from = $from + 0xFFFFFFFF + 1;//
}
}
fclose($zip);
return 1;
}
| Class | 2 |
function privReadEndCentralDirZip4G(&$p_central_dir){
$zip = fopen($this->zipname,'rb');
$from = $p_central_dir['offset'];
$size = filesize($this->zipname);
while($from < $size){
fseek($zip,$from);
$sign = unpack('Vid',@fread($zip, 4));
//debug_out($from,$sign,0x02014b50);
if($sign['id'] == 0x02014b50){
$p_central_dir['offset'] = $from;
break;
}else{
$from = $from + 0xFFFFFFFF + 1;//
}
}
fclose($zip);
return 1;
}
| Base | 1 |
public function coverMake($cachePath,$path,$coverName,$size){
if(IO::fileNameExist($cachePath,$coverName)){return 'exists;';}
if(!is_dir(TEMP_FILES)){mk_dir(TEMP_FILES);}
$info = IO::info($path);$ext = $info['ext'];
$thumbFile = TEMP_FILES . $coverName;
$localFile = $this->localFile($path);
$movie = '3gp,avi,mp4,m4v,mov,mpg,mpeg,mpe,mts,m2ts,wmv,ogv,webm,vob,flv,f4v,mkv,rmvb,rm';
$isVideo = in_array($ext,explode(',',$movie));
// 过短的视频封面图,不指定时间;
$videoThumbTime = true;
if( $isVideo && is_array($info['fileInfoMore']) &&
isset($info['fileInfoMore']['playtime']) &&
floatval($info['fileInfoMore']['playtime']) <= 3 ){
$videoThumbTime = false;
}
if($isVideo){
// 不是本地文件; 切片后获取:mp4,mov,mpg,webm,f4v,ogv,avi,mkv,wmv;(部分失败)
if(!$localFile){
$localTemp = $thumbFile.'.'.$ext;
$localFile = $localTemp;
file_put_contents($localTemp,IO::fileSubstr($path,0,1024*600));
}
$this->thumbVideo($localFile,$thumbFile,$videoThumbTime);
} else {
if(!$localFile){$localFile = $this->pluginLocalFile($path);}
if($ext == 'ttf'){
$this->thumbFont($localFile,$thumbFile,$size);
}else{
$this->thumbImage($localFile,$thumbFile,$size,$ext);
}
}
if($localTemp){@unlink($localTemp);}
if(@file_exists($thumbFile)){
Cache::remove($coverName);
return IO::move($thumbFile,$cachePath);
}
Cache::set($coverName,'no',600);
del_file($thumbFile);
return 'convert error! localFile='.get_path_this($localFile);
} | Class | 2 |
public function coverMake($cachePath,$path,$coverName,$size){
if(IO::fileNameExist($cachePath,$coverName)){return 'exists;';}
if(!is_dir(TEMP_FILES)){mk_dir(TEMP_FILES);}
$info = IO::info($path);$ext = $info['ext'];
$thumbFile = TEMP_FILES . $coverName;
$localFile = $this->localFile($path);
$movie = '3gp,avi,mp4,m4v,mov,mpg,mpeg,mpe,mts,m2ts,wmv,ogv,webm,vob,flv,f4v,mkv,rmvb,rm';
$isVideo = in_array($ext,explode(',',$movie));
// 过短的视频封面图,不指定时间;
$videoThumbTime = true;
if( $isVideo && is_array($info['fileInfoMore']) &&
isset($info['fileInfoMore']['playtime']) &&
floatval($info['fileInfoMore']['playtime']) <= 3 ){
$videoThumbTime = false;
}
if($isVideo){
// 不是本地文件; 切片后获取:mp4,mov,mpg,webm,f4v,ogv,avi,mkv,wmv;(部分失败)
if(!$localFile){
$localTemp = $thumbFile.'.'.$ext;
$localFile = $localTemp;
file_put_contents($localTemp,IO::fileSubstr($path,0,1024*600));
}
$this->thumbVideo($localFile,$thumbFile,$videoThumbTime);
} else {
if(!$localFile){$localFile = $this->pluginLocalFile($path);}
if($ext == 'ttf'){
$this->thumbFont($localFile,$thumbFile,$size);
}else{
$this->thumbImage($localFile,$thumbFile,$size,$ext);
}
}
if($localTemp){@unlink($localTemp);}
if(@file_exists($thumbFile)){
Cache::remove($coverName);
return IO::move($thumbFile,$cachePath);
}
Cache::set($coverName,'no',600);
del_file($thumbFile);
return 'convert error! localFile='.get_path_this($localFile);
} | Base | 1 |
private function thumbVideo($file,$cacheFile,$videoThumbTime){
$command = $this->getFFmpeg();
if(!$command){
echo "Ffmpeg ".LNG("fileThumb.check.notFound");
return false;
}
$tempPath = $cacheFile;
if($GLOBALS['config']['systemOS'] == 'linux' && is_writable('/tmp/')){
mk_dir('/tmp/fileThumb');
$tempPath = '/tmp/fileThumb/'.rand_string(15).'.jpg';
}
$maxWidth = 800;
$timeAt = $videoThumbTime ? '-ss 00:00:03' : '';
$script = $command.' -i "'.$file.'" -y -f image2 '.$timeAt.' -vframes 1 '.$tempPath.' 2>&1';
$out = shell_exec($script);
if(!file_exists($tempPath)) {
if ($this->thumbVideoByLink($cacheFile)) return;
return $this->log('video thumb error,'.$out.';cmd='.$script);
}
move_path($tempPath,$cacheFile);
$cm = new ImageThumb($cacheFile,'file');
$cm->prorate($cacheFile,$maxWidth,$maxWidth);
} | Class | 2 |
private function thumbVideo($file,$cacheFile,$videoThumbTime){
$command = $this->getFFmpeg();
if(!$command){
echo "Ffmpeg ".LNG("fileThumb.check.notFound");
return false;
}
$tempPath = $cacheFile;
if($GLOBALS['config']['systemOS'] == 'linux' && is_writable('/tmp/')){
mk_dir('/tmp/fileThumb');
$tempPath = '/tmp/fileThumb/'.rand_string(15).'.jpg';
}
$maxWidth = 800;
$timeAt = $videoThumbTime ? '-ss 00:00:03' : '';
$script = $command.' -i "'.$file.'" -y -f image2 '.$timeAt.' -vframes 1 '.$tempPath.' 2>&1';
$out = shell_exec($script);
if(!file_exists($tempPath)) {
if ($this->thumbVideoByLink($cacheFile)) return;
return $this->log('video thumb error,'.$out.';cmd='.$script);
}
move_path($tempPath,$cacheFile);
$cm = new ImageThumb($cacheFile,'file');
$cm->prorate($cacheFile,$maxWidth,$maxWidth);
} | Base | 1 |
public function videoPreview($plugin){
$pickCount = 300;// 总共截取图片数(平均时间内截取)
$path = $plugin->filePath($GLOBALS['in']['path']);
$fileInfo = IO::info($path);
$fileInfo = Action('explorer.list')->pathInfoMore($fileInfo);
$tempFileName = 'preview-'.KodIO::hashPath($fileInfo).'.jpg';
$findSource = IO::fileNameExist($plugin->cachePath,$tempFileName);
if($findSource){return IO::fileOut(KodIO::make($findSource));}
$command = $plugin->getFFmpeg();
if(!$command){return show_json('command error',false);}
$localFile = $plugin->localFile($path);
if(!$localFile ){return show_json('not local file',false);}
$videoInfo = $this->parseVideoInfo($command,$localFile);
$this->storeVideoMetadata($fileInfo,$videoInfo);
if(!$videoInfo || $videoInfo['playtime'] <= 30){return show_json('time too short!',false);}
// $pickCount = $totalTime; 每秒生成一张图片; 可能很大
// 宽列数固定10幅图, 行数为总截取图除一行列数; https://blog.51cto.com/u_15639793/5297432
if(Cache::get($tempFileName)) return show_json('running');
Cache::set($tempFileName,'running',600);
ignore_timeout();
$tempPath = TEMP_FILES.$tempFileName;
$fps = $pickCount / $videoInfo['playtime'];
$sizeW = 150;
$tile = '10x'.ceil($pickCount / 10).'';
$scale = 'scale='.$sizeW.':-2'; //,pad='.$sizeW.':'.$sizeH.':-1:-1 -q:v 1~5 ;质量从最好到最差;
$args = '-sws_flags accurate_rnd -q:v 4 -an'; //更多参数; 设置图片缩放算法(不设置缩小时可能产生绿色条纹花屏);
$cmd = 'ffmpeg -y -i "'.$localFile.'" -vf "fps='.$fps.','.$scale.',tile='.$tile.'" '.$args.' "'.$tempPath.'"';
$this->log('[videoPreview start] '.$fileInfo['name'].';size='.size_format($fileInfo['size']),0,0);$timeStart = timeFloat();
$this->log('[videoPreview run] '.$cmd,0,0);
@shell_exec($cmd);//pr($cmd);exit;
Cache::remove($tempFileName);
$success = file_exists($tempPath) && filesize($tempPath) > 100;
$msg = $success ? 'success' : 'error';
$this->log('[videoPreview end] '.$fileInfo['name'].';time='.(timeFloat() - $timeStart).'s;'.$msg,0,0); | Class | 2 |
public function videoPreview($plugin){
$pickCount = 300;// 总共截取图片数(平均时间内截取)
$path = $plugin->filePath($GLOBALS['in']['path']);
$fileInfo = IO::info($path);
$fileInfo = Action('explorer.list')->pathInfoMore($fileInfo);
$tempFileName = 'preview-'.KodIO::hashPath($fileInfo).'.jpg';
$findSource = IO::fileNameExist($plugin->cachePath,$tempFileName);
if($findSource){return IO::fileOut(KodIO::make($findSource));}
$command = $plugin->getFFmpeg();
if(!$command){return show_json('command error',false);}
$localFile = $plugin->localFile($path);
if(!$localFile ){return show_json('not local file',false);}
$videoInfo = $this->parseVideoInfo($command,$localFile);
$this->storeVideoMetadata($fileInfo,$videoInfo);
if(!$videoInfo || $videoInfo['playtime'] <= 30){return show_json('time too short!',false);}
// $pickCount = $totalTime; 每秒生成一张图片; 可能很大
// 宽列数固定10幅图, 行数为总截取图除一行列数; https://blog.51cto.com/u_15639793/5297432
if(Cache::get($tempFileName)) return show_json('running');
Cache::set($tempFileName,'running',600);
ignore_timeout();
$tempPath = TEMP_FILES.$tempFileName;
$fps = $pickCount / $videoInfo['playtime'];
$sizeW = 150;
$tile = '10x'.ceil($pickCount / 10).'';
$scale = 'scale='.$sizeW.':-2'; //,pad='.$sizeW.':'.$sizeH.':-1:-1 -q:v 1~5 ;质量从最好到最差;
$args = '-sws_flags accurate_rnd -q:v 4 -an'; //更多参数; 设置图片缩放算法(不设置缩小时可能产生绿色条纹花屏);
$cmd = 'ffmpeg -y -i "'.$localFile.'" -vf "fps='.$fps.','.$scale.',tile='.$tile.'" '.$args.' "'.$tempPath.'"';
$this->log('[videoPreview start] '.$fileInfo['name'].';size='.size_format($fileInfo['size']),0,0);$timeStart = timeFloat();
$this->log('[videoPreview run] '.$cmd,0,0);
@shell_exec($cmd);//pr($cmd);exit;
Cache::remove($tempFileName);
$success = file_exists($tempPath) && filesize($tempPath) > 100;
$msg = $success ? 'success' : 'error';
$this->log('[videoPreview end] '.$fileInfo['name'].';time='.(timeFloat() - $timeStart).'s;'.$msg,0,0); | Base | 1 |
public function processFind($search){
$cmd = "ps -eo user,pid,ppid,args | grep '".$search."' | grep -v grep | awk '{print $2}'";
if($GLOBALS['config']['systemOS'] != 'windows'){return trim(@shell_exec($cmd));}
// windows 获取pid;
$cmd = 'WMIC process where "Commandline like \'%%%'.$search.'%%%\'" get Caption,Processid,Commandline';
$res = trim(@shell_exec($cmd));
$resArr = explode("\n",trim($res));
if(!$resArr || count($resArr) <= 3) return '';
$lineFind = $resArr[count($resArr) - 3];// 最后两个一个为wmic,和cmd;
$res = preg_match("/.*\s+(\d+)\s*$/",$lineFind,$match);
if($res && is_array($match) && $match[1]){return $match[1];}
return '';
} | Class | 2 |
public function processFind($search){
$cmd = "ps -eo user,pid,ppid,args | grep '".$search."' | grep -v grep | awk '{print $2}'";
if($GLOBALS['config']['systemOS'] != 'windows'){return trim(@shell_exec($cmd));}
// windows 获取pid;
$cmd = 'WMIC process where "Commandline like \'%%%'.$search.'%%%\'" get Caption,Processid,Commandline';
$res = trim(@shell_exec($cmd));
$resArr = explode("\n",trim($res));
if(!$resArr || count($resArr) <= 3) return '';
$lineFind = $resArr[count($resArr) - 3];// 最后两个一个为wmic,和cmd;
$res = preg_match("/.*\s+(\d+)\s*$/",$lineFind,$match);
if($res && is_array($match) && $match[1]){return $match[1];}
return '';
} | Base | 1 |
private function convert2pdf($file,$cacheFile,$ext){
$command = $this->getSoffice();
if(!$command){
Action($this->pluginName)->showTips(LNG('officeViewer.libreOffice.sofficeError'), 'LibreOffice');
}
//linux下$cacheFile不可写问题,先生成到/tmp下;再复制出来
$tempPath = $cacheFile;
if($GLOBALS['config']['systemOS'] == 'linux' && is_writable('/tmp/')){
mk_dir('/tmp/libreOffice');
$tempPath = '/tmp/libreOffice/'.rand_string(15).'.pdf';
}
$fname = get_path_this($tempPath);
$fpath = get_path_father($tempPath);
// 转换类型'pdf'改为'新文件名.pdf',会生成'源文件名.新文件名.pdf'
$export = 'export HOME=/tmp/libreOffice && ';
$script = $export.$command . ' --headless --invisible --convert-to '.$fname.' "'.$file.'" --outdir '.$fpath;
$out = shell_exec($script);
$tname = substr(end(explode('/', $file)), 0, -strlen('.'.$ext));
$tfile = $fpath . $tname . '.' . $fname; // 源文件名.filename.pdf
if(!file_exists($tfile)){
write_log('libreoffice convert error: '.$script."\n".$out,'error');
}
$res = move_path($tfile,$cacheFile);
if (!$res) write_log('libreoffice move file error: '.$tfile.'=>'.$cacheFile, 'error');
} | Class | 2 |
private function convert2pdf($file,$cacheFile,$ext){
$command = $this->getSoffice();
if(!$command){
Action($this->pluginName)->showTips(LNG('officeViewer.libreOffice.sofficeError'), 'LibreOffice');
}
//linux下$cacheFile不可写问题,先生成到/tmp下;再复制出来
$tempPath = $cacheFile;
if($GLOBALS['config']['systemOS'] == 'linux' && is_writable('/tmp/')){
mk_dir('/tmp/libreOffice');
$tempPath = '/tmp/libreOffice/'.rand_string(15).'.pdf';
}
$fname = get_path_this($tempPath);
$fpath = get_path_father($tempPath);
// 转换类型'pdf'改为'新文件名.pdf',会生成'源文件名.新文件名.pdf'
$export = 'export HOME=/tmp/libreOffice && ';
$script = $export.$command . ' --headless --invisible --convert-to '.$fname.' "'.$file.'" --outdir '.$fpath;
$out = shell_exec($script);
$tname = substr(end(explode('/', $file)), 0, -strlen('.'.$ext));
$tfile = $fpath . $tname . '.' . $fname; // 源文件名.filename.pdf
if(!file_exists($tfile)){
write_log('libreoffice convert error: '.$script."\n".$out,'error');
}
$res = move_path($tfile,$cacheFile);
if (!$res) write_log('libreoffice move file error: '.$tfile.'=>'.$cacheFile, 'error');
} | Base | 1 |
public function getSoffice(){
$check = 'LibreOffice';
$data = Action($this->pluginName)->_appConfig('lb');
$bin = isset($data['soffice']) ? $data['soffice'] : '';
$bin = '"'.trim(iconv_system($bin)).'"'; // win路径空格处理
$result = $this->checkBin($bin,$check);
return $result ? $bin : false;
} | Class | 2 |
public function getSoffice(){
$check = 'LibreOffice';
$data = Action($this->pluginName)->_appConfig('lb');
$bin = isset($data['soffice']) ? $data['soffice'] : '';
$bin = '"'.trim(iconv_system($bin)).'"'; // win路径空格处理
$result = $this->checkBin($bin,$check);
return $result ? $bin : false;
} | Base | 1 |
public function checkAccessToken(){
$model = $this->loadModel('Plugin');
$config = $model->getConfig('fileView');
if(!$config['apiKey']){
return;
}
$timeTo = isset($this->in['timeTo'])?intval($this->in['timeTo']):'';
$token = md5($config['apiKey'].$this->in['path'].$timeTo);
//show_tips(array($config['apiKey'],$token,$this->in));
if($token != $this->in['token']){
show_tips('token 错误!');
}
if($timeTo != '' && $timeTo <= time()){
show_tips('token已失效!');
}
}
| Base | 1 |
public function checkAccessToken(){
$model = $this->loadModel('Plugin');
$config = $model->getConfig('fileView');
if(!$config['apiKey']){
return;
}
$timeTo = isset($this->in['timeTo'])?intval($this->in['timeTo']):'';
$token = md5($config['apiKey'].$this->in['path'].$timeTo);
//show_tips(array($config['apiKey'],$token,$this->in));
if($token != $this->in['token']){
show_tips('token 错误!');
}
if($timeTo != '' && $timeTo <= time()){
show_tips('token已失效!');
}
}
| Base | 1 |
public function checkAccessToken(){
$model = $this->loadModel('Plugin');
$config = $model->getConfig('fileView');
if(!$config['apiKey']){
return;
}
$timeTo = isset($this->in['timeTo'])?intval($this->in['timeTo']):'';
$token = md5($config['apiKey'].$this->in['path'].$timeTo);
//show_tips(array($config['apiKey'],$token,$this->in));
if($token != $this->in['token']){
show_tips('token 错误!');
}
if($timeTo != '' && $timeTo <= time()){
show_tips('token已失效!');
}
}
| Base | 1 |
public function checkAccessToken(){
$model = $this->loadModel('Plugin');
$config = $model->getConfig('fileView');
if(!$config['apiKey']){
return;
}
$timeTo = isset($this->in['timeTo'])?intval($this->in['timeTo']):'';
$token = md5($config['apiKey'].$this->in['path'].$timeTo);
//show_tips(array($config['apiKey'],$token,$this->in));
if($token != $this->in['token']){
show_tips('token 错误!');
}
if($timeTo != '' && $timeTo <= time()){
show_tips('token已失效!');
}
}
| Base | 1 |
function get_path_ext($path){
$name = get_path_this($path);
$ext = '';
if(strstr($name,'.')){
$ext = substr($name,strrpos($name,'.')+1);
$ext = strtolower($ext);
}
if (strlen($ext)>3 && preg_match("/([\x81-\xfe][\x40-\xfe])/", $ext, $match)) {
$ext = '';
}
return htmlspecialchars($ext);
}
| Base | 1 |
function get_path_ext($path){
$name = get_path_this($path);
$ext = '';
if(strstr($name,'.')){
$ext = substr($name,strrpos($name,'.')+1);
$ext = strtolower($ext);
}
if (strlen($ext)>3 && preg_match("/([\x81-\xfe][\x40-\xfe])/", $ext, $match)) {
$ext = '';
}
return htmlspecialchars($ext);
}
| Base | 1 |
function get_path_ext($path){
$name = get_path_this($path);
$ext = '';
if(strstr($name,'.')){
$ext = substr($name,strrpos($name,'.')+1);
$ext = strtolower($ext);
}
if (strlen($ext)>3 && preg_match("/([\x81-\xfe][\x40-\xfe])/", $ext, $match)) {
$ext = '';
}
return htmlspecialchars($ext);
}
| Base | 1 |
function get_path_ext($path){
$name = get_path_this($path);
$ext = '';
if(strstr($name,'.')){
$ext = substr($name,strrpos($name,'.')+1);
$ext = strtolower($ext);
}
if (strlen($ext)>3 && preg_match("/([\x81-\xfe][\x40-\xfe])/", $ext, $match)) {
$ext = '';
}
return htmlspecialchars($ext);
}
| Base | 1 |
function hash_path($path,$addExt=false){
$password = 'kodcloud';
if(isset($GLOBALS['config']['settingSystem']['systemPassword'])){
$password = $GLOBALS['config']['settingSystem']['systemPassword'];
}
$pre = substr(md5($path.$password),0,8);
$result = $pre.md5($path);
if(file_exists($path)){
$result = $pre.md5($path.filemtime($path));
if(filesize($path) < 50*1024*1024){
$fileMd5 = @md5_file($path);
if($fileMd5){
$result = $fileMd5;
}
}
}
if($addExt){
$result = $result.'.'.get_path_ext($path);
}
return $result;
}
| Base | 1 |
function hash_path($path,$addExt=false){
$password = 'kodcloud';
if(isset($GLOBALS['config']['settingSystem']['systemPassword'])){
$password = $GLOBALS['config']['settingSystem']['systemPassword'];
}
$pre = substr(md5($path.$password),0,8);
$result = $pre.md5($path);
if(file_exists($path)){
$result = $pre.md5($path.filemtime($path));
if(filesize($path) < 50*1024*1024){
$fileMd5 = @md5_file($path);
if($fileMd5){
$result = $fileMd5;
}
}
}
if($addExt){
$result = $result.'.'.get_path_ext($path);
}
return $result;
}
| Base | 1 |
function hash_path($path,$addExt=false){
$password = 'kodcloud';
if(isset($GLOBALS['config']['settingSystem']['systemPassword'])){
$password = $GLOBALS['config']['settingSystem']['systemPassword'];
}
$pre = substr(md5($path.$password),0,8);
$result = $pre.md5($path);
if(file_exists($path)){
$result = $pre.md5($path.filemtime($path));
if(filesize($path) < 50*1024*1024){
$fileMd5 = @md5_file($path);
if($fileMd5){
$result = $fileMd5;
}
}
}
if($addExt){
$result = $result.'.'.get_path_ext($path);
}
return $result;
}
| Base | 1 |
function hash_path($path,$addExt=false){
$password = 'kodcloud';
if(isset($GLOBALS['config']['settingSystem']['systemPassword'])){
$password = $GLOBALS['config']['settingSystem']['systemPassword'];
}
$pre = substr(md5($path.$password),0,8);
$result = $pre.md5($path);
if(file_exists($path)){
$result = $pre.md5($path.filemtime($path));
if(filesize($path) < 50*1024*1024){
$fileMd5 = @md5_file($path);
if($fileMd5){
$result = $fileMd5;
}
}
}
if($addExt){
$result = $result.'.'.get_path_ext($path);
}
return $result;
}
| Base | 1 |
function prorate($toFile, $toW, $toH){
if(!$this->im){
return false;
}
$toWH = $toW / $toH;
$srcWH = $this->srcW / $this->srcH;
if ($toWH<=$srcWH) {
$ftoW = $toW;
$ftoH = $ftoW * ($this->srcH / $this->srcW);
} else {
$ftoH = $toH;
$ftoW = $ftoH * ($this->srcW / $this->srcH);
}
if ($this->srcW > $toW || $this->srcH > $toH) {
$cImg = $this->creatImage($this->im, $ftoW, $ftoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
} else {
$cImg = $this->creatImage($this->im, $this->srcW, $this->srcH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
}
} | Base | 1 |
function prorate($toFile, $toW, $toH){
if(!$this->im){
return false;
}
$toWH = $toW / $toH;
$srcWH = $this->srcW / $this->srcH;
if ($toWH<=$srcWH) {
$ftoW = $toW;
$ftoH = $ftoW * ($this->srcH / $this->srcW);
} else {
$ftoH = $toH;
$ftoW = $ftoH * ($this->srcW / $this->srcH);
}
if ($this->srcW > $toW || $this->srcH > $toH) {
$cImg = $this->creatImage($this->im, $ftoW, $ftoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
} else {
$cImg = $this->creatImage($this->im, $this->srcW, $this->srcH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
}
} | Base | 1 |
function prorate($toFile, $toW, $toH){
if(!$this->im){
return false;
}
$toWH = $toW / $toH;
$srcWH = $this->srcW / $this->srcH;
if ($toWH<=$srcWH) {
$ftoW = $toW;
$ftoH = $ftoW * ($this->srcH / $this->srcW);
} else {
$ftoH = $toH;
$ftoW = $ftoH * ($this->srcW / $this->srcH);
}
if ($this->srcW > $toW || $this->srcH > $toH) {
$cImg = $this->creatImage($this->im, $ftoW, $ftoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
} else {
$cImg = $this->creatImage($this->im, $this->srcW, $this->srcH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
}
} | Base | 1 |
function prorate($toFile, $toW, $toH){
if(!$this->im){
return false;
}
$toWH = $toW / $toH;
$srcWH = $this->srcW / $this->srcH;
if ($toWH<=$srcWH) {
$ftoW = $toW;
$ftoH = $ftoW * ($this->srcH / $this->srcW);
} else {
$ftoH = $toH;
$ftoW = $ftoH * ($this->srcW / $this->srcH);
}
if ($this->srcW > $toW || $this->srcH > $toH) {
$cImg = $this->creatImage($this->im, $ftoW, $ftoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
} else {
$cImg = $this->creatImage($this->im, $this->srcW, $this->srcH, 0, 0, 0, 0, $this->srcW, $this->srcH);
return $this->echoImage($cImg, $toFile);
}
} | Base | 1 |
protected function fixTags($tags) {
// move @ tags out of variable namespace
foreach ($tags as &$tag) {
if ($tag{0} == $this->lessc->vPrefix)
$tag[0] = $this->lessc->mPrefix;
}
return $tags;
} | Base | 1 |
protected function fixTags($tags) {
// move @ tags out of variable namespace
foreach ($tags as &$tag) {
if ($tag{0} == $this->lessc->vPrefix)
$tag[0] = $this->lessc->mPrefix;
}
return $tags;
} | Base | 1 |
protected function fixTags($tags) {
// move @ tags out of variable namespace
foreach ($tags as &$tag) {
if ($tag{0} == $this->lessc->vPrefix)
$tag[0] = $this->lessc->mPrefix;
}
return $tags;
} | Base | 1 |
protected function fixTags($tags) {
// move @ tags out of variable namespace
foreach ($tags as &$tag) {
if ($tag{0} == $this->lessc->vPrefix)
$tag[0] = $this->lessc->mPrefix;
}
return $tags;
} | Base | 1 |
public function get_data($query = '')
{
$page_number = ($this->get_pagenum() - 1) * $this->limit;
$orderby = "ORDER BY {$this->tb_prefix}sms_subscribes.date DESC";
$where = "";
if (isset($_REQUEST['orderby'])) {
$orderby = "ORDER BY {$this->tb_prefix}sms_subscribes.{$_REQUEST['orderby']} {$_REQUEST['order']}";
}
if (!$query) {
if (isset($_GET['group_id']) && $_GET['group_id']) {
$group_id = sanitize_text_field($_GET['group_id']);
$where = "WHERE group_ID = {$group_id}";
}
if (isset($_GET['country_code']) && $_GET['country_code']) {
$country_code = sanitize_text_field($_GET['country_code']);
if ($where) {
$where .= " AND mobile LIKE '{$country_code}%'";
} else {
$where = "WHERE mobile LIKE '{$country_code}%'";
}
}
$query = $this->db->prepare("SELECT * FROM {$this->tb_prefix}sms_subscribes {$where} {$orderby} LIMIT %d OFFSET %d", $this->limit, $page_number);
} else {
$query .= $this->db->prepare(" LIMIT %d OFFSET %d", $this->limit, $page_number);
}
$result = $this->db->get_results($query, ARRAY_A);
return $result;
} | Base | 1 |
public function column_name($item)
{
/**
* Sanitize the input
*/
$page = sanitize_text_field($_REQUEST['page']);
//Build row actions
$actions = array(
'edit' => sprintf('<a href="#" onclick="wp_sms_edit_subscriber(%s)">' . __('Edit', 'wp-sms') . '</a>', $item['ID']),
'delete' => sprintf('<a href="?page=%s&action=%s&ID=%s">' . __('Delete', 'wp-sms') . '</a>', $page, 'delete', $item['ID']),
);
//Return the title contents
return sprintf('%1$s %3$s',
/*$1%s*/
esc_html($item['name']),
/*$2%s*/
$item['ID'],
/*$2%s*/
$this->row_actions($actions)
);
} | Base | 1 |
public function __construct(
Dispatcher $events,
SessionAuthenticator $authenticator,
Rememberer $rememberer,
Factory $view,
UrlGenerator $url
) {
$this->events = $events;
$this->authenticator = $authenticator;
$this->rememberer = $rememberer;
$this->view = $view;
$this->url = $url;
} | Base | 1 |
public function __construct(
string $appName,
IRequest $request,
ISession $session,
IUserSession $userSession,
SAMLSettings $samlSettings,
UserBackend $userBackend,
IConfig $config,
IURLGenerator $urlGenerator,
LoggerInterface $logger,
IL10N $l,
UserResolver $userResolver,
UserData $userData,
ICrypto $crypto
) {
parent::__construct($appName, $request);
$this->session = $session;
$this->userSession = $userSession;
$this->samlSettings = $samlSettings;
$this->userBackend = $userBackend;
$this->config = $config;
$this->urlGenerator = $urlGenerator;
$this->logger = $logger;
$this->l = $l;
$this->userResolver = $userResolver;
$this->userData = $userData;
$this->crypto = $crypto;
} | Base | 1 |
Group createNew(String name, String description, int organizationId) {
AffectedRowCountAndKey<Integer> insert = groupRepository.insert(name, description, organizationId);
return groupRepository.getById(insert.getKey());
} | Base | 1 |
public Optional<GroupModification> update(int listId, GroupModification modification) {
if(groupRepository.getOptionalById(listId).isEmpty() || CollectionUtils.isEmpty(modification.getItems())) {
return Optional.empty();
}
List<String> existingValues = groupRepository.getAllValuesIncludingNotActive(listId);
List<GroupMemberModification> notPresent = modification.getItems().stream()
.filter(i -> i.getId() == null && !existingValues.contains(i.getValue().strip().toLowerCase()))
.distinct()
.collect(Collectors.toList());
if(!notPresent.isEmpty()) {
var insertResult = insertMembers(listId, notPresent);
if(!insertResult.isSuccess()) {
var error = Objects.requireNonNull(insertResult.getFirstErrorOrNull());
throw new DuplicateGroupItemException(error.getDescription());
}
}
groupRepository.update(listId, modification.getName(), modification.getDescription());
return loadComplete(listId);
} | Base | 1 |
default int[] insert(int groupId, List<GroupMemberModification> members) {
MapSqlParameterSource[] params = members.stream()
.map(i -> new MapSqlParameterSource("groupId", groupId).addValue("value", i.getValue().toLowerCase()).addValue("description", i.getDescription()))
.toArray(MapSqlParameterSource[]::new);
return getNamedParameterJdbcTemplate().batchUpdate("insert into group_member(a_group_id_fk, value, description) values(:groupId, :value, :description)", params);
} | Base | 1 |
public static String pathOffset(String path, RoutingContext context) {
final Route route = context.currentRoute();
// cannot make any assumptions
if (route == null) {
return path;
}
if (!route.isExactPath()) {
final String rest = context.pathParam("*");
if (rest != null) {
// normalize
if (rest.length() > 0) {
if (rest.charAt(0) == '/') {
return rest;
} else {
return "/" + rest;
}
} else {
return "/";
}
}
}
int prefixLen = 0;
String mountPoint = context.mountPoint();
if (mountPoint != null) {
prefixLen = mountPoint.length();
// special case we need to verify if a trailing slash is present and exclude
if (mountPoint.charAt(mountPoint.length() - 1) == '/') {
prefixLen--;
}
}
// we can only safely skip the route path if there are no variables or regex
if (!route.isRegexPath()) {
String routePath = route.getPath();
if (routePath != null) {
prefixLen += routePath.length();
// special case we need to verify if a trailing slash is present and exclude
if (routePath.charAt(routePath.length() - 1) == '/') {
prefixLen--;
}
}
}
return prefixLen != 0 ? path.substring(prefixLen) : path;
} | Base | 1 |
protected void onInitialize() {
super.onInitialize();
IModel<String> valueModel = new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
return getUser().getAccessToken();
}
};
add(new TextField<String>("value", valueModel) {
@Override
protected String[] getInputTypes() {
return new String[] {"password"};
}
});
add(new CopyToClipboardLink("copy", valueModel));
add(new Link<Void>("regenerate") {
@Override
public void onClick() {
getUser().setAccessToken(RandomStringUtils.randomAlphanumeric(User.ACCESS_TOKEN_LEN));
OneDev.getInstance(UserManager.class).save(getUser());
Session.get().success("Access token regenerated");
setResponsePage(getPage());
}
}.add(new ConfirmClickModifier("This will invalidate current token and generate a new one, do you want to continue?")));
} | Base | 1 |
public ConfigDatabase(final DataSource dataSource, final XStreamInfoSerialBinding binding) {
this(dataSource, binding, null);
} | Base | 1 |
private Dialect dialect() {
if (dialect == null) {
this.dialect = Dialect.detect(dataSource);
}
return dialect;
} | Base | 1 |
public ConfigDatabase(
final DataSource dataSource,
final XStreamInfoSerialBinding binding,
CacheProvider cacheProvider) {
this.binding = binding;
this.template = new NamedParameterJdbcTemplate(dataSource);
// cannot use dataSource at this point due to spring context config hack
// in place to support tx during testing
this.dataSource = dataSource;
this.catalogRowMapper = new InfoRowMapper<CatalogInfo>(CatalogInfo.class, binding);
this.configRowMapper = new InfoRowMapper<Info>(Info.class, binding);
if (cacheProvider == null) {
cacheProvider = DefaultCacheProvider.findProvider();
}
cache = cacheProvider.getCache("catalog");
identityCache = cacheProvider.getCache("catalogNames");
serviceCache = cacheProvider.getCache("services");
locks = new ConcurrentHashMap<>();
} | Base | 1 |
public <T extends CatalogInfo> int count(final Class<T> of, final Filter filter) {
QueryBuilder<T> sqlBuilder = QueryBuilder.forCount(dialect, of, dbMappings).filter(filter);
final StringBuilder sql = sqlBuilder.build();
final Filter unsupportedFilter = sqlBuilder.getUnsupportedFilter();
final boolean fullySupported = Filter.INCLUDE.equals(unsupportedFilter);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Original filter: " + filter);
LOGGER.finer("Supported filter: " + sqlBuilder.getSupportedFilter());
LOGGER.finer("Unsupported filter: " + sqlBuilder.getUnsupportedFilter());
}
final int count;
if (fullySupported) {
final Map<String, Object> namedParameters = sqlBuilder.getNamedParameters();
logStatement(sql, namedParameters);
count = template.queryForObject(sql.toString(), namedParameters, Integer.class);
} else {
LOGGER.fine(
"Filter is not fully supported, doing scan of supported part to return the number of matches");
// going the expensive route, filtering as much as possible
CloseableIterator<T> iterator = query(of, filter, null, null, (SortBy) null);
try {
return Iterators.size(iterator);
} finally {
iterator.close();
}
}
return count;
} | Base | 1 |
public static Dialect detect(DataSource dataSource) {
Dialect dialect;
try {
Connection conn = dataSource.getConnection();
String driver = conn.getMetaData().getDriverName();
if (driver.contains("Oracle")) {
dialect = new OracleDialect();
} else {
dialect = new Dialect();
}
conn.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return dialect;
} | Base | 1 |
public Object visit(PropertyIsNil filter, Object extraData) {
final PropertyName propertyName = (PropertyName) filter.getExpression();
final String propertyTypesParam = propertyTypesParam(propertyName);
StringBuilder builder =
append(
extraData,
"oid IN (SELECT oid FROM object_property WHERE property_type IN (:",
propertyTypesParam,
") AND value IS NULL) /* ",
filter.toString(),
" */\n");
return builder;
} | Base | 1 |
public Object visit(IncludeFilter filter, Object extraData) {
append(extraData, "1 = 1 /* INCLUDE */\n");
return extraData;
} | Base | 1 |
public Object visit(And filter, Object extraData) {
StringBuilder sql = (StringBuilder) extraData;
List<Filter> children = filter.getChildren();
checkArgument(children.size() > 0);
sql.append("(\n ");
for (Iterator<Filter> it = children.iterator(); it.hasNext(); ) {
Filter child = it.next();
sql = (StringBuilder) child.accept(this, sql);
if (it.hasNext()) {
sql = append(extraData, " AND\n ");
}
}
sql.append(")");
return sql;
} | Base | 1 |
public FilterToCatalogSQL(Class<?> queryType, DbMappings dbMappings) {
this.queryType = queryType;
this.dbMappings = dbMappings;
List<Integer> concreteQueryTypes = dbMappings.getConcreteQueryTypes(queryType);
namedParams.put("types", concreteQueryTypes);
} | Base | 1 |
public Object visit(Not filter, Object extraData) {
filter.getFilter().accept(this, append(extraData, "NOT ("));
return append(extraData, ")");
} | Base | 1 |
public Object visit(ExcludeFilter filter, Object extraData) {
append(extraData, "0 = 1 /* EXCLUDE */\n");
return extraData;
} | Base | 1 |
public Object visit(Or filter, Object extraData) {
StringBuilder sql = (StringBuilder) extraData;
List<Filter> children = filter.getChildren();
checkArgument(children.size() > 0);
sql.append("(");
for (Iterator<Filter> it = children.iterator(); it.hasNext(); ) {
Filter child = it.next();
sql = (StringBuilder) child.accept(this, sql);
if (it.hasNext()) {
sql = append(extraData, " OR\n ");
}
}
sql.append(")");
return sql;
} | Base | 1 |
private String handleInstanceOf(IsInstanceOf instanceOf) {
Expression expression1 = instanceOf.getParameters().get(0);
Class<?> clazz = expression1.evaluate(null, Class.class);
if (clazz == null || dbMappings.getTypeId(clazz) == null) {
return "0 = 1 /* EXCLUDE */\n";
}
Integer typeId = dbMappings.getTypeId(clazz);
return "type_id = " + typeId + " /* isInstanceOf " + clazz.getName() + " */\n";
} | Base | 1 |
public Object visit(PropertyIsNull filter, Object extraData) {
final PropertyName propertyName = (PropertyName) filter.getExpression();
final String propertyTypesParam = propertyTypesParam(propertyName);
StringBuilder builder =
append(
extraData,
"(oid IN (SELECT oid FROM object_property WHERE property_type IN (:",
propertyTypesParam,
") AND value IS NULL) OR oid NOT IN (SELECT oid FROM object_property WHERE property_type IN (:"
+ propertyTypesParam
+ "))) /* ",
filter.toString(),
" */\n");
return builder;
} | Base | 1 |
public void applyOffsetLimit(
StringBuilder sql, @Nullable Integer offset, @Nullable Integer limit) {
// some db's require limit to be present of offset is
if (offset != null && limit == null) {
limit = Integer.MAX_VALUE; // ensure we don't wrap around
}
if (limit != null && offset == null) {
offset = 0;
limit += 1; // not zero-based
}
if (offset != null && limit != null) {
sql.insert(0, "SELECT * FROM (SELECT query.*, rownum rnum FROM (\n");
sql.append(") query\n");
if (limit != Integer.MAX_VALUE) {
limit = offset + limit;
}
sql.append("WHERE rownum <= ").append(limit).append(")\n");
sql.append("WHERE rnum > ").append(offset);
}
} | Base | 1 |
public StringBuilder build() {
StringBuilder whereClause = buildWhereClause();
StringBuilder query = new StringBuilder();
if (isCountQuery) {
if (Filter.INCLUDE.equals(this.originalFilter)) {
query.append("SELECT COUNT(oid) FROM object WHERE type_id IN (:types)");
} else {
query.append("SELECT COUNT(oid) FROM object WHERE type_id IN (:types) AND (\n");
query.append(whereClause).append(")");
}
} else {
SortBy[] orders = this.sortOrder;
if (orders == null) {
query.append("SELECT id FROM object WHERE type_id IN (:types) AND (\n");
query.append(whereClause).append(")");
query.append(" ORDER BY oid");
} else {
querySortBy(query, whereClause, orders);
}
applyOffsetLimit(query);
}
return query;
} | Base | 1 |
public ConfigDatabase configDatabase() {
return new ConfigDatabase(
dataSource(), new XStreamInfoSerialBinding(new XStreamPersisterFactory()));
} | Base | 1 |
public void testSort3() {
Filter filter = Predicates.acceptAll();
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.sortOrder(
Predicates.asc("foo"),
Predicates.desc("bar"),
Predicates.asc("baz"))
.build();
} | Base | 1 |
public void testIsNil() {
// Create the filter
Filter filter = Predicates.isNull("name");
// Build it
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.build();
String sql = build.toString();
String sqlNil =
"oid IN (SELECT oid FROM object_property WHERE property_type IN (:"
+ "ptype0) AND value IS NULL)";
// Ensure the following sql is present
assertThat(sql, containsString(sqlNil));
} | Base | 1 |
public void testSort1() {
Filter filter = Predicates.acceptAll();
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.sortOrder(Predicates.asc("foo"))
.build();
} | Base | 1 |
public void testSort3WithFilter() {
Filter filter = Predicates.equal("name", "quux");
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.sortOrder(
Predicates.asc("foo"),
Predicates.desc("bar"),
Predicates.asc("baz"))
.build();
} | Base | 1 |
public void testSort2() {
Filter filter = Predicates.acceptAll();
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.sortOrder(Predicates.asc("foo"), Predicates.desc("bar"))
.build();
} | Base | 1 |
public void testIsInstanceOf() {
// Create the filter
Filter filter = Predicates.isInstanceOf(LayerInfo.class);
// Build it
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.build();
String sql = build.toString();
// Ensure the following sql is present
assertThat(sql, containsString("type_id = " + dbMappings.getTypeId(LayerInfo.class)));
} | Base | 1 |
public void setUp() throws Exception {
dialect = new Dialect();
dbMappings = new DbMappings(dialect);
testSupport =
new JDBCConfigTestSupport(
(JDBCConfigTestSupport.DBConfig)
JDBCConfigTestSupport.parameterizedDBConfigs().get(0)[0]);
testSupport.setUp();
dbMappings = testSupport.getDbMappings();
} | Base | 1 |
public void testNotEquals() {
// Create the filter
Filter filter = Predicates.notEqual("name", "quux");
// Build it
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.build();
String sql = build.toString();
// Ensure the following sql is present
assertThat(
sql,
containsString(
"NOT (oid IN (SELECT oid FROM object_property WHERE property_type IN (:ptype0) AND UPPER(value) = :value0)"));
} | Base | 1 |
public void testQueryAll() {
Filter filter = Predicates.equal("name", "ws1");
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.build();
} | Base | 1 |
public void testIsNull() {
// Create the filter
Filter filter = Predicates.isNull("name");
// Build it
StringBuilder build =
QueryBuilder.forIds(dialect, WorkspaceInfo.class, dbMappings)
.filter(filter)
.build();
String sql = build.toString();
String sqlNull =
"oid IN (SELECT oid FROM object_property WHERE property_type IN (:"
+ "ptype0) AND value IS NULL) OR oid NOT IN (SELECT oid FROM object_property WHERE property_type IN (:"
+ "ptype0))";
// Ensure the following sql is present
assertThat(sql, containsString(sqlNull));
} | Base | 1 |
public Object visit(PropertyIsLike filter, Object extraData) {
char esc = filter.getEscape().charAt(0);
char multi = filter.getWildCard().charAt(0);
char single = filter.getSingleChar().charAt(0);
boolean matchCase = filter.isMatchingCase();
String literal = filter.getLiteral();
Expression att = filter.getExpression();
// JD: hack for date values, we append some additional padding to handle
// the matching of time/timezone/etc...
Class attributeType = getExpressionType(att);
// null check if returnType of expression is Object, null is returned
// from getExpressionType
if (attributeType != null && Date.class.isAssignableFrom(attributeType)) {
literal += multi;
}
String pattern = LikeFilterImpl.convertToSQL92(esc, multi, single, matchCase, literal);
try {
if (!matchCase) {
out.write(" UPPER(");
}
att.accept(this, extraData);
if (!matchCase) {
out.write(") LIKE '");
} else {
out.write(" LIKE '");
}
out.write(pattern);
out.write("' ");
} catch (java.io.IOException ioe) {
throw new RuntimeException(IO_ERROR, ioe);
}
return extraData;
} | Base | 1 |
protected void writeLiteral(Object literal) throws IOException {
if (literal == null) {
out.write("NULL");
} else if (literal instanceof Number || literal instanceof Boolean) {
out.write(String.valueOf(literal));
} else if (literal instanceof java.sql.Date || literal instanceof java.sql.Timestamp) {
// java.sql.date toString declares to always format to yyyy-mm-dd
// (and TimeStamp uses a similar approach)
out.write("'" + literal + "'");
} else if (literal instanceof java.util.Date) {
// get back to the previous case
Timestamp ts = new java.sql.Timestamp(((Date) literal).getTime());
out.write("'" + ts + "'");
} else if (literal instanceof Instant) {
java.util.Date date = ((Instant) literal).getPosition().getDate();
Timestamp ts = new java.sql.Timestamp(date.getTime());
out.write("'" + ts + "'");
} else if (literal.getClass().isArray()) {
// write as a SQL99 array
out.write("ARRAY[");
int length = Array.getLength(literal);
for (int i = 0; i < length; i++) {
writeLiteral(Array.get(literal, i));
if (i < length - 1) {
out.write(", ");
}
}
out.write("]");
} else {
// we don't know the type...just convert back to a string
String encoding = Converters.convert(literal, String.class, null);
if (encoding == null) {
// could not convert back to string, use original l value
encoding = literal.toString();
}
// sigle quotes must be escaped to have a valid sql string
String escaped = encoding.replaceAll("'", "''");
out.write("'" + escaped + "'");
}
} | Base | 1 |
public Object visit(Id filter, Object extraData) {
if (primaryKey == null) {
throw new RuntimeException("Must set primary key before trying to encode FIDFilters");
}
Set ids = filter.getIdentifiers();
LOGGER.finer("Exporting FID=" + ids);
try {
if (ids.size() > 1) {
out.write("(");
}
List<PrimaryKeyColumn> columns = primaryKey.getColumns();
for (Iterator i = ids.iterator(); i.hasNext(); ) {
Identifier id = (Identifier) i.next();
List<Object> attValues = JDBCDataStore.decodeFID(primaryKey, id.toString(), false);
out.write("(");
for (int j = 0; j < attValues.size(); j++) {
// in case of join the pk columns need to be qualified with alias
if (filter instanceof JoinId) {
out.write(escapeName(((JoinId) filter).getAlias()));
out.write(".");
}
out.write(escapeName(columns.get(j).getName()));
out.write(" = '");
out.write(
attValues.get(j).toString()); // DJB: changed this to attValues[j] from
// attValues[i].
out.write("'");
if (j < (attValues.size() - 1)) {
out.write(" AND ");
}
}
out.write(")");
if (i.hasNext()) {
out.write(" OR ");
}
}
if (ids.size() > 1) {
out.write(")");
}
} catch (java.io.IOException e) {
throw new RuntimeException(IO_ERROR, e);
}
return extraData;
} | Base | 1 |
public static String convertToSQL92(
char escape, char multi, char single, boolean matchCase, String pattern)
throws IllegalArgumentException {
if ((escape == '\'') || (multi == '\'') || (single == '\''))
throw new IllegalArgumentException("do not use single quote (') as special char!");
StringBuffer result = new StringBuffer(pattern.length() + 5);
for (int i = 0; i < pattern.length(); i++) {
char chr = pattern.charAt(i);
if (chr == escape) {
// emit the next char and skip it
if (i != (pattern.length() - 1)) result.append(pattern.charAt(i + 1)); //
i++; // skip next char
} else if (chr == single) {
result.append('_');
} else if (chr == multi) {
result.append('%');
} else if (chr == '\'') {
result.append('\'');
result.append('\'');
} else {
result.append(matchCase ? chr : Character.toUpperCase(chr));
}
}
return result.toString();
} | Base | 1 |
public String getSQL92LikePattern() throws IllegalArgumentException {
if (escape.length() != 1) {
throw new IllegalArgumentException(
"Like Pattern --> escape char should be of length exactly 1");
}
if (wildcardSingle.length() != 1) {
throw new IllegalArgumentException(
"Like Pattern --> wildcardSingle char should be of length exactly 1");
}
if (wildcardMulti.length() != 1) {
throw new IllegalArgumentException(
"Like Pattern --> wildcardMulti char should be of length exactly 1");
}
return LikeFilterImpl.convertToSQL92(
escape.charAt(0),
wildcardMulti.charAt(0),
wildcardSingle.charAt(0),
matchingCase,
pattern);
} | Base | 1 |
public void testLikeToSQL() {
Assert.assertEquals(
"BroadWay%", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "BroadWay*"));
Assert.assertEquals(
"broad#ay", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broad#ay"));
Assert.assertEquals(
"broadway", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broadway"));
Assert.assertEquals(
"broad_ay", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broad.ay"));
Assert.assertEquals(
"broad.ay", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broad!.ay"));
Assert.assertEquals(
"broa''dway", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broa'dway"));
Assert.assertEquals(
"broa''''dway",
LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broa" + "''dway"));
Assert.assertEquals(
"broadway_", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broadway."));
Assert.assertEquals(
"broadway", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broadway!"));
Assert.assertEquals(
"broadway!", LikeFilterImpl.convertToSQL92('!', '*', '.', true, "broadway!!"));
} | Base | 1 |
public FilterToSQL createFilterToSQL() {
return new MySQLFilterToSQL(delegate.getUsePreciseSpatialOps());
} | Base | 1 |
new UnWrapper() {
@Override
public Statement unwrap(Statement statement) {
throw new UnsupportedOperationException();
}
@Override
public Connection unwrap(Connection conn) {
throw new UnsupportedOperationException();
}
@Override
public boolean canUnwrap(Statement st) {
return false;
}
@Override
public boolean canUnwrap(Connection conn) {
return false;
}
}; | Base | 1 |
public String jsonExists(Function function) {
PropertyName columnName = (PropertyName) getParameter(function, 0, true);
Literal jsonPath = (Literal) getParameter(function, 1, true);
Expression expected = getParameter(function, 2, true);
String[] pointers = jsonPath.getValue().toString().split("/");
if (pointers.length > 0) {
String strJsonPath = String.join(".", pointers);
return String.format(
"json_exists(%s, '$%s?(@ == \"%s\")')",
columnName, strJsonPath, expected.evaluate(null));
} else {
throw new IllegalArgumentException(
"Cannot encode filter Invalid pointer " + jsonPath.getValue());
}
} | Base | 1 |
protected void doSDODistance(
BinarySpatialOperator filter, Expression e1, Expression e2, Object extraData)
throws IOException {
double distance = ((DistanceBufferOperator) filter).getDistance();
String unit = getSDOUnitFromOGCUnit(((DistanceBufferOperator) filter).getDistanceUnits());
String within = filter instanceof DWithin ? "TRUE" : "FALSE";
out.write("SDO_WITHIN_DISTANCE(");
e1.accept(this, extraData);
out.write(",");
e2.accept(this, extraData);
// encode the unit verbatim when available
if (unit != null && !"".equals(unit.trim()))
out.write(",'distance=" + distance + " unit=" + unit + "') = '" + within + "' ");
else out.write(",'distance=" + distance + "') = '" + within + "' ");
} | Base | 1 |
public String buildJsonFromStrPointer(String[] pointers, Expression expectedExp) {
if (!"".equals(pointers[0])) {
if (pointers.length == 1) {
final String expected =
getBaseType(expectedExp).isAssignableFrom(String.class)
? String.format(
"\"%s\"", ((Literal) expectedExp).getValue().toString())
: ((Literal) expectedExp).getValue().toString();
return String.format("\"%s\": [%s]", pointers[0], expected);
} else {
return String.format(
"\"%s\": { %s }",
pointers[0],
buildJsonFromStrPointer(
Arrays.copyOfRange(pointers, 1, pointers.length), expectedExp));
}
} else
return buildJsonFromStrPointer(
Arrays.copyOfRange(pointers, 1, pointers.length), expectedExp);
} | Base | 1 |
private void encodeJsonArrayContains(Function jsonArrayContains) throws IOException {
PropertyName column = (PropertyName) getParameter(jsonArrayContains, 0, true);
Literal jsonPath = (Literal) getParameter(jsonArrayContains, 1, true);
Expression expected = getParameter(jsonArrayContains, 2, true);
String[] strJsonPath = jsonPath.getValue().toString().split("/");
if (strJsonPath.length > 0) {
String jsonFilter =
String.format("{ %s }", buildJsonFromStrPointer(strJsonPath, expected));
out.write(
String.format(
"\"%s\"::jsonb @> '%s'::jsonb", column.getPropertyName(), jsonFilter));
} else {
throw new IllegalArgumentException(
"Cannot encode filter Invalid pointer " + jsonPath.getValue());
}
} | Base | 1 |
public void testFunctionJsonArrayContains() throws Exception {
filterToSql.setFeatureType(testSchema);
Function pointer =
ff.function(
"jsonArrayContains",
ff.property("OPERATIONS"),
ff.literal("/operations"),
ff.literal("OP1"));
filterToSql.encode(pointer);
String sql = writer.toString().trim();
assertEquals("\"OPERATIONS\"::jsonb @> '{ \"operations\": [\"OP1\"] }'::jsonb", sql);
} | Base | 1 |
public void testNestedObjectJsonArrayContains() throws Exception {
filterToSql.setFeatureType(testSchema);
Function pointer =
ff.function(
"jsonArrayContains",
ff.property("OPERATIONS"),
ff.literal("/operations/parameters"),
ff.literal("P1"));
filterToSql.encode(pointer);
String sql = writer.toString().trim();
assertEquals(
"\"OPERATIONS\"::jsonb @> '{ \"operations\": { \"parameters\": [\"P1\"] } }'::jsonb",
sql);
} | Base | 1 |
public void testFunctionJsonArrayContainsNumber() throws Exception {
filterToSql.setFeatureType(testSchema);
Function pointer =
ff.function(
"jsonArrayContains",
ff.property("OPERATIONS"),
ff.literal("/operations"),
ff.literal(1));
filterToSql.encode(pointer);
String sql = writer.toString().trim();
assertEquals("\"OPERATIONS\"::jsonb @> '{ \"operations\": [1] }'::jsonb", sql);
} | Base | 1 |
public void validate(final OidcCredentials credentials, final WebContext context) {
final AuthorizationCode code = credentials.getCode();
// if we have a code
if (code != null) {
try {
final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
// Token request
final TokenRequest request = createTokenRequest(new AuthorizationCodeGrant(code, new URI(computedCallbackUrl)));
HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());
final HTTPResponse httpResponse = tokenHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(),
httpResponse.getContent());
final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
if (response instanceof TokenErrorResponse) {
throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
}
logger.debug("Token response successful");
final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
// save tokens in credentials
final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
credentials.setAccessToken(oidcTokens.getAccessToken());
credentials.setRefreshToken(oidcTokens.getRefreshToken());
credentials.setIdToken(oidcTokens.getIDToken());
} catch (final URISyntaxException | IOException | ParseException e) {
throw new TechnicalException(e);
}
}
} | Base | 1 |
private boolean isImage(MultipartFile file) {
BufferedImage image = null;
try (InputStream input = file.getInputStream()) {
image = ImageIO.read(input);
} catch (IOException e) {
LogUtil.error(e.getMessage(), e);
return false;
}
if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
return false;
}
return true;
} | Base | 1 |
public void backup(File targetDir, DataSource dataSource, DbProperties dbProperties) throws InterruptedException, TimeoutException, IOException {
ProcessResult processResult = createProcessExecutor(targetDir, dbProperties).execute();
if (processResult.getExitValue() == 0) {
log.info("MySQL backup finished successfully.");
} else {
log.warn("There was an error backing up the database using `mysqldump`. The `mysqldump` process exited with status code {}.", processResult.getExitValue());
throw new RuntimeException("There was an error backing up the database using `mysqldump`. The `mysqldump` process exited with status code " + processResult.getExitValue() +
". Please see the server logs for more errors");
}
} | Base | 1 |
private ProcessExecutor createProcessExecutor(File targetDir, DbProperties dbProperties) {
ConnectionUrl connectionUrlInstance = ConnectionUrl.getConnectionUrlInstance(dbProperties.url(), dbProperties.connectionProperties());
LinkedHashMap<String, String> env = new LinkedHashMap<>();
if (isNotBlank(dbProperties.password())) {
env.put("MYSQL_PWD", dbProperties.password());
}
// override with any user specified environment
env.putAll(dbProperties.extraBackupEnv());
ArrayList<String> argv = new ArrayList<>();
argv.add("mysqldump");
String dbName = connectionUrlInstance.getDatabase();
HostInfo mainHost = connectionUrlInstance.getMainHost();
if (mainHost != null) {
argv.add("--host=" + mainHost.getHost());
argv.add("--port=" + mainHost.getPort());
}
if (isNotBlank(dbProperties.user())) {
argv.add("--user=" + dbProperties.user());
}
// append any user specified args for mysqldump
if (isNotBlank(dbProperties.extraBackupCommandArgs())) {
Collections.addAll(argv, Commandline.translateCommandline(dbProperties.extraBackupCommandArgs()));
}
argv.add("--result-file=" + new File(targetDir, "db." + dbName).toString());
argv.add(connectionUrlInstance.getDatabase());
ProcessExecutor processExecutor = new ProcessExecutor();
processExecutor.redirectOutputAlsoTo(Slf4jStream.of(getClass()).asDebug());
processExecutor.redirectErrorAlsoTo(Slf4jStream.of(getClass()).asDebug());
processExecutor.environment(env);
processExecutor.command(argv);
return processExecutor;
} | Base | 1 |
public void backup(File targetDir, DataSource dataSource, DbProperties dbProperties) throws Exception {
ProcessResult processResult = createProcessExecutor(targetDir, dbProperties).execute();
if (processResult.getExitValue() == 0) {
log.info("PostgreSQL backup finished successfully.");
} else {
log.warn("There was an error backing up the database using `pg_dump`. The `pg_dump` process exited with status code {}.", processResult.getExitValue());
throw new RuntimeException("There was an error backing up the database using `pg_dump`. The `pg_dump` process exited with status code " + processResult.getExitValue() +
". Please see the server logs for more errors.");
}
} | Base | 1 |
ProcessExecutor createProcessExecutor(File targetDir, DbProperties dbProperties) {
Properties connectionProperties = dbProperties.connectionProperties();
Properties pgProperties = Driver.parseURL(dbProperties.url(), connectionProperties);
ArrayList<String> argv = new ArrayList<>();
LinkedHashMap<String, String> env = new LinkedHashMap<>();
if (isNotBlank(dbProperties.password())) {
env.put("PGPASSWORD", dbProperties.password());
}
// override with any user specified environment
env.putAll(dbProperties.extraBackupEnv());
String dbName = pgProperties.getProperty("PGDBNAME");
argv.add("pg_dump");
argv.add("--host=" + pgProperties.getProperty("PGHOST"));
argv.add("--port=" + pgProperties.getProperty("PGPORT"));
argv.add("--dbname=" + dbName);
if (isNotBlank(dbProperties.user())) {
argv.add("--username=" + dbProperties.user());
}
argv.add("--no-password");
// append any user specified args for pg_dump
if (isNotBlank(dbProperties.extraBackupCommandArgs())) {
Collections.addAll(argv, Commandline.translateCommandline(dbProperties.extraBackupCommandArgs()));
}
argv.add("--file=" + new File(targetDir, "db." + dbName));
ProcessExecutor processExecutor = new ProcessExecutor();
processExecutor.redirectOutputAlsoTo(Slf4jStream.of(getClass()).asDebug());
processExecutor.redirectErrorAlsoTo(Slf4jStream.of(getClass()).asDebug());
processExecutor.environment(env);
processExecutor.command(argv);
return processExecutor;
} | Base | 1 |
public void visit(Modification modification) {
modifiedFilesJson = new ArrayList();
Map<String, Object> jsonMap = new LinkedHashMap<>();
jsonMap.put("user", modification.getUserDisplayName());
jsonMap.put("revision", modification.getRevision());
jsonMap.put("date", formatISO8601(modification.getModifiedTime()));
String comment = modification.getComment();
if (!revision.getMaterial().getMaterialType().equals(TYPE)) {
comment = commentRenderer.render(comment);
}
jsonMap.put("comment", comment);
jsonMap.put("modifiedFiles", modifiedFilesJson);
modificationsJson.add(jsonMap);
} | Base | 1 |
public void visit(MaterialRevision revision) {
this.revision = revision;
modificationsJson = new ArrayList();
materialJson = new LinkedHashMap();
materialJson.put("revision", revision.getRevision().getRevision());
materialJson.put("revision_href", revision.getRevision().getRevisionUrl());
materialJson.put("user", revision.buildCausedBy());
materialJson.put("date", formatISO8601(revision.getDateOfLatestModification()));
materialJson.put("changed", valueOf(revision.isChanged()));
materialJson.put("modifications", modificationsJson);
materials.add(materialJson);
} | Base | 1 |
public List json() {
return materials;
} | Base | 1 |
private Map<String, Object> createJobDetailModel() {
GitMaterialConfig gitMaterialConfig = gitMaterialConfig();
MaterialRevisions materialRevisions = new MaterialRevisions();
materialRevisions.addRevision(new GitMaterial(gitMaterialConfig),
new Modification("Ernest Hemingway <oldman@sea.com>", "comment", "email", new Date(), "12", ""));
Pipeline pipeline = schedule(pipelineConfig("pipeline", new MaterialConfigs(gitMaterialConfig)), createWithModifications(materialRevisions, ""));
JobDetailPresentationModel model = new JobDetailPresentationModel(building("job"), new JobInstances(), null,
pipeline, new Tabs(), new TrackingTool(),
mock(ArtifactsService.class), StageMother.custom("stage"));
return minimalModelFrom(model);
} | Base | 1 |
public void setUp() throws Exception {
super.setUp("build_detail/build_detail_page.ftl");
} | Base | 1 |
public void shouldRenderIframeSandboxForTestsTab() {
JobDetailPresentationModel jobDetailPresentationModel = mock(JobDetailPresentationModel.class, RETURNS_SMART_NULLS);
when(jobDetailPresentationModel.hasTests()).thenReturn(true);
when(jobDetailPresentationModel.getCustomizedTabs()).thenReturn(new Tabs());
Document actualDoc = Jsoup.parse(view.render(minimalModelFrom(jobDetailPresentationModel)));
assertThat(actualDoc.select("#tab-content-of-tests").last().html(), containsString("<iframe sandbox=\"allow-scripts\""));
} | Base | 1 |
public void shouldEscapeBuildCauseInTrimPathTemplate() {
Document actualDoc = Jsoup.parse(view.render(createJobDetailModel()));
assertThat(actualDoc.select("#build-summary-template").last().html(), containsString("modified by Ernest Hemingway &lt;oldman@sea.com&gt;"));
} | Base | 1 |
public void shouldEscapeBuildCauseOnVelocityTemplate() {
Document actualDoc = Jsoup.parse(view.render(createJobDetailModel()));
assertThat(actualDoc.select("#build-detail-summary").last().html(), containsString("modified by Ernest Hemingway <oldman@sea.com>"));
} | Base | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.