sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function create(array $paths) { $standards = new Standards(); foreach ($paths as $path) { $standards->addStandard($this->standardFactory->create($path)); } return $standards; }
Creates PHPCodeSniffer standards from paths. @param array $paths Paths with PHPCodeSniffer standard paths. @return Standards PHPCodeSniffer standards object.
entailment
public function compiler() { static $engineResolver; if (!$engineResolver) { $engineResolver = $this->getContainer()->make('view.engine.resolver'); } return $engineResolver->resolve('blade')->getCompiler(); }
Get the compiler @return \Illuminate\View\Compilers\BladeCompiler
entailment
public function applyNamespaceToPath($path) { /** @var ViewFinderInterface $finder */ $finder = $this->getContainer()['view.finder']; if (!method_exists($finder, 'getHints')) { return $path; } $delimiter = $finder::HINT_PATH_DELIMITER; $hints = $finder->getHints(); $view = array_reduce(array_keys($hints), function ($view, $namespace) use ($delimiter, $hints) { return str_replace($hints[$namespace], $namespace.$delimiter, $view); }, $path); return preg_replace("%{$delimiter}[\\/]*%", $delimiter, $view); }
Convert path to view namespace @param string $path @return string
entailment
public function removeStandard($standard) { if ($this->hasStandard($standard)) { unset($this->standards[$this->getStandardName($standard)]); } return $this; }
Remove a single standard from the set. @param string|StandardInterface $standard The standard to remove @return $this Fluent interface
entailment
public function getStandard($standard) { if (! $this->hasStandard($standard)) { return null; } return $this->standards[$this->getStandardName($standard)]; }
Get a single standard. @param string|StandardInterface $standard The standard to get @return StandardInterface|null Return the standard or null if not exist
entailment
public function setStandards(array $standards) { $this->standards = []; foreach ($standards as $standard) { $this->addStandard($standard); } return $this; }
Set standards hold by this set. @param StandardInterface[] $standards Array with standards to set @return $this Fluent interface
entailment
public function key() { $key = key($this->standards); return array_search($key, array_keys($this->standards)); }
Return the key of the current element @link http://php.net/manual/en/iterator.key.php @return mixed scalar on success, or null on failure. @since 5.0.0
entailment
private function escapeArgs(&$args) { $escaped = array(); foreach ($args as $arg) { $escaped[] = escapeshellarg($arg); } return $escaped; }
Escape given argument array @param array $args @return array Escaped arguments
entailment
protected function readStream(&$stream, &$output) { $content = stream_get_contents($stream); if (strlen(rtrim($content))) { foreach (preg_split('/\r?\n/', $content) as $line) { $output[] = $line; } } }
Read stream content to output array @param resource $stream Stream resource @param array $output
entailment
public function read($key, $default = null) { if ($this->data === null) { $this->readFile(); } if (isset($this->data[$key])) { return $this->data[$key]; } else { return $default; } }
Read given @param string $key Cache key @param mixed $default Cache value @return mixed Cache value
entailment
protected function faststart($src) { if (!$this->config['qt-faststart.bin']) { return 0; } $output = array(); $dst = $src . '.mp4'; $result = $this->Process->run($this->config['qt-faststart.bin'], array($src, $dst), $output); if ($result == 0) { unlink($src); rename($dst, $src); } return $result; }
Move mp4 meta data to the front to support streaming @param string $src Filename of mp4 @return int Result. 0 for success
entailment
public function in($path) { $finder = $this->getSymfonyFinder() ->in($path) ->files() ->name('ruleset.xml') ->sortByName(); $paths = iterator_to_array($finder, false); $paths = array_map( function (\SplFileInfo $file) { return $file->getPath(); }, $paths ); return $this->createStandardsFromPaths($paths); }
Find and return PHPCodeSniffer standards. @param string $path @return Standards @SuppressWarnings(PHPMD.ShortMethodName)
entailment
public function register() { $this->registerFilesystem(); $this->registerEvents(); $this->registerEngineResolver(); $this->registerViewFinder(); $this->registerFactory(); return $this; }
Bind required instances for the service provider.
entailment
public function registerViewFinder() { $this->app->bindIf('view.finder', function ($app) { $config = $this->app['config']; $paths = $config['view.paths']; $namespaces = $config['view.namespaces']; $finder = new FileViewFinder($app['files'], $paths); array_map([$finder, 'addNamespace'], array_keys($namespaces), $namespaces); return $finder; }, true); return $this; }
Register the view finder implementation.
entailment
protected function parseEncoder($lines) { $encoders = array(); foreach ($lines as $line) { if (preg_match('/^\s+([A-Z .]+)\s+(\w{2,})\s+(.*)$/', $line, $m)) { $type = trim($m[1]); if (strpos($type, 'E') !== false) { $encoder = trim($m[2]); if (strpos($encoder, ',') !== false) { foreach (split(',', $encoder) as $e) { $encoders[] = $e; } } else { $encoders[] = $encoder; } } } } sort($encoders); return $encoders; }
Extract encoder names from output lines @param array $lines ffmpeg output lines @return array List of supported encoders
entailment
protected function parseInfo($lines) { $result = array('videoStreams' => 0, 'audioStreams' => 0); foreach ($lines as $line) { if (preg_match('/Duration:\s+(\d\d):(\d\d):(\d\d\.\d+)/', $line, $m)) { $result['duration'] = $m[1] * 3600 + $m[2] * 60 + $m[3]; } else if (preg_match('/\s+Stream #(\d)+.*$/', $line, $sm)) { if (strpos($line, 'Video:')) { $result['videoStreams']++; $words = preg_split('/,?\s+/', trim($line)); for ($i = 0; $i < count($words); $i++) { if (preg_match('/(\d+)x(\d+)/', $words[$i], $m)) { $result['width'] = $m[1]; $result['height'] = $m[2]; } } } else if (strpos($line, 'Audio:')) { $result['audioStreams']++; } } } return $result; }
Parse streaming informations @param array $lines @return array
entailment
protected function isVersionIsGreaterOrEqual($version, $other) { $max = min(count($version), count($other)); for ($i = 0; $i < $max; $i++) { if ($version[$i] < $other[$i]) { return false; } } return true; }
Compare two versions @param array $version Version array @param array $other Version array @return boolean True if first version is greater or equal to other version
entailment
protected function searchEncoder($needle) { if (is_array($needle)) { foreach ($needle as $n) { $result = $this->searchEncoder($n); if ($result) { return $result; } } return false; } $encoders = $this->getEncoders(); foreach ($encoders as $encoder) { if (strpos($encoder, $needle) !== false) { return $encoder; } } return false; }
Search for matching encoder @param string|array $needle Encoder type @return mixed
entailment
protected function getDriver() { $version = $this->getVersion(); if ($this->isVersionIsGreaterOrEqual($version, array(0, 11, 0))) { return new Driver\FfmpegDriver(); } else if ($this->isVersionIsGreaterOrEqual($version, array(0, 9, 0))) { return new Driver\FfmpegDriver10(); } else if ($this->isVersionIsGreaterOrEqual($version, array(0, 8, 0))) { return new Driver\FfmpegDriver08(); } else { return new Driver\FfmpegDriver06(); } }
Get current ffmpeg driver @return object FfmpegDriver
entailment
protected function createConverter($targetFormat, $profileName) { $profile = $this->getProfile($profileName); $videoContainers = $this->config['videoContainers']; if (!isset($videoContainers[$targetFormat])) { throw new \Exception("Unsupported target video container"); } $targetConfig = $videoContainers[$targetFormat]; if (!isset($targetConfig['videoEncoder']) || !isset($targetConfig['audioEncoder'])) { throw new \Exception("Video or audio encoder are missing for target format $targetFormat"); } $videoEncoder = $this->searchEncoder($targetConfig['videoEncoder']); if (!$videoEncoder) { throw new \Exception("Video encoder not found for video codec {$targetConfig['videoEncoder']} for $targetFormat"); } $audioEncoder = $this->searchEncoder($targetConfig['audioEncoder']); if (!$audioEncoder) { throw new \Exception("Audio encoder not found for audio codec {$targetConfig['audioEncoder']} for $targetFormat"); } if ($targetFormat == 'mp4') { return new Converter\Mp4Converter($this->Process, $this->getDriver(), $this->config, $profile, $videoEncoder, $audioEncoder); } return new Converter\GenericConverter($this->Process, $this->getDriver(), $this->config, $profile, $videoEncoder, $audioEncoder); }
Create a video convert for given profile and target container @param string $targetFormat Target container format @param string $profileName Profile name @return \Html5Video\Converter\Mp4Converter|\Html5Video\Converter\GenericConverter @throws \Exception
entailment
protected function mergeOptions($src, $dst, &$options) { if (!isset($options['width']) && !isset($options['height'])) { $info = $this->getVideoInfo($src); $options['width'] = $info['width']; $options['height'] = $info['height']; if (!$info['audioStreams']) { $options['audio'] = false; } } if (!isset($options['targetFormat'])) { $ext = strtolower(substr($dst, strrpos($dst, '.') + 1)); $options['targetFormat'] = $ext; } }
If no width and height are given in the option read the video file and set width and height from the souce @param string $src Source video filename @param string $dst Desitination video filename @param array $options Convert options
entailment
public function getVersion() { $version = $this->Cache->read('version', null); if ($version !== null) { return $version; } $version = array(2, 0, 0); $lines = array(); $result = $this->Process->run($this->config['ffmpeg.bin'], array('-version'), $lines); if ($result == 0 && $lines && preg_match('/^\w+\s(version\s)?(\d+)\.(\d+)\.(\d+).*/', $lines[0], $m)) { $version = array($m[2], $m[3], $m[4]); } else if ($result == 0 && $lines && preg_match('/^\w+\s(version\s)?\S*N-(\d+)-.*/', $lines[0], $m)) { $winVersion = $m[2]; if ($winVersion <= 30610) { $version = array(0, 6, 0); } else if ($winVersion <= 30956) { $version = array(0, 7, 0); } else if ($winVersion <= 48409) { $version = array(0, 8, 0); } else if ($winVersion <= 48610) { $version = array(1, 0, 1); } else if ($winVersion <= 49044) { $version = array(1, 1, 0); } else { $version = array(2, 0, 0); } } $this->Cache->write('version', $version); return $version; }
Get current version of ffmpeg @return array Version array(major, minor, patch)
entailment
public function getEncoders() { $encoders = $this->Cache->read('encoders'); if ($encoders !== null) { return $encoders; } $args = array('-codecs'); if (!$this->isVersionIsGreaterOrEqual($this->getVersion(), array(0, 8))) { $args = array('-formats'); } $lines = array(); $errCode = $this->Process->run($this->config['ffmpeg.bin'], $args, $lines); if (!count($lines) || $errCode != 0) { return array(); } $encoders = $this->parseEncoder($lines); $this->Cache->write('encoders', $encoders); return $encoders; }
Get supported encoder names @return array Sorted list of supported encoders
entailment
public function getProfile($name) { $dirs = $this->config['profile.dirs']; foreach ($dirs as $dir) { if (!is_dir($dir) || !is_readable($dir)) { continue; } $filename = $dir . DIRECTORY_SEPARATOR . $name . '.profile'; if (is_readable($filename)) { $content = file_get_contents($filename); $json = json_decode($content); return $json; } } throw new \Exception("Profile $name not found"); }
Read the video profile in given profile directories @param string $name Profile name @return object Profile @throws Exception
entailment
public function listProfiles() { $dirs = $this->config['profile.dirs']; $profiles = array(); foreach ($dirs as $dir) { if (!is_dir($dir) || !is_readable($dir)) { continue; } $files = scandir($dir); foreach ($files as $file) { if (preg_match('/(.*)\.profile$/', $file, $m)) { $profiles[] = $m[1]; } } } return $profiles; }
List all available profiles @return array List of available profiles
entailment
public function getVideoInfo($src) { $lines = array(); if (!is_readable($src)) { throw new \Exception("Source file '$src' is not readable"); } $this->Process->run($this->config['ffmpeg.bin'], array('-i', $src), $lines); if (count($lines)) { return $this->parseInfo($lines); } return false; }
Get information about a video file @param string $src Video filename @return mixed False on error
entailment
public function convert($src, $dst, $profileName, $options = array()) { $this->setTimeLimit(); $this->mergeOptions($src, $dst, $options); $converter = $this->createConverter($options['targetFormat'], $profileName); $result = $converter->create($src, $dst, $options); return $result; }
Convert a given video to html5 video @param string $src Source filename @param string $dst Destination filename @param string $profileName Profile name @param array $options Additional options - targetFormat: target container format. Default extension of $dst - width: Width of source video - height: Height of source video - audio: true | false @return mixed
entailment
public function getPossibleViewFiles($name) { $parts = explode(self::FALLBACK_PARTS_DELIMITER, $name); $templates[] = array_shift($parts); foreach ($parts as $i => $part) { $templates[] = $templates[$i].self::FALLBACK_PARTS_DELIMITER.$part; } rsort($templates); return $this->getPossibleViewFilesFromTemplates($templates); }
Get an array of possible view files from a single file name. @param string $name @return array
entailment
public function getPossibleViewFilesFromTemplates($templates) { return call_user_func_array('array_merge', array_map(function ($template) { return array_map(function ($extension) use ($template) { return str_replace('.', '/', $template).'.'.$extension; }, $this->extensions); }, $templates)); }
Get an array of possible view files from an array of templates @param array $templates @return array
entailment
protected function getNameFromRuleSet($ruleSetXmlPath) { try { $ruleSet = new \SimpleXMLElement(file_get_contents($ruleSetXmlPath)); $name = trim($ruleSet->attributes()['name']); if ($name !== '') { return $name; } } catch (\Exception $e) { // Nothing todo, use folder name. } return basename(dirname($ruleSetXmlPath)); }
Fetch PHPCodeSniffer standard name from ruleset.xml. @param string $ruleSetXmlPath The absolute path to ruleset.xml. @return string The name of the PHPCodeSniffer standard.
entailment
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { if (! parent::isInstalled($repo, $package)) { return false; } $srcStandards = $this->getSourceStandards($package); $dstStandards = $this->getDestinationStandards($repo); foreach ($srcStandards as $srcStandard) { if (! $dstStandards->hasStandard($srcStandard) || ! $this->compareStandards($srcStandard, $dstStandards->getStandard($srcStandard)) ) { return false; } } return true; }
{@inheritDoc}
entailment
public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { parent::install($repo, $package); $this->installStandards($repo, $package); }
{@inheritDoc}
entailment
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) { parent::update($repo, $initial, $target); $this->installStandards($repo, $target, $initial ? false : true); }
{@inheritDoc}
entailment
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { if (! $repo->hasPackage($package)) { throw new \InvalidArgumentException('Package is not installed: ' . $package); } $this->removeStandards($repo, $package); parent::uninstall($repo, $package); }
{@inheritDoc}
entailment
protected function installStandards( InstalledRepositoryInterface $repo, PackageInterface $package, $override = false ) { $filesystem = new SymfonyFilesystem(); $srcStandards = $this->getSourceStandards($package); $dstStdBasePath = $this->getPHPCodeSnifferStandardsBasePath($repo); $this->io->writeError(' Installing PHP-CodeSniffer Standards:', false); foreach ($srcStandards as $srcStandard) { $this->io->writeError(sprintf(' <info>%s</info>', $srcStandard->getName())); $srcPath = $srcStandard->getPath(); $dstPath = $dstStdBasePath . DIRECTORY_SEPARATOR . $srcStandard->getName(); $filesystem->mirror($srcPath, $dstPath, null, ['override' => $override]); } }
@param InstalledRepositoryInterface $repo @param PackageInterface $package @param bool $override @return void @SuppressWarnings(PHPMD.BooleanArgumentFlag)
entailment
protected function removeStandards(InstalledRepositoryInterface $repo, PackageInterface $package) { $srcStandards = $this->getSourceStandards($package); $dstStandards = $this->getDestinationStandards($repo); $this->io->writeError(' Removing PHP-CodeSniffer Standards:', false); foreach ($srcStandards as $srcStandard) { if (! $dstStandards->hasStandard($srcStandard)) { continue; } $this->io->writeError(sprintf(' <info>%s</info>', $srcStandard->getName())); $dstStandard = $dstStandards->getStandard($srcStandard); $this->filesystem->removeDirectory($dstStandard->getPath()); } }
@param InstalledRepositoryInterface $repo @param PackageInterface $package @return void
entailment
protected function getSourceStandards(PackageInterface $package) { $basePath = $this->getInstallPath($package); return $this->findStandards($basePath); }
Get source (provided by the composer package) standards for package. @param PackageInterface $package @return Standards
entailment
protected function getDestinationStandards(InstalledRepositoryInterface $repo) { $basePath = $this->getPHPCodeSnifferInstallPath($repo); return $this->findStandards($basePath); }
Get destination (provided by PHPCodeSniffer) standards. @param InstalledRepositoryInterface $repo @return Standards
entailment
protected function compareStandards(Standard $source, Standard $destination) { return $source->getName() === $destination->getName() && sha1_file($source->getRuleSetXmlPath()) === sha1_file($destination->getRuleSetXmlPath()); }
@param Standard $source @param Standard $destination @return bool
entailment
protected function getPHPCodeSnifferStandardsBasePath(InstalledRepositoryInterface $repo) { $package = $this->getPHPCodeSnifferPackage($repo); $basePath = $this->getInstallPath($package); return $basePath . DIRECTORY_SEPARATOR . 'CodeSniffer' . DIRECTORY_SEPARATOR . 'Standards'; }
@param InstalledRepositoryInterface $repo @return string
entailment
protected function getPHPCodeSnifferPackage(InstalledRepositoryInterface $repo) { $packageKey = 'squizlabs/php_codesniffer'; $package = $repo->findPackage($packageKey, '*'); if (! $package) { throw new \RuntimeException(sprintf('Package "%s" not installed.', $packageKey)); } return $package; }
@param InstalledRepositoryInterface $repo @return PackageInterface
entailment
public function supports($packageType) { $secondaryTypes = ['phpcodesniffer-standards']; $deprecatedTypes = ['php-codesniffer-standards']; return parent::supports($packageType) || in_array($packageType, array_merge($secondaryTypes, $deprecatedTypes)); }
{@inheritDoc}
entailment
public function categoriesAdd(Request $request, Response $response) { if ($check = $this->sentinel->hasPerm('blog_categories.create', 'dashboard', $this->config['blog-enabled'])) { return $check; } if ($request->isPost()) { $this->validator->validate($request, [ 'category_name' => V::length(2, 25)->alpha('\''), 'category_slug' => V::slug() ]); $checkSlug = BC::where('slug', '=', $request->getParam('category_slug'))->get()->count(); if ($checkSlug > 0) { $this->validator->addError('category_slug', 'Slug already in use.'); } if ($this->validator->isValid()) { $addCategory = new BC; $addCategory->name = $request->getParam('category_name'); $addCategory->slug = $request->getParam('category_slug'); if ($addCategory->save()) { $this->flash('success', 'Category added successfully.'); return $this->redirect($response, 'admin-blog'); } } $this->flash('danger', 'An error occured while adding this category.'); } return $this->redirect($response, 'admin-blog'); }
Add New Blog Category
entailment
public function categoriesDelete(Request $request, Response $response) { if ($check = $this->sentinel->hasPerm('blog_categories.delete', 'dashboard', $this->config['blog-enabled'])) { return $check; } $category = BC::find($request->getParam('category_id')); if (!$category) { $this->flash('danger', 'Category doesn\'t exist.'); return $this->redirect($response, 'admin-blog'); } if ($category->delete()) { $this->flash('success', 'Category has been removed.'); return $this->redirect($response, 'admin-blog'); } $this->flash('danger', 'There was a problem removing the category.'); return $this->redirect($response, 'admin-blog'); }
Delete Blog Category
entailment
public function categoriesEdit(Request $request, Response $response, $categoryId) { if ($check = $this->sentinel->hasPerm('blog_categories.update', 'dashboard', $this->config['blog-enabled'])) { return $check; } $category = BC::find($categoryId); if (!$category) { $this->flash('danger', 'Sorry, that category was not found.'); return $response->withRedirect($this->router->pathFor('admin-blog')); } if ($request->isPost()) { // Get Vars $categoryName = $request->getParam('category_name'); $categorySlug = $request->getParam('category_slug'); // Validate Data $validateData = array( 'category_name' => array( 'rules' => V::length(2, 25)->alpha('\''), 'messages' => array( 'length' => 'Must be between 2 and 25 characters.', 'alpha' => 'Letters only and can contain \'' ) ), 'category_slug' => array( 'rules' => V::slug(), 'messages' => array( 'slug' => 'May only contain lowercase letters, numbers and hyphens.' ) ) ); $this->validator->validate($request, $validateData); // Validate Category Slug $checkSlug = $category->where('id', '!=', $category->id) ->where('slug', '=', $categorySlug) ->get() ->count(); if ($checkSlug > 0 && $categorySlug != $category->slug) { $this->validator->addError('category_slug', 'Category slug is already in use.'); } if ($this->validator->isValid()) { if ($category->id == 1) { $this->flash('danger', 'Cannot edit uncategorized category.'); return $this->redirect($response, 'admin-blog'); } $category->name = $categoryName; $category->slug = $categorySlug; if ($category->save()) { $this->flash('success', 'Category has been updated successfully.'); return $this->redirect($response, 'admin-blog'); } } $this->flash('danger', 'An error occured updating the category.'); } return $this->view->render($response, 'blog-categories-edit.twig', ['category' => $category]); }
Edit Blog Category
entailment
public function WriteUserSpace($startpos = 1, $valuelen, $value) { //Size ($comment, $varName = '', $labelFindLen = null) { $params[] = Toolkit::AddParameterChar ('in', 20, "User space name and lib", 'usfullname', $this->getUSFullName()); $params[] = Toolkit::AddParameterInt32('in', "Starting position",'pos_from', $startpos); $params[] = Toolkit::AddParameterInt32('in', "Length of data", 'dataLen', $valuelen); $params[] = Toolkit::AddParameterChar('in', $valuelen, "Input data", 'data_value', $value); $params[] = Toolkit::AddParameterChar('in', 1, "Force changes to auxiliary storage", 'aux_storage', '0'); $params[] = Toolkit::AddErrorDataStruct(); $retPgmArr = $this->ToolkitSrvObj->PgmCall('QUSCHGUS', 'QSYS', $params); if ($this->ToolkitSrvObj->verify_CPFError($retPgmArr , "Write into User Space failed. Error:")) { return false; } return true; }
@todo write binary data? @param int $startpos @param $valuelen @param $value @return bool
entailment
public function WriteUserSpaceCw($startPos = 1, ProgramParameter $param) { /* if (!is_object($param) && !is_array($param)) { throw new \Exception('Parameter passed to WriteUserSpaceCw must be an array or ProgramParameter object.'); } */ // @todo any error, write to toolkit log. $labelForSizeOfInputData = 'dssize'; $param->setParamLabelLen($labelForSizeOfInputData); //Size ($comment, $varName = '', $labelFindLen = null) { $params[] = Toolkit::AddParameterChar('in', 20,"User space name and lib", 'usfullname', $this->getUSFullName()); $params[] = Toolkit::AddParameterInt32('in', "Starting position", 'pos_from', $startPos); $params[] = Toolkit::AddParameterSize("Length of data",'dataLen', $labelForSizeOfInputData); $params[] = $param; $params[] = Toolkit::AddParameterChar('in', 1, "Force changes to auxiliary storage", 'aux_storage', '0'); $params[] = Toolkit::AddErrorDataStruct(); $retPgmArr = $this->ToolkitSrvObj->PgmCall('QUSCHGUS', 'QSYS', $params); if ($this->ToolkitSrvObj->getErrorCode()) { return false; } else { return true; } }
CW version. $param must be an array of ProgramParameter objects or a single ProgramParameter object. @param int $startPos @param ProgramParameter $param @return bool
entailment
public function ReadUserSpace($frompos=1, $readlen = 0, $receiveStructure = null) { //how to see via green screen DSPF STMF('/QSYS.lib/qgpl.lib/ZS14371311.usrspc') $dataRead = ' '; $params[] = Toolkit::AddParameterChar('in', 20, "User space name and library", 'userspacename', $this->getUSFullName()); $params[] = Toolkit::AddParameterInt32('in', "From position", 'position_from', $frompos); $receiverVarName = 'receiverdata'; if ($receiveStructure) { // must be a ProgramParameter if (!is_object($receiveStructure)) { throw new \Exception('Parameter 3 passed to ReadUserSpace must be a ProgramParameter object.'); } $labelForSizeOfInputData = 'dssize'; // $params[] = Toolkit::AddParameterSize("Length of data", 'dataLen', $labelForSizeOfInputData); // wrap simple ds around receive structure so we can assign a varname to retrieve later. $receiveDs[] = $receiveStructure; $params[] = Toolkit::AddDataStruct($receiveDs, $receiverVarName, 0, '', false, $labelForSizeOfInputData); } else { // regular readlen, no special structure or size labels. $params[] = Toolkit::AddParameterInt32('in', "Size of data", 'datasize', $readlen); $params[] = Toolkit::AddParameterChar('out', $readlen, $receiverVarName, $receiverVarName, $receiveStructure); } $params[] = Toolkit::AddErrorDataStruct(); $retPgmArr = $this->ToolkitSrvObj->PgmCall('QUSRTVUS', 'QSYS', $params); if ($this->ToolkitSrvObj->verify_CPFError($retPgmArr , "Read user space failed. Error:")) return false; $retArr = $retPgmArr['io_param']; // return our receiverstructure. return $retArr[$receiverVarName]; }
if receiveDescription given, readlen = 0 @param int $frompos @param int $readlen @param null $receiveStructure @return bool @throws \Exception
entailment
public function getUSFullName() { if ($this->USName != null) { return sprintf("%-10s%-10s", $this->USName, $this->USlib); } return NULL; }
Name and Library @return null|string
entailment
public function blog(Request $request, Response $response) { // Get Page Number $page = 1; $routeArgs = $request->getAttribute('route')->getArguments(); if (isset($routeArgs['page']) && is_numeric($routeArgs['page'])) { $page = $routeArgs['page']; } $posts = BlogPosts::where('status', 1) ->where('publish_at', '<', Carbon::now()) ->with('category', 'tags', 'author') ->withCount('comments', 'pendingComments') ->orderBy('publish_at', 'DESC'); $pagination = new Paginator($posts->count(), $this->config['blog-per-page'], $page, "/blog/(:num)"); $pagination = $pagination; $posts = $posts->skip($this->config['blog-per-page']*($page-1)) ->take($this->config['blog-per-page']); return $this->view->render( $response, 'blog.twig', array("posts" => $posts->get(), "pagination" => $pagination) ); }
Main Blog Page
entailment
public function blogAuthor(Request $request, Response $response) { $routeArgs = $request->getAttribute('route')->getArguments(); $checkAuthor = Users::where('username', $routeArgs['username'])->first(); if (!$checkAuthor) { $this->flash('warning', 'Author not found.'); return $this->redirect($response, 'blog'); } // Get/Set Page Number $page = 1; if (isset($routeArgs['page']) && is_numeric($routeArgs['page'])) { $page = $routeArgs['page']; } $posts = BlogPosts::where('status', 1) ->where('user_id', $checkAuthor->id) ->where('publish_at', '<', Carbon::now()) ->with('category', 'tags', 'author') ->withCount('comments', 'pendingComments') ->orderBy('publish_at', 'DESC'); $pagination = new Paginator( $posts->count(), $this->config['blog-per-page'], $page, "/blog/author/".$checkAuthor->username."/(:num)" ); $pagination = $pagination; $posts = $posts->skip($this->config['blog-per-page']*($page-1)) ->take($this->config['blog-per-page']); return $this->view->render( $response, 'blog.twig', array( "author" => $checkAuthor, "posts" => $posts->get(), "pagination" => $pagination, "authorPage" => true ) ); }
Author Posts Page
entailment
public function blogCategory(Request $request, Response $response) { $routeArgs = $request->getAttribute('route')->getArguments(); $checkCat = BlogCategories::where('slug', $routeArgs['slug'])->first(); if (!$checkCat) { $this->flash('warning', 'Tag not found.'); return $this->redirect($response, 'blog'); } // Get/Set Page Number $page = 1; if (isset($routeArgs['page']) && is_numeric($routeArgs['page'])) { $page = $routeArgs['page']; } $posts = BlogCategories::withCount(['posts' => function ($query) { $query->where('status', 1) ->where('publish_at', '<', Carbon::now()); }]) ->with(['posts' => function ($query) use ($page) { $query->where('status', 1) ->where('publish_at', '<', Carbon::now()) ->with('category', 'tags', 'author') ->withCount('comments', 'pendingComments') ->skip($this->config['blog-per-page']*($page-1)) ->take($this->config['blog-per-page']) ->orderBy('publish_at', 'DESC'); }]) ->find($checkCat->id); $pagination = new Paginator( $posts->posts_count, $this->config['blog-per-page'], $page, "/blog/category/".$checkCat->slug."/(:num)" ); $pagination = $pagination; return $this->view->render( $response, 'blog.twig', array( "category" => $checkCat, "posts" => $posts->posts, "pagination" => $pagination, "categoryPage" => true ) ); }
Category Posts Page
entailment
public function blogPost(Request $request, Response $response) { $args = $request->getAttribute('route')->getArguments(); $post = BlogPosts::with( 'tags', 'category', 'author', 'author.profile', 'approvedComments', 'approvedComments.approvedReplies' ) ->where('slug', $args['slug']) ->where('status', '=', 1) ->where('publish_at', '<', Carbon::now()) ->first(); if (!$post) { $this->flash('danger', 'That blog post cound not be found.'); return $this->redirect($response, 'blog'); } if ($request->isPost()) { if (!$this->auth->check()) { $this->flashNow('danger', 'You need to be logged in to comment.'); return $this->view->render($response, 'blog-post.twig', array("post" => $post, "showSidebar" => 1)); } if ($request->getParam('add_comment') !== null) { if ($this->addComment($post)) { $this->flash('success', 'Your comment has been submitted.'); return $response->withRedirect($request->getUri()->getPath()); } $this->flashNow('danger', 'There was a problem submitting your comment. please try again.'); } if ($request->getParam('add_reply') !== null) { if ($this->addReply()) { $this->flash('success', 'Your reply has been submitted.'); return $response->withRedirect($request->getUri()->getPath()); } $this->flashNow('danger', 'There was a problem submitting your reply. please try again.'); } } return $this->view->render( $response, 'blog-post.twig', array("post" => $post, "showSidebar" => 1, "requestParams" => $request->getParams()) ); }
Blog Post
entailment
protected function findValueInArray($searchKey, $valueArray) { $connection = $this->getConnection(); // ensure that array is not empty if (!count($valueArray)) { i5ErrorActivity(I5_ERR_PHP_TYPEPARAM, I5_CAT_PHP, "Array of input values must not be empty", "Array of input values must not be empty"); return false; } foreach ($valueArray as $key=>$value) { // a match was found! if ($key == $searchKey) { // $valToLog = (is_array($value)) ? print_r($value, true) : $value; // $connection->logThis("findValueInArray: searchKey: $searchKey. value found: $valToLog"); return $value; } } // if failed, return null // $connection->logThis("findValueInArray: searchKey: $searchKey. no value found"); return false; }
Given an array key name, recursively search the input values array and return the value associated with the key name provided. @param string $searchKey key to search for @return string|array|false value found in input array for array key. false if failed
entailment
protected function oldToNewDescriptionItem($oldDataDescription = array(), $inputValues = null) { // pass in old, return new if (!$oldDataDescription || !is_array($oldDataDescription) || !count($oldDataDescription)) { return false; } // $inputValues can be a branch of the overall input tree, if this function was called recursively. // if building a "receive-only" data structure, we can use default values. $useDefaultValues = $this->getIsReceiverOnly(); // convert keys to lowercase to make case-insensitive // because key case is usually inconsistent with toolkit // PHP function array_change_key_case() works on top level of array. $old = array_change_key_case($oldDataDescription, CASE_LOWER); // can initialize with saved array if not planning to use default values anyway if (!$inputValues && !$useDefaultValues) { $inputValues = $this->getInputValues(); } $connection = $this->getConnection(); // $connection->logThis("desc in: " . print_r($old, true) . " value array in: " . print_r($inputValues, true)); // $connection->logThis("use default values? $useDefaultValues"); // get count/dim (0 if none) $dim = 0; // default $nameContainingCount = ''; // default if (isset($old['count']) && $old['count']) { // This param contains a count value $dim = $old['count']; } elseif (isset($old['countref']) && $old['countref']) { // This param refers to another parameter that contains a count value (or will after program execution). // countref takes value from a param value // Find the input array entry that countref references, and assign its value to $dim. // Note that this value will probably change in an RPG/COBOL program // according to the actual number of records returned. $nameContainingCount = trim($old['countref']); // save this countref name for later use (we will later set a label on the countref field itself) $this->addCountRefName($nameContainingCount); // get value of actual field referred to by countref. This will be starting count for dim='count', for initializing occur arrays in called program. // findInputValueByName() searches recursively for the desired key. $countRefValue = $this->findInputValueByName($nameContainingCount, $this->getInputValues()); // getInputValues() goes to original input array to search all params for the countref field if (!$countRefValue) { // value not found for countRef. Use default of 999 for backwards compatibility with older CW versions. // (If the called program sets the field referred to by countRef ('dou/enddo' value)to a number higher than 999, the limit will still be 999.) $countRefValue = 999; } // if key found, value must be numeric (numeric string or integer) because it'll be our count. if (is_numeric($countRefValue)) { $dim = trim($countRefValue); } else { // error! not found, or an array or possibly a non-numeric string. i5ErrorActivity(I5_ERR_PHP_TYPEPARAM, I5_CAT_PHP, "Value for CountRef, field $nameContainingCount, must exist and be numeric", "Value for CountRef, field $nameContainingCount, must exist and be numeric"); return false; } } // input or output. default to input. // May have multiple values OR'ed together. $io = (isset($old['io']) && $old['io']) ? $old['io'] : I5_IN; // get new IO from old. Try one at a time. $inOutStuff = $io & I5_INOUT; // two bits. could be IN, OUT, or INOUT $byVal = $io & I5_BYVAL; $newInout = (isset($this->_inoutMap[$inOutStuff])) ? $this->_inoutMap[$inOutStuff] : 'in'; $newBy = (isset($this->_inoutMap[$byVal])) ? $this->_inoutMap[$byVal] : ''; // default is blank // get name $name = (isset($old['name']) && $old['name']) ? $old['name'] : ''; // get dsname (only present if a data structure) $dsName = (isset($old['dsname']) && $old['dsname']) ? $old['dsname'] : ''; if ($dsName) { // data structure detected! // See if there is a DSParm containing subfields. $dsParm = (isset($old['dsparm']) && $old['dsparm']) ? $old['dsparm'] : ''; // check that it's an array, which dsParm should be if (!is_array($dsParm)) { i5ErrorActivity(I5_ERR_PHP_TYPEPARAM, I5_CAT_PHP, 'DSParm must be an array', 'DSParm must be an array'); return false; } // check that it's non-empty if (!count($dsParm)) { i5ErrorActivity(I5_ERR_PHP_TYPEPARAM, I5_CAT_PHP, 'DSParm must not be empty', 'DSParm must not be empty'); return false; } /* For the data structure $dsParm, * get array of subfield input values * * The array may contain real values or default values. */ /* $useDefaultValues may be true in two situations: 1. We're calling "receive data queue" or other similar function where the data ALWAYS starts empty, and that has requested default values 2. We are doing a normal program call but the associated input/output values are not present. */ if ($useDefaultValues) { /** * Create values to fill array hinted at by dsParm. */ $dsData = array(); // loop through subfields of the data structure foreach ($dsParm as $subParm) { // for each subfield, find a name (regular name or data structure name) // and initialize its value ($dsData) to blanks. // This is the process of creating an array of values. $subParm = array_change_key_case($subParm, CASE_LOWER); // for consistency // look for name or dsname $subname = ''; if (isset($subParm['name'])) { $subname = $subParm['name']; } elseif (isset($subParm['dsname'])) { $subname = $subParm['dsname']; } // At this point we have a subfield name, derived from if (!$subname) { i5ErrorActivity(I5_ERR_PARAMNOTFOUND, I5_CAT_PHP, "Subfield of $dsName does not have a name itself", "Subfield of $dsName does not have a name itself"); return false; } $dsData[$subname] = ''; // default value. TODO Could do 0 or something for numeric } } else { // default values not requested. // For this parameter that's a data structure, // Look up its value (could be another data structure or a single value) // in the input array, based on data structure name. $dsData = $this->findValueInArray($dsName, $inputValues); // Compare with false since this is what findValueInArray returns on error // this will prevent things such as empty arrays from causing errors if ($dsData === false) { // ds has no description to match value! i5ErrorActivity(I5_ERR_PARAMNOTFOUND, I5_CAT_PHP, "Requested parameter '$dsName' does not exist in the input data", "Requested parameter $dsName does not exist in the input data"); return false; } } /** * dim > 1 * We will create an array of description items. * If we are using default values then we need to wrap it in an "array" data structure * because later it will come back to us, as output, with all elements generated * within that structure. * * If we are not using default values, let's assume that data for the array has been provided to us * fully formed. * */ if ($dim > 1) { // Array requested. // Step 1: expand the data into an array. // This occurs whether we're using default values or not. // If we had real data, assume it's already an array. // if we use default values, treat as a single DS but employ the "dim" attribute to tell XMLSERVICE to provide output of dim/array of DS. // if we use real values, expect an array of arrays (the fully formed array of data) // to exist, and dsData is the outer array to be looped through. // if not default values then expand to array $expandToArray = !$useDefaultValues; // If we are expanding to a fully data-populated array then we don't need to tell XMLSERVICE // to dimension anything via the 'dim' tag. // If we plan to pass one array element representing the whole, // Then pass the dim value to XMLSERVICE so that XMLSERVICE can provide output // that's dim'med to the proper size. if ($expandToArray) { $dimTagValue = 0; } else { // use the 'dim' tag instead of expanding it with full data $dimTagValue = $dim; // Put an outer array around our single element so it can survive the "foreach" below. $dsData = array(0 => $dsData); } // Now, whether we used default values or not, // Create an array of identical DS'es. // We do this by looping through the values, // associating each value with its "description" (name, data type, etc.) // If default values, make an array of one record, but specify 'dim', too. // TODO check that count of ds values (each a ds) does not exceed dim. /** * $connection->logThis("array of DS found. dsName: $dsName. dsData: " . print_r($dsData, true) . ' dsParm: ' . print_r($dsParm, true)); */ // Step 2: Associate description with data for each element of the DS // In this case, we have real data so we loop through each array element. // If default values, works the same but with only one element. // treat each ds and data array separately. // loop through input values array for DS $dsDataValues = array(); foreach ($dsData as $numericIndex=>$dsDataSingle) { // work with a single data structure // *** dsParm (structure) will be the same for each ds in the array **** // recursively handle each ds in array and add to dsDataValue array. // Handle one data array element at a time // We will have something like: // dsparm: /* array ( array ("Name"=>"PS1", "IO"=>I5_INOUT, "Type"=>I5_TYPE_CHAR, "Length"=>10), array ("Name"=>"PS2", "IO"=>I5_INOUT, "Type"=>I5_TYPE_CHAR, "Length"=>10), array ("Name"=>"PS3", "IO"=>I5_INOUT, "Type"=>I5_TYPE_CHAR, "Length"=>10) ); */ // dsdata: /* array( array("PS1"=>"test1", "PS2"=>"test2", "PS3"=>"test3"), array("PS1"=>"test3", "PS2"=>"test4", "PS3"=>"test5") ); */ // $connection->logThis("recursively handle a single DS from an array"); // pass in full description of DS, including DS name etc., but with count = 1. $singleDsDesc = $old; unset($singleDsDesc['count'],$singleDsDesc['countref']); // single now // On output we will use numeric index (0, 1, 2, 3...) as "name" of array elements // $singleDsDesc['dsname'] = $dsName; // pass in the ds elements and the input data for it. // Get back the new-style description item. $newStyleItem = $this->oldToNewDescriptionItem($singleDsDesc,array($dsName=>$dsDataSingle)); // dim tag tells XMLSERVICE to expand this element to a certain maximum size on output // (after the RPG/COBOL completes) to hold the output array. if ($dimTagValue) { $newStyleItem->setParamDimension($dimTagValue); // dim gets set at inner level // if a "do until" label is supplied, the actual array size will be determined // by the value of a "count" field defined in the RPG/COBOL. // Set a label to identify the count field. The same label will be attached // to the count field to match them up. if (isset($nameContainingCount) && $nameContainingCount) { $newStyleItem->setParamProperties(array('dou'=>$nameContainingCount)); } //(if ($nameContainingCount)) } $dsDataValues[] = $newStyleItem; } // create a special "array" ds to house the array of DSes. // Very important. The output parser will see this DS labeled [array='true'] and know that we have an array of DSes inside. $new = new DataStructure($dsDataValues, $dsName, 0 , false, '', true); // 'true' says this outer structure is an array } else { // not dim, not an array of DSes. A single DS. foreach ($dsParm as $singleParm) { // singleParm is something like this: /** * [Name] => PS1 * [IO] => 3 * [Type] => 0 * [Length] => 10 */ // do it within ds // Use recursion to get each subfield. $dataValue[] = $this->oldToNewDescriptionItem($singleParm, $dsData); } // create a ds based on individual parms gathered above. $new = new DataStructure($dataValue, $dsName); } } else { // *** not a data structure. A regular element (could be an array or single value). *** // data type. don't check for "empty" or $old[['type'], because 0 is legit (CHAR). $type = (isset($old['type'])) ? $old['type'] : '0'; // get new type from old $newType = ($this->_typeMap[$type]) ? $this->_typeMap[$type] : ''; // get length if there is one $length = (isset($old['length']) && $old['length']) ? $old['length'] : ''; // split into whole and decimal parts. may be like "3" or "3.1" list($whole, $dec) = explode('.', $length) + array('', ''); // extra array avoids Undefined index errors // TODO: apply same dim/array logic here that was used above for data structure dim/arrays. // But the need is not as urgent here because single-element arrays are not as big (XML-wise) // as data structures. Also, multiple occurrence data structures are more prevalent // than are single-element arrays. if ($useDefaultValues) { // if $dim, it's an array. Otherwise a single value. if ($dim > 1) { // array of dummy values, dimension of $dim // TODO: should be able to use a single ProgramParameter object with the 'dim' value set. // Or try to fix into a DS mold. $dataValue = array_fill(0, $dim, ''); $isArray = true; } else { // single dummy value $dataValue = ''; $isArray = false; // and leave $dim alone to flow into the ProgramParmeter below. } } else { // real values $dataValue = $this->findValueInArray($name, $inputValues); // make sure array count doesn't exceed $dim (planned count). $isArray = is_array($dataValue); if ($isArray) { if (count($dataValue) > $dim) { i5ErrorActivity(I5_ERR_ENDOFOCC, I5_CAT_PHP, "Number of array elements in $name greater than the maximum, $dim, set in the description", "Number of array elements in $name greater than the maximum, $dim, set in the description"); return false; } } } // done with $dim. PHP wrapper handles dim differently. $dim = 0; //$type, $io, $comment='', $varName = '', $value, $varing = 'off', $dimension = 0, $by = 'ref') $new = new ProgramParameter( // type sprintf($newType, $whole, $dec), // io $newInout, // comment $name, // varName $name, // value $dataValue, // varing 'off', // dimension $dim, // by (val or ref) $newBy, // is array says the param is an array $isArray ); // $loggableValue = (is_array($dataValue)) ? print_r($dataValue, true) : $dataValue; // $connection->logThis("just said new ProgramParameter with name: $name and dataValue: $loggableValue"); } return $new; }
Process a single parameter definition, converting from old toolkit to new toolkit style. Each description item contains: Name - name of the field Type - type of the field, can be one of Data types Length for CHAR, BYTE - integer describing length. Length can be number or name of the variable holding the length in the data structure. for PACKED, ZONED - string "NUMBER.NUMBER" defining length and precision for STRUCT - array containing data definition of the structure Data structure is defined via PHP as follows: DSName - name of the parameter DSParm (optional) - array of the parameter of the Data structure. Each parameter is defined by a data definition in the same format as described here. for INT, FLOAT - ignored IO - can be one of I/O values (I5_IN|I5_OUT, I5_INOUT). Default is I5_IN count (optional) - repetition count if the field is an array countRef (optional) - reference to the repetition count if the field is an array @param array $oldDataDescription @param null $inputValues @return bool|DataStructure|ProgramParameter array of new or, if a problem, false.
entailment
public function generateNewToolkitParams($input = array(), $description = null) { $paramsForNewToolkit = array(); // store input value array for safekeeping. // could be blank. $this->setInputValues($input); // use specified description if available, otherwise class member description. $description = ($description) ? ($description) : $this->_description; // do one at a time foreach ($description as $key=>$descParam) { // convert top-level keys to lower case for consistency. $descParam = array_change_key_case($descParam, CASE_LOWER); // if an input value wasn't specified for a param definition/description, // set a flag to provide default input values (often used as a placeholder). $needDefaultInput = false; // default // if not globally specified as needing default input values if (!$this->getIsReceiverOnly()) { // desc name can be given under the index "name" or "dsname". if ((isset($descParam['name']) && $descParam['name'])) { $name = $descParam['name']; } elseif (isset($descParam['dsname']) && $descParam['dsname']) { $name = $descParam['dsname']; } else { i5ErrorActivity(I5_ERR_PHP_TYPEPARAM, I5_CAT_PHP, "Parameter name in description is missing or blank", "Parameter name in description is missing or blank"); return false; } // if corresponding input param not given, set flag for using default. $needDefaultInput = !isset($input[$name]); } if ($needDefaultInput) { // only set this if didn't already turn on receiver-only globally. We don't want to interfere then. $this->setIsReceiverOnly(true); } // Build array of new style parameters // as we convert each param from old toolkit style to new. $paramsForNewToolkit[] = $this->oldToNewDescriptionItem($descParam); if ($needDefaultInput) { // revert back to false. $this->setIsReceiverOnly(false); } } // Determine if any "CountRef" field references were found. // If so, apply "enddo" label to those countref fields that were referenced. if ($countRefNames = $this->getCountRefNames()) { foreach ($countRefNames as $countRefName) { // for each countRefName, find data definition (new toolkit params now) // where that fieldname is defined. // If not defined, write error to error log. // If found, set the enddo label there. foreach ($paramsForNewToolkit as $param) { // check name of param for a match if ($param->getParamName() == $countRefName) { if (!$param->isDS()) { // Good, we found matching field name that's a regular field. // Use the count ref name as the label. // Should work as long as there aren't two identically named countRef fields. $param->setParamProperties(array('enddo'=>$countRefName)); } else { // no good. Count must be in a regular variable, not a DS. $this->getConnection()->logThis("countRef $countRefName cannot be specified by a data structure. Must be a scalar variable type to hold the count."); } break; // we found what we wanted } } } } // TODO: when count/dim is specified, use it as max array size. otherwise error 38 should occur. return $paramsForNewToolkit; }
Take the previously given data description and match up with values and output params to make a parameter array/object that can be presented to a program or data queue, etc. If any error or validation problem occurs (such as a value not matching data type), return false. @param array $input Data input params @param array $description[optional] Description of data, if want to specify explicitly rather than to use description from class member. @return array|boolean Return the param array or, if an error occurs, false.
entailment
public function callProgram($newInputParams = array()) { $pgmInfo = $this->getObjInfo(); $pgmName = $pgmInfo['obj']; $lib = $pgmInfo['lib']; $func = $pgmInfo['func']; $options = array(); // if a service program subprocedure (function) is defined if ($func) { $options['func'] = $func; } $pgmCallOutput = $this->getConnection()->PgmCall($pgmName, $lib, $newInputParams, // null for returnvalue var because old toolkit doesn't handle return values (as far as we can tell) null, $options); // TODO handle errors $conn = $this->getConnection(); if ($pgmCallOutput) { $outputParams = $conn->getOutputParam($pgmCallOutput); $this->setPgmOutput($outputParams); return true; } else { return false; } }
Given input values and an output array in a particular format, and having captured the data description and program info in the constructor, and having converted the data desc and interpolated the values, Now we call the program and return an array of output variables. @param array $newInputParams New-style toolkit array of params including values (use generateNewToolkitParams($inputValues) to create it) @return boolean true if OK, false if it didn't succeed.
entailment
protected function findInputValueByName( $name, $inputArray ) { foreach($inputArray as $key=>$value){ if($key === $name) { // use === because plain == allowed numeric indexes to be equal to names return $value; } if (is_array($value)) { if (($result = $this->findInputValueByName($name,$value)) !== false) { return $result; } } } return false; }
search through entire input array for the value indicated by name. @param $name @param $inputArray @return bool
entailment
public function tagsAdd(Request $request, Response $response) { if ($check = $this->sentinel->hasPerm('blog_tags.create', 'dashboard', $this->config['blog-enabled'])) { return $check; } if ($request->isPost()) { $tagName = $request->getParam('tag_name'); $tagSlug = $request->getParam('tag_slug'); $this->validator->validate($request, [ 'tag_name' => V::length(2, 25)->alpha('\''), 'tag_slug' => V::slug() ]); $checkSlug = BT::where('slug', '=', $request->getParam('tag_slug'))->get()->count(); if ($checkSlug > 0) { $this->validator->addError('tag_slug', 'Slug already in use.'); } if ($this->validator->isValid()) { $addTag = new BT; $addTag->name = $tagName; $addTag->slug = $tagSlug; if ($addTag->save()) { $this->flash('success', 'Category added successfully.'); return $this->redirect($response, 'admin-blog'); } } $this->flash('danger', 'There was a problem adding the tag.'); return $this->redirect($response, 'admin-blog'); } }
Add New Blog Tag
entailment
public function tagsDelete(Request $request, Response $response) { if ($check = $this->sentinel->hasPerm('blog_tags.delete', 'dashboard', $this->config['blog-enabled'])) { return $check; } $tag = BT::find($request->getParam('tag_id')); if (!$tag) { $this->flash('danger', 'Tag doesn\'t exist.'); return $this->redirect($response, 'admin-blog'); } if ($tag->delete()) { $this->flash('success', 'Tag has been removed.'); return $this->redirect($response, 'admin-blog'); } $this->flash('danger', 'There was a problem removing the tag.'); return $this->redirect($response, 'admin-blog'); }
Delete Blog Tag
entailment
public function tagsEdit(Request $request, Response $response, $tagId) { if ($check = $this->sentinel->hasPerm('blog_tags.update', 'dashboard', $this->config['blog-enabled'])) { return $check; } $tag = BT::find($tagId); if (!$tag) { $this->flash('danger', 'Tag doesn\'t exist.'); return $this->redirect($response, 'admin-blog'); } if ($request->isPost()) { // Get Vars $tagName = $request->getParam('tag_name'); $tagSlug = $request->getParam('tag_slug'); // Validate Data $validateData = array( 'tag_name' => array( 'rules' => V::length(2, 25)->alpha('\''), 'messages' => array( 'length' => 'Must be between 2 and 25 characters.', 'alpha' => 'Letters only and can contain \'' ) ), 'tag_slug' => array( 'rules' => V::slug(), 'messages' => array( 'slug' => 'May only contain lowercase letters, numbers and hyphens.' ) ) ); $this->validator->validate($request, $validateData); //Validate Category Slug $checkSlug = $tag->where('id', '!=', $tagId)->where('slug', '=', $tagSlug)->get()->count(); if ($checkSlug > 0 && $tagSlug != $tag['slug']) { $this->validator->addError('tag_slug', 'Category slug is already in use.'); } if ($this->validator->isValid()) { $tag->name = $tagName; $tag->slug = $tagSlug; if ($tag->save()) { $this->flash('success', 'Category has been updated successfully.'); return $this->redirect($response, 'admin-blog'); } $this->flash('success', 'An unknown error occured.'); } } return $this->view->render($response, 'blog-tags-edit.twig', ['tag' => $tag]); }
Edit Blog Tag
entailment
protected function getDefaultServiceParams() { return array('XMLServiceLib' => $this->getConfigValue('system', 'XMLServiceLib', 'ZENDSVR6'), 'HelperLib' => $this->getConfigValue('system', 'HelperLib', 'ZENDSVR6'), 'debug' => $this->getConfigValue('system', 'debug', false), 'debugLogFile' => $this->getConfigValue('system', 'debugLogFile', false), 'encoding' => $this->getConfigValue('system', 'encoding', 'ISO-8859-1'), 'parseOnly' => $this->getConfigValue('testing', 'parse_only', false), 'parseDebugLevel' => $this->getConfigValue('testing', 'parse_debug_level', null)); }
get service param values from Config to use in object
entailment
protected function getOptionalParams($type, array $optionalParams) { foreach ($optionalParams as $optionalParamName) { $val = $this->getConfigValue($type, $optionalParamName); if ($val) { $this->serviceParams[$optionalParamName] = $val; } $this->optionalParamNames = $optionalParamName; } }
get optional param values from Config and add them to the service params @param $type @param array $optionalParams
entailment
protected function plugSizeToBytes($plugSize) { // return size in bytes based on plugSize. if (isset($this->_dataSize[$plugSize])) { return $this->_dataSize[$plugSize]; } throw new \Exception("plugSize '$plugSize' is not valid. Try one of these: " . $this->validPlugSizeList()); }
return size in bytes based on plugSize. @param $plugSize @throws \Exception
entailment
protected function chooseTransport($transportName = '') { switch($transportName) { case 'http': $transport = new httpsupp(); $transport->setUrl( $this->getOption('httpTransportUrl') ); $this->setTransport($transport); break; case 'https': $transport = new httpsupp(); // Set SSL certificate authority file $sslCaFile = $this->getConfigValue('transport', 'sslCaFile'); $transport->setSSLCAFile($sslCaFile); // Set server name $serverName = $this->getConfigValue('transport', 'serverName'); $transport->setServerName($serverName); $transport->setUrl( $this->getOption('httpTransportUrl') ); $this->setTransport($transport); break; default: $this->setDb($transportName); } }
Choose data transport type: ibm_db2, odbc, http @param string $transportName 'ibm_db2' or 'odbc' or 'http' @throws \Exception
entailment
protected function setDb($transportType = '') { $transportType = trim($transportType); // if extension is specified, use it; else use default db. $extensionName = ($transportType) ? $transportType : DBPROTOCOL; if (!extension_loaded($extensionName)) { throw new \Exception("Extension $extensionName not loaded."); } // extension is loaded. Set up db transport objects. if ($extensionName === 'ibm_db2') { $this->setOptions(array('plugPrefix' => 'iPLUG')); $this->db = new db2supp(); $this->setDb2(); // not used in toolkit anymore but keep for backwards compat. } elseif ($extensionName === 'odbc') { //for odbc will be different default stored procedure call $this->setOptions(array('plugPrefix' => 'iPLUGR')); // "R" = "result set" which is how ODBC driver returns param results $this->db = new odbcsupp(); } // transport, too, to be generic $this->setTransport($this->db); return; }
transport type is same as db extension name when a db transport is used. @param string $transportType @throws \Exception
entailment
public function setToolkitServiceParams(array $XmlServiceOptions) { // copy incoming options to new array that we can safely manipulate $options = $XmlServiceOptions; // special cases first /* If sbmjobParams is present, it must contain at least one slash. If not, do not process it. * The slash implies that subsystem name and subsytem decscription (and, optionally, job name) * are present in the string */ if (isset($options['sbmjobParams']) && !strstr($options['sbmjobParams'], "/")) { unset($options['sbmjobParams']); } //(if sbmjobParams is set but no slash) // if a plug name is passed in, it overrides plugPrefix and plugSize. if (isset($options['plug']) && $options['plug']) { // @todo enumerate plug prefixes centrally, tied to db extension name, at top of this class $possiblePrefixes = array('iPLUG', 'iPLUGR'); $options['plugSize'] = str_replace($possiblePrefixes, '', $options['plug']); // remove prefix to get size $options['plugPrefix'] = str_replace($options['plugSize'], '', $options['plug']); // remove size to get prefix } // encoding provided but it's blank if (isset($options['encoding']) && !$options['encoding']) { unset($options['encoding']); } // verify that schemaSep is a valid character for this purpose if (isset($options['schemaSep']) && !in_array($options['schemaSep'], $this->_validSeparators)) { unset($options['schemaSep']); } // handle case sensitivity. Put value in index of proper camel casing if (isset($options['InternalKey'])) { $options['internalKey'] = $options['InternalKey']; } // now set all in a generic fashion // loop through all options provided in param foreach ($options as $optionName=>$optionValue) { if (isset($this->_options[$optionName])) { // it's valid. Set class property to its value. $this->_options[$optionName] = $optionValue; } } }
Also alias setOptions() @param array $XmlServiceOptions
entailment
public function getToolkitServiceParam($optionName) { // special case, case sensitivity if ($optionName == 'InternalKey') { $optionName = 'internalKey'; } // we use array_key_exists() rather than isset() because the value may be null. if (array_key_exists($optionName, $this->_options)) { return $this->_options[$optionName]; } else { // nothing matched Throw new \Exception("Invalid option requested: $optionName"); } }
get a single option value return property value if property is set. @param $optionName @return bool @throws \Exception
entailment
public function disconnect() { // if stateful connection, end the toolkit job. if (!$this->isStateless()) { $this->PgmCall("OFF", NULL); } // if transport is a db, end the db connection. if (isset($this->db) && $this->db) { $this->db->disconnect($this->conn); } $this->conn = null; }
end job if private job (internal key set); end DB transport if not persistent.
entailment
public function disconnectPersistent() { $this->PgmCall("OFF", NULL); if (isset($this->db) && $this->db) { $this->db->disconnectPersistent($this->conn); } $this->conn = null; }
same as disconnect but also really close persistent database connection.
entailment
public function specialCall($callType) { $this->setOptions(array($callType=>true)); $outputArray = $this->PgmCall("NONE", NULL, NULL ,NULL); $this->setOptions(array($callType=>false)); return $outputArray; }
for special requests such as transport, performance, license @param $callType @return array|bool
entailment
public function pgmCall($pgmName, $lib, $inputParam = NULL, $returnParam = NULL, $options = NULL) { $this->cpfErr = ''; $this->error = ''; $this->joblog = ''; $function = NULL; ProgramParameter::initializeFallbackVarName(); // If only one 'return' param, turn it into an array for later processing. if ($returnParam instanceof ProgramParameter) { $returnParam = array($returnParam); } $this->XMLWrapper = new XMLWrapper(array('encoding' => $this->getOption('encoding')), $this); // $optional handles special requests such as 'license' $disconnect = (strcmp($pgmName, "OFF") === 0) ? true : false; $optional = (strcmp($pgmName, "NONE") === 0) ? true : false; $outputParamArray = false; if (isset($options['func'])) { $function = $options['func']; } if ($disconnect || $optional) { $inputXml = $this->XMLWrapper->disconnectXMLIn(); } else { $inputXml = $this->XMLWrapper->buildXmlIn($inputParam, $returnParam, $pgmName, $lib, $function); } // send XML to XMLSERVICE $outputXml = $this->sendXml($inputXml, $disconnect); if ($outputXml != '') { $outputParamArray = $this->XMLWrapper->getParamsFromXml($outputXml); // didn't get expected return, search logs to find out why if (!is_array($outputParamArray)) { // No real data. Look for errors. Retrieve details from joblog. $this->joblog = $this->XMLWrapper->getLastJoblog(); // standard list of programs that provide CPF codes in joblog $programsToLookFor = array($pgmName, '< lveContext', '#mnrnrl', 'QRNXIE', '< allProgram'); if (isset($this->_cpfMapping[$pgmName])) { // list of other programs not called directly that might generate CPF codes in joblog. $programsToLookFor = array_merge($programsToLookFor, $this->_cpfMapping[$pgmName]); } // put values in $this->cpfErr and $this->error $this->extractErrorFromJoblog($programsToLookFor); } } unset ($this->XMLWrapper); // output array includes in/out parameters and return parameters. return $outputParamArray; }
pgmCall @param string $pgmName Name of program to call, without library @param string $lib Library of program. Leave blank to use library list or current library @param null $inputParam An array of ProgramParameter objects OR XML representing params, to be sent as-is. @param null $returnParam ReturnValue Array of one parameter that's the return value parameter @param null $options Array of other options. The most popular is 'func' indicating the name of a subprocedure or function. @return array|bool
entailment
public function ExecuteProgram($inputXml, $disconnect = false) { $this->execStartTime = ''; $this->error = ''; $this->VerifyPLUGName(); // calculates value of option 'plug' $this->VerifyInternalKey(); // @todo create driver-specific SQL in driver classes (db2, odbc) $internalKey = $this->getInternalKey(); $controlKeyString = $this->getControlKey($disconnect); $plugSize = $this->getOption('plugSize'); // @todo have one transport class that includes db as well. // If a database transport if (isset($this->db) && $this->db) { $result = $this->makeDbCall($internalKey, $plugSize, $controlKeyString, $inputXml, $disconnect); } else { // Not a DB transport. At this time, assume HTTP transport (which doesn't use a plug, by the way. uses outbytesize) $transport = $this->getTransport(); $transport->setIpc($internalKey); $transport->setCtl($controlKeyString); $url = $this->getOption('httpTransportUrl'); $transport->setUrl($url); // convert plugSize to bytes $outByteSize = $this->plugSizeToBytes($plugSize); // if debug mode, log control key, and input XML. if ($this->isDebug()) { $this->debugLog("\nExec start: " . date("Y-m-d H:i:s") . "\nVersion of toolkit front end: " . self::getFrontEndVersion() ."\nToolkit class: '" . __FILE__ . "'\nIPC: '" . $this->getInternalKey() . "'. Control key: $controlKeyString\nHost URL: $url\nExpected output size (plugSize): $plugSize or $outByteSize bytes\nInput XML: $inputXml\n"); $this->execStartTime = microtime(true); } $result = $transport->send($inputXml, $outByteSize); // workaround: XMLSERVICE as of 1.7.4 returns a single space instead of empty string when no content was requested. if ($result == ' ') { $result = ''; } } if ($this->isDebug() && $result) { $end = microtime(true); $elapsed = $end - $this->execStartTime; $this->debugLog("Output XML: $result\nExec end: " . date("Y-m-d H:i:s") . ". Seconds to execute: $elapsed.\n\n"); } return $result; }
Send any XML to XMLSERVICE toolkit. The XML doesn't have to represent a program. Was protected; made public to be usable by applications. @param $inputXml @param bool $disconnect @return string @throws \Exception
entailment
public function CLCommand($command, $exec = '') { $this->XMLWrapper = new XMLWrapper(array('encoding' => $this->getOption('encoding')), $this); $this->cpfErr = '0'; $this->error = ''; $this->errorText = ''; $inputXml = $this->XMLWrapper->buildCommandXmlIn($command, $exec); // rexx and pase are the ways we might get data back. $expectDataOutput = in_array($exec, array('rexx', 'pase', 'pasecmd')); // if a PASE command is to be run, the tag will be 'sh'. Otherwise, 'cmd'. if ($exec == 'pase' || $exec == 'pasecmd') { $parentTag = 'sh'; } else { $parentTag = 'cmd'; } $this->VerifyPLUGName(); // send the XML, running the command $outputXml = $this->sendXml($inputXml, false); // get status: error or success, with a real CPF error message, and set the error code/msg. $successFlag = $this->XMLWrapper->getCmdResultFromXml($outputXml, $parentTag); if ($successFlag) { $this->cpfErr = '0'; $this->error = ''; } else { $this->cpfErr = $this->XMLWrapper->getErrorCode(); $this->error = $this->cpfErr; // ->error is ambiguous. Include for backward compat. $this->errorText = $this->XMLWrapper->getErrorMsg(); } if ($successFlag && $expectDataOutput) { // if we expect to receive data, extract it from the XML and return it. $outputParamArray = $this->XMLWrapper->getRowsFromXml($outputXml, $parentTag); unset($this->XMLWrapper); return $outputParamArray; } else { // don't expect data. Return true/false (success); unset($this->XMLWrapper); return $successFlag; } }
CLCommand @param array $command string will be turned into an array @param string $exec could be 'pase', 'pasecmd', 'system,' 'rexx', or 'cmd' @return array|bool
entailment
protected function getControlKey($disconnect = false) { $key = ''; if ($disconnect) { return "*immed"; } /* if(?) *justproc if(?) *debug if(?) *debugproc if(?) *nostart if(?) *rpt*/ // Idle timeout supported by XMLSERVICE 1.62 // setting idle for *sbmjob protects the time taken by program calls // Do that with *idle(30/kill) or whatever the time in seconds. if (trim($this->getOption('idleTimeout')) != '') { $idleTimeout = $this->getOption('idleTimeout'); $key .= " *idle($idleTimeout/kill)"; // ends idle only, but could end MSGW with *call(30/kill) } // if cdata requested, request it. XMLSERVICE will then wrap all output in CDATA tags. if ($this->getOption('cdata')) { $key .= " *cdata"; } /* stateless calls in stored procedure job * * Add *here, which will run everything inside the current PHP/transport job * without spawning or submitting a separate XTOOLKIT job. */ if ($this->isStateless()) { $key .= " *here"; } else { // not stateless, so could make sense to supply *sbmjob parameters for spawning a separate job. if (trim($this->getOption('sbmjobParams')) != '') { $sbmjobParams = $this->getOption('sbmjobParams'); $key .= " *sbmjob($sbmjobParams)"; } } // if internal XMLSERVICE tracing, into database table XMLSERVLOG/LOG, is desired if ($this->getOption('trace')) { $key .= " *log"; } // directive not to run any program, but to parse XML and return parsed output, including dim/dou. if ($this->getOption('parseOnly')) { $key .= " *test"; // add a debugging level (1-9) to the parse, to make *test(n) where n is the debugging level if ($parseDebugLevel = $this->getOption('parseDebugLevel')) { $key .= "($parseDebugLevel)"; } } // return XMLSERVICE version/license information (no XML calls) if ($this->getOption('license')) { $key .= " *license"; } // check proc call speed (no XML calls) if ($this->getOption('transport')) { $key .= " *justproc"; } // get performance of last call data (no XML calls) if ($this->getOption('performance')) { $key .= " *rpt"; } // *fly is number of ticks of each operation. *nofly is the default if ($this->getOption('timeReport')) { $key .= " *fly"; } // PASE CCSID for <sh> type of functions such as WRKACTJOB ('system' command in PASE) if ($paseCcsid = $this->getOption('paseCcsid')) { $key .= " *pase($paseCcsid)"; } // allow custom control keys if ($this->getOption('customControl')) { $key .= " {$this->getOption('customControl')}"; } return trim($key); // trim off any extra blanks on beginning or end }
construct a string of space-delimited control keys based on properties of this class. @param bool $disconnect @return string
entailment
protected function VerifyPLUGName() { // if plug already set, don't need to set it now. if ($this->getOption('plug') != '') { return; } //Sets the default plug. $size = 512; $unit = 'K';//or M /*4K, 32K, 65K, 512K, 1M, 5M, 10M up to 15M ...*/ //in case that following SQL error error: //Length in a varying-length or LOB host variable not valid. SQLCODE=-311 //verify that all last blob ptfs are applied on i5 machine //set the $this->plug = "iPLUG4K";, //it calls the program that returns data via char storage $plug = $this->getOption('plugPrefix') . $size . $unit; $this->setOptions(array('plug' => $plug)); }
to set a plug name use function setToolkitServiceParams('plug'=>'iPLUGR512K')
entailment
protected function verifyInternalKey() { // if we are running in stateless mode, there's no need for an IPC key. if ($this->isStateless()) { $this->setInternalKey(''); return; } if (trim($this->getInternalKey()) == '') { if (session_id() != '') { /*if programmer already started session, use it*/ $this->setInternalKey("/tmp/" . session_id()); } else { $this->setInternalKey("/tmp/". $this->generate_name()); } } }
Ensures that an IPC has been set. If not, generate one
entailment
static function GenerateErrorParameter() { $ErrBytes = 144; $ErrBytesAv = 144; $ErrCPF = '0000000'; $ErrRes = ' '; $ErrEx = ' '; // changed $this to self so can work in static context $ds[] = self::AddParameterInt32('in', "Bytes provided", 'errbytes', $ErrBytes); $ds[] = self::AddParameterInt32('out', "Bytes available",'err_bytes_avail', $ErrBytesAv); $ds[] = self::AddParameterChar('out',7, "Exception ID", 'exceptId', $ErrCPF); $ds[] = self::AddParameterChar('out',1, "Reserved", 'reserved', $ErrRes); $ds[] = self::AddParameterHole('out',128, "Exception data", 'excData', $ErrEx); // can be bad XML so make it a hole return $ds; }
creates Data structure that going to be used in lot of i5 API's for error handling @return array
entailment
public function ParseErrorParameter(array $Error) { $CPFErr = false; if (!is_array($Error)) { return false; } // If there's an error structure and some error info was returned. if (isset($Error['exceptId']) && ($Error['err_bytes_avail'] > 0)) { $CPFErr = $Error['exceptId']; } return $CPFErr; }
err_bytes_avail is the official, reliable way to check for an error. @todo should this be using $this->cpfErr @param array $Error @return bool
entailment
protected function extractErrorFromJoblog(array $programsToLookFor) { // CPF, CPC, CPE... // also get between /*Message . . . . : Invalid length. MAXLEN for data queue NEWQ in CWDEMO is 128. Cause . . . . . : */ // where we can find info in joblog $cpfOffset = 0; // first 7 chars is CPF $cpfLen = 7; $pgmOffset = 67; // program name found on same line as CPF code, offset 68 $pgmLen = 12; // can be special '< lveContext' type names. $messageLabel = 'Message . . . . :'; $messageLabelOffset = 37; // "Message . . . . : " $messageLabelLen = strlen($messageLabel); $causeLabel = 'Cause . . . . . :'; $recoveryLabel = 'Recovery . . . :'; // split on line feeds, then put in reverse order so that we'll get the latest first $joblogLines = $lines = preg_split('/\r\n|\r|\n/', $this->joblog); // split on 0D0A etc. // in reverse order, look for line with program given/ // "true" in array_reverse() keeps array index/record numbers intact. $startingLine = 0; foreach (array_reverse($joblogLines, true) as $lineNum=>$lineString) { // Look for program name that we originally called. // Trim spaces from the right but not the left. (Need pgm name to START in precise location) $substringAtProgramLocation = rtrim(substr($lineString, $pgmOffset, $pgmLen)); if (in_array($substringAtProgramLocation, $programsToLookFor)) { $startingLine = $lineNum; break; } } if ($startingLine) { // we found a joblog entry for the program that we called. // first line of section has CPF code as well as program name. $firstLine = $joblogLines[$startingLine]; // get the error code. We call it CPF but it could also be GUI, CPE, CPC.... $cpfCode = substr($firstLine, $cpfOffset, $cpfLen); // go forward till we hit the end or till we come to a new CPF code (detect that if find a fully 7-position string at start) $msgText = ''; $startCollecting = false; // get rid of lines before starting line $joblogLines = array_slice($joblogLines, $startingLine); while (($lineString = next($joblogLines)) && ($lineString !== false) && (strpos($lineString, ' ', $cpfOffset) < $cpfLen)) { // but start collecting text when we find "Message" label. if (substr($lineString, $messageLabelOffset, $messageLabelLen) == $messageLabel) { $startCollecting = true; } if ($startCollecting) { // If not a heading (omit headings) /* 5761SS1 V6R1M0 080215 Display Job Log SBSUSA 11/18/11 15:39:54 Page 2 Job name . . . . . . . . . . : QSQSRVR User . . . . . . : QUSER Number . . . . . . . . . . . : 815166 Job description . . . . . . : QDFTSVR Library . . . . . : QGPL MSGID TYPE SEV DATE TIME FROM PGM LIBRARY INST TO PGM LIBRARY INST */ $lineLen = strlen($lineString); // Is a heading if one of the following are found. Use !== false because 0 is a valid "found" result. // Check that line length is > 46 before checking for string in position 46, to avoid warning in log $isHeadingLine = (($lineLen > 46 && (strpos($lineString, 'Display Job Log', 46) !== false)) || strpos($lineString, 'Job name', 2) !== false || strpos($lineString, 'Job description', 2) !== false || strpos($lineString, 'MSGID', 0) !== false); if (!$isHeadingLine) { // concatenate whole line. We will remove labels later $msgText .= ' '. trim($lineString); } //(if not a heading line) } } /** * Clean up $msgText. * Remove text labels and convert multiple spaces to single space */ $old = array($messageLabel, $causeLabel, $recoveryLabel, ' ', ' '); $new = array('', '', '', ' ', ' '); $cleanMsgText = str_replace($old, $new, $msgText); $this->cpfErr = $cpfCode; $this->error = trim($cleanMsgText); $this->errorText = trim($cleanMsgText); } else { // could not find it. // use error text from XML parser (though this text is usually worthless) // @todo $this->cpfErr is expecting a 7 digit code, so this may be wrong $this->cpfErr = 'UNEXPECTED'; $this->error = $this->XMLWrapper->getLastError(); $this->errorText = $this->error; } return true; }
given $this->joblog, and an array of program names that might have caused errors, extract the error code (CPF or similar) and message text from the joblog. Include '< lveContext' because it may appear in the program spot if library does not exist. '#mnrnrl' if program does not exist. 'QRNXIE' for non-numeric data passed in numeric field. '< allProgram' for when wrong number of params are passed. @todo instead of all these pseudo-program names, take last error from XMLSERVICE parsing, if program name itself not found. If can't find error in joblog, uses UNEXPECTED and text from $this->XMLWrapper->getLastError(); Code is placed in $this->cpfErr. Text goes to $this->error. @param array $programsToLookFor @return boolean True on success, False on failure
entailment
function changeCurrentUser($user, $password) { // Force user/pw to uppercase. (should they?) // Ask Support team for opinion on uppercase or not. $user = strtoupper($user); $password = strtoupper($password); // Get profile handle (checking u/p validity) // http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2Fapis%2FQSYGETPH.htm $apiPgm = 'QSYGETPH'; $apiLib = 'QSYS'; $pwLen = strlen($password); $pwCcsid = '-1'; // -1 means 37 or DFTCCSID depending on password level $params[] = $this->addParameterChar('in', 10, '1. user', 'user', $user); $params[] = $this->addParameterChar('in', 10, '2. password', 'pw', $password); $params[] = $this->addParameterBin('out', 12, '3. profile handle', 'handleOut'); // use a zero (0) bytes length to force errors to bubble up to job. It's easier for us to get full message text from joblog that XMLSERVICE toolkit provides. // As well, the QSNDDTAQ API doesn't have an error struct, so this way we can be consistent---get all errors in joblog. $params[] = $this->addParameterInt32('both', 'Size of error DS. Use 0 to force errors to bubble up to the job', 'errbytes', '0'); if (substr($password, 0, 1) != '*') { /* No asterisk at the start, so this is an attempt at a real password, * not a special pw value starting with an asterisk such as *NOPWD, *NOPWDCHK, or *NOPWDSTS. * Therefore, include pw len and CCSID, which must be omitted if pw is a special "*" value. */ $params[] = $this->addParameterInt32('both', '5. length of password. Must be equal to the actual pw length. ', 'pwLen', $pwLen); $params[] = $this->addParameterInt32('both', '6. CCSID of password', 'pwCcsid', $pwCcsid); } // now call the API, returning results. $retPgmArr = $this->PgmCall($apiPgm, $apiLib, $params, null); if ($this->getErrorMsg() || $this->getErrorCode()) { // problem--possibly user or password was wrong return false; } // get handle from API we called. if (isset($retPgmArr['io_param']['handleOut'])) { $handle = $retPgmArr['io_param']['handleOut']; // handleOut defined in XML above } // if anything went wrong if (!isset($handle) || empty($handle)) { return false; } // now set the user profile via the handle. // http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2FQWTSETP.htm // $apiPgm = 'QWTSETP'; // set profile // $apiLib = 'QSYS'; // reset $params array for next API call $params = array(); $params[] = $this->addParameterBin('in', 12, '1. profile handle', 'handleIn', $handle); // error ds param $params[] = $this->addParameterInt32('both', '2. Size of error DS. Use 0 to force errors to bubble up to the job', 'errbytes', '0'); // any errors? if ($this->getErrorMsg() || $this->getErrorCode()) { // problem--possibly user or password was wrong return false; } // Now close/release the handle (handles are limited resources, about 20,000 per job). // http://publib.boulder.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Fapis%2FQSYRLSPH.htm $apiPgm = 'QSYRLSPH'; // release profile handle $apiLib = 'QSYS'; // reset $params array for next API call $params = array(); $params[] = $this->addParameterBin('in', 12, '1. profile handle', 'handleIn', $handle); // error ds param $params[] = $this->addParameterInt32('both', '2. Size of error DS. Use 0 to force errors to bubble up to the job', 'errbytes', '0'); // now call the "release handle" API! $this->PgmCall($apiPgm, $apiLib, $params); // any errors? if ($this->getErrorMsg() || $this->getErrorCode()) { // problem--possibly user or password was wrong return false; } return true; }
changeCurrentUser (1.5.0+) Changes the current user of the job to a specific user. All actions will be executed as this user from now on. Otherwise known as "swap user" or the misnomer "adopt authority." @param string $user Generally should be uppercase @param string $password @return boolean True on success, False on failure
entailment
static function getConfigValue($heading, $key, $default = null) { // if we haven't read config file yet, do so. if (!isset(self::$_config)) { // read/stat INI once and only once per request self::$_config = parse_ini_file(CONFIG_FILE, true); } if (isset(self::$_config[$heading][$key])) { return self::$_config[$heading][$key]; } elseif (isset($default)) { return $default; } else { return false; } }
return value from toolkit config file, or a default value, or false if not found. method is static so that it can retain its value from call to call. @todo store in Zend Data Cache to avoid reading during each request @todo change getConfigValue to allow getting many at one time @param $heading @param $key @param null $default @return bool|null
entailment
static function getInstance($databaseNameOrResource = '*LOCAL', $userOrI5NamingFlag = '', $password = '', $transportType = '', $isPersistent = false) { return new Toolkit($databaseNameOrResource, $userOrI5NamingFlag, $password, $transportType, $isPersistent); }
need to define this so we get Cw object and not parent object @param string $databaseNameOrResource @param string $userOrI5NamingFlag @param string $password @param string $transportType @param bool $isPersistent @return bool|null
entailment
public function JobLog($JobName, $JobUser, $JobNumber, $direction = 'L') { if ($JobName=='' ||$JobUser=='' || $JobNumber == '') { return false; } $this->TmpUserSpace = new TmpUserSpace($this->ToolkitSrvObj, $this->TmpLib); $FullUSName = $this->TmpUserSpace->getUSFullName(); $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('input', 20, 'USER SPACE NAME', 'userspacename', $FullUSName); $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('input', 10, 'JOB NAME', 'jobname', $JobName); $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('input', 10, 'USER NAME', 'username', $JobUser); //L from the last log message to the first one //from the first message to the last one $dir = 'L'; if (strtoupper($direction) == "N") { $dir = $direction; } $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('input', 6, 'Job Number', 'jobnumber', $JobNumber); //From the Last - "L" $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('input', 1, 'Direction', 'direction', $dir); $ret_code ='0'; $InputArray[]=$this->ToolkitSrvObj->AddParameterChar('both', 1, 'retcode', 'retcode', $ret_code); $OutputArray = $this->ToolkitSrvObj->PgmCall(ZSTOOLKITPGM, $this->ToolkitSrvObj->getOption('HelperLib'), $InputArray, NULL, array('func'=>'JOBLOGINFO')); if (isset($OutputArray['io_param']['retcode'])) { //may be authorization problem if ($OutputArray['io_param']['retcode'] == '1') { //No data created in US. return false; } } sleep(1); $JobLogRows = $this->TmpUserSpace->ReadUserSpace(1, $this->TmpUserSpace->RetrieveUserSpaceSize()); $this->TmpUserSpace->DeleteUserSpace(); unset ($this->TmpUserSpace); if (trim($JobLogRows) != '') { $logArray = str_split($JobLogRows, $this->JOBLOG_RECORD_SIZE); return $logArray; } else { return false; } }
it seems that all three parms must be entered; it's for a specific job. @param $JobName @param $JobUser @param $JobNumber @param string $direction @return array|bool @throws \Exception
entailment
protected function processParamProps(&$props = array()) { $alphanumeric = true; // start with assumption // if type is not alphanumeric/char, get out of here! Hex has no purpose for non-char. if (isset($props['type']) && $props['type'] && (strtolower(substr($props['type'], -1)) != 'a')) { // there's a data type but it doesn't end with 'a' as in '3a'. $alphanumeric = false; } $data = (isset($props['data'])) ? $props['data'] : ''; $props['processedData'] = $data; // default $props['ccsidStr'] = ''; // default $props['hexStr'] = ''; // default $propUseHexValue = (isset($props['useHex'])) ? $props['useHex'] : null; // if alphanumeric (therefore a candidate for hex conversion), // and hex is set for this specific property, // or it's set globally if ($alphanumeric && ($propUseHexValue || $this->getOption('useHex'))) { // convert data to hex $props['processedData'] = bin2hex($data); $props['hexStr'] = " hex='on'"; // check for CCSID before and after. We should expect it since we're using hex. // Use property-specific value, if available, otherwise global. $ccsidBefore = (isset($props['ccsidBefore']) && $props['ccsidBefore']) ? $props['ccsidBefore'] : $this->getOption('ccsidBefore'); $ccsidAfter = (isset($props['ccsidAfter']) && $props['ccsidAfter']) ? $props['ccsidAfter'] : $this->getOption('ccsidAfter'); $props['ccsidStr'] = " before='$ccsidBefore' after='$ccsidAfter'"; } }
Do any processing on parameter properties to prepare for hex, ccsid. Adds these elements to array: processedData, ccsidStr, hexStr @todo: This works but is somewhat clumsy to use. Refactor as method of ProgramParam object with XML creator injected into it. @param array $props
entailment
protected function getPgmTag($pgm, $lib, $function) { // specify opm mode if given $opmString = ($this->getOption('v5r4')) ? " mode='opm'" : ""; // get encoded pgm/lib/func names $propArray = array(); $this->processParamProps($propArray); // if directed to use hex/CCSID, specify "long form" of program tag, with nested name/lib/func tags. // If not using hex/CCSID, use "short form" of program tag. // Why allow both? For backward compatibility with older (pre-1.6.8) XMLSERVICE that didn't support long form. if ($propArray['hexStr']) { // Hex/CCSID, so use long form of pgm tag // specify function if given $encodedFunction = $this->encodeString($function); $funcString = ($function) ? " <func{$propArray['ccsidStr']}{$propArray['hexStr']}>$encodedFunction</func>" : ""; // $pgmtag = "<pgm name='$pgm' lib='$lib'$opmString$funcString>"; // split pgm, name, lib into separate lines to can give separate encodings. $pgmtag = "<pgm$opmString> <name{$propArray['ccsidStr']}{$propArray['hexStr']}>" . $this->encodeString($pgm) . "</name> <lib{$propArray['ccsidStr']}{$propArray['hexStr']}>" . $this->encodeString($lib) . "</lib> $funcString"; } else { // no hex/CCSID, so use short form of pgm tag // (For backward compability with pre-1.6.8 XMLSERVICE) $funcString = ($function) ? " func='$function'" : ""; $pgmtag = "<pgm name='" . $pgm . "' lib='" . $lib . "' " . $opmString . $funcString . ">"; } return $pgmtag; }
getPgmTag() return the XML string that specifies a program's name, including potential library, function, and attributes. @param $pgm @param $lib @param $function @return string
entailment
protected function addOuterTags($inputXml) { // start xml with encoding tag $finalXml = $this->xmlStart(); // open script tag $finalXml .= "\n<script>"; // include override of submit command if specified if ($this->getOption('sbmjobCommand')) { $sbmJobCommand = $this->getOption('sbmjobCommand'); $finalXml .= "\n<sbmjob>{$sbmJobCommand}</sbmjob>"; } // inner "meat" of the XML $finalXml .= "\n$inputXml"; // close script tag $finalXml .= "\n</script>"; return $finalXml; }
For consistently, add commonly used starting and ending tags to input XML @todo: $xml should be a property of the class (true OO style), then $this->addOuterTags(); @param $inputXml @return string
entailment
protected function xmlToObj($xml) { $xmlobj = simplexml_load_string($xml); if (!$xmlobj instanceof \SimpleXMLElement) { $badXmlLog = '/tmp/bad.xml'; $this->error = "Unable to parse output XML, which has been logged in $badXmlLog. Possible problems: CCSID, encoding, binary data in an alpha field (use binary/BYTE type instead); if < or > are the problem, consider using CDATA tags."; error_log($xml, 3, $badXmlLog); return false; } return $xmlobj; }
convert xml string to simplexml object @param $xml @return bool|\SimpleXMLElement
entailment
public function diagnosticsXmlIn($info = 'joblog', $jobName = '', $jobUser = '', $jobNumber = '') { // xml tag $xml = $this->xmlStart(); // start of tag and info attribute $xml .= "<script><diag info='$info'"; // if specific job requested. (If not then will be current job) if ($jobName && $jobUser && $jobNumber) { $xml .= " job='$jobName' user='$jobUser' nbr='$jobNumber'"; } // end tag $xml .= " /></script>"; return $xml; }
$info can be 'joblog' (joblog and additional info) or 'conf' (if custom config info set up in PLUGCONF) @param string $info @param string $jobName @param string $jobUser @param string $jobNumber @return string
entailment
public function buildXmlIn($inputOutputParams = NULL, array $returnParams = NULL, $pgm, $lib = "", $function = NULL) { // initialize XML to empty. Could remain blank if no parameters were passed $parametersXml = ''; $returnParametersXml = ''; // input/output params and return params $params = array(); // XML can be passed directly in. If a string, assume we received XML directly. if (is_string($inputOutputParams)) { // XML for params is being provided raw. Use it. $parametersXml = $inputOutputParams; } elseif (is_array($inputOutputParams) && (!empty($inputOutputParams))) { // an array of ProgramParameter objects. Set tagName to 'parm' $params['parm'] = $inputOutputParams; } // Prepare to create XML from return param definitions, too, if they exist. if (is_array($returnParams) && (!empty($returnParams))) { // tagName is 'return' $params['return'] = $returnParams; } // process 'parm' and 'return' in the same manner. // $path will be 'parm' or 'return', which are used in creating XML path foreach ($params as $tagName=>$paramElements) { // within each tag name (parm or return), process each param. foreach ($paramElements as $param) { // do parm tag with comment and io. $elementProps = $param->getParamProperties(); // Use comments only when in debug mode. (Reduce XML sent) $commentStr = ''; if (isset($elementProps['comment']) && $this->getOption('debug')) { $commentStr = " comment='{$elementProps['comment']}'"; } // only send io if not the default 'both'. (Reduce XML sent) $ioStr = ''; if (isset($elementProps['io']) && $elementProps['io'] != 'both') { $ioStr = " io='{$elementProps['io']}'"; } // The XML tag will be named 'parm' or 'return' (value of $path). $parametersXml .= "<{$tagName}{$ioStr}{$commentStr}>"; // buildParamXml takes one ProgramParameter object and recursively build XML. $parametersXml .= $this->buildParamXml($param); // end parm tag $parametersXml .= "</{$tagName}>\n"; } } $pgmtag = $this->getPgmTag($pgm, $lib, $function); $xmlIn = "{$pgmtag}\n{$parametersXml}{$returnParametersXml}</pgm>"; return $this->addOuterTags($xmlIn); }
$inputOutputParams can be an array of ProgramParameter objects, or an XML string representing parameters already in XML form ("parm" tags). @param string|array $inputOutputParams @param array $returnParams @param $pgm @param string $lib blank library means use current/default or library list @param null $function @return string
entailment
protected function buildParamXml(ProgramParameter $paramElement) { $paramXml = ''; $specialOuterDsName = ''; // build start ds tag $props = $paramElement->getParamProperties(); // optional by $by = $props['by']; $byStr = ($by) ? " by='$by'" : ''; $name = $props['var']; // optional "array" attribute $isArray = $props['array']; $isArrayStr = ($isArray) ? " array='on'" : ''; // optional dim (goes best with multi but could exist on its own, too) $dim = $props['dim']; $dimStr = ($dim) ? " dim='$dim'" : ''; // if dim>0 and array integrity is specified $isMulti = ($dim && $this->getOption('arrayIntegrity')); /* if a multiple occurrence DS or scalar field. * later we will wrap an additional DS around it * The inner DS or scalar field will be a template with a 'dim' attribute to be expanded on output from XMLSERVICE. */ /* if we add an outer DS that's "multi," don't bother to give the inner (original) ds a name. * The inner ds will be repeated many times and its name will be replaced on output by numeric indexes. * So no need to include an inner ds name. */ if ($isMulti) { $specialOuterDsName = $name; $innerName = ''; } else { // not multi. Use normal inner name. $innerName = $name; // starts with space, directly following "<data" } // optional dou (do until) $dou = $props['dou']; $douStr = ($dou) ? " dou='$dou'" : ''; // optional len that checks length of the structure/field to which it's appended $labelLen = $props['len']; $labelLenStr = ($labelLen) ? " len='$labelLen'" : ''; // it's a data structure if ($props['type'] == 'ds') { // start ds tag with name and optional dim and by $innerNameStr = ($innerName) ? " var='$innerName'" : ''; $paramXml .= "<ds$innerNameStr$dimStr$douStr$isArrayStr$labelLenStr>\n"; // get the subfields $dsSubFields = $paramElement->getParamValue(); if (is_array($dsSubFields) && count($dsSubFields)) { // recursively build XML from each data structure subfield foreach ($dsSubFields as $subField) { $paramXml .= $this->buildParamXml($subField); } } // complete the ds tag $paramXml .= "</ds>\n"; } else { // not a data structure. a regular single field $type = $props['type']; // optional varying // varying only inserted if set on/2/4 (default is off, so we can let XMLSERVICE supply the default behavior if off). The less XML we create and send, the more efficient we will be. $varyingStr = ''; if (isset($props['varying'])) { // a valid non-off value, so add the varying attribute. if (in_array($props['varying'], $this->_varyingTypes)) { $varyingStr = " varying='{$props['varying']}'"; } } // optional enddo $enddo = $props['enddo']; $enddoStr = ($enddo) ? " enddo='$enddo'" : ''; // optional setLen to set length value to a numeric field (see 'len' for where the length comes from) $labelSetLen = $props['setlen']; $labelSetLenStr = ($labelSetLen) ? " setlen='$labelSetLen'" : ''; $data = $props['data']; if (is_object($data)) { // uh-oh. Something wrong echo "data is not a string. type is: $type. data is: " . var_export($data, true) . "<BR>"; } // get hex/ccsid information to include in the data tag $this->processParamProps($props); $ccsidHexStr = "{$props['ccsidStr']}{$props['hexStr']}"; $processedData = $props['processedData']; // Google Code issue 11 // Use short type tag when it's empty if ($processedData === '') { $dataEndTag = " />"; } else { $dataEndTag = ">$processedData</data>"; } // use the old, inefficient "repeat item with sequential numbering of field name" technique if backwards compatibility is desired $useOldDimWay = ($dim && !$isMulti); if ($useOldDimWay) { // Backward compatibility technique // a flattened group of data fields with sequentially increasing names foreach (range(1, $dim) as $sequence) { // only difference is the $sequence inserted after $innerNameStr // and no $dimStr. Because we're physically repeating the line // And always need the name specified with sequence. $paramXml .= "<data var='$innerName$sequence' type='$type'$ccsidHexStr$enddoStr$byStr$varyingStr$labelSetLenStr$dataEndTag"; } } else { // Not dim or perhaps dim and multi // Use new, efficient, good way. Only one line needed with $dimStr, which XMLSERVICE will expand for us. $innerNameStr = ($innerName) ? " var='$innerName'" : ''; // only need name if exists. If not then it's probably a "multi" and doesn't need an inner name. $paramXml .= "<data$innerNameStr type='$type'$ccsidHexStr$dimStr$enddoStr$byStr$varyingStr$labelSetLenStr$dataEndTag"; } } // if a multi-occurrence DS or scalar field, wrap in an identially named "array" DS shell. // The "array" indicator will help us parse the results on the way out. if ($isMulti) { $paramXml = "\n\n<ds var='$specialOuterDsName' comment='Multi-occur container' array='on'>\n{$paramXml}\n</ds>"; } elseif ($dim) { // if not multi but regular old-style dim, an ordinary <ds> tag will do to contain all the <data> elements. $paramXml = "\n\n<ds comment='old-style repeated data array container'>\n{$paramXml}\n</ds>"; } return $paramXml; }
Do all that's necessary to convert a single parameter into XML. Can call itself recursively for infinitely deep data structures. @param ProgramParameter $paramElement @return string
entailment
protected function updateType(&$data, $xmlServiceType) { $patterns = array('/10i0/', '/5i0/', '/4f/', '/\d*p\d*/'); $replacements = array('integer', 'integer', 'float', 'float'); // look for a match $newType = preg_replace($patterns, $replacements, $xmlServiceType); // if a different type is warranted if ($newType != $xmlServiceType) { settype($data, $newType); } }
given XMLSERVICE type such as 10i0, 5i0, 4f, 4p2, set data to the corresponding PHP type as closely as possible. Omit alpha/string because that's our default. @param $data @param $xmlServiceType
entailment
protected function getSingleParamFromXml(\SimpleXMLElement $simpleXmlElement) { // if it's too slow to set types, change it to false. $setTypes = $this->getIsCw(); // do it if in CW mode because old toolkit did return correct types $element = array(); // is this a parm, or perhaps a DS?? $elementType = $simpleXmlElement->getName(); // "name" of the XML tag is element type // if this is the outer (parm or return) element, go down one level to either ds or data. if ($elementType == 'parm' || $elementType == 'return') { if (isset($simpleXmlElement->ds)) { // get ds beneath. $simpleXmlElement = $simpleXmlElement->ds; } elseif (isset($simpleXmlElement->data)) { // get data beneath. $simpleXmlElement = $simpleXmlElement->data; } } // now we should be at a ds or data level. let's see what we have now. $elementType = $simpleXmlElement->getName(); if ($elementType == 'ds') { // call it $ds for convenience $ds = $simpleXmlElement; $subElementArray = array(); /// get info about this data structure $outerDsAttributes = $ds->attributes(); $outerDsName = (string) $outerDsAttributes['var']; // determine whether this element is to be considered a simple array $outerDsIsArray = (isset($outerDsAttributes['array']) && (strtolower($outerDsAttributes['array']) == 'on')); $outerDsIsDim = (isset($outerDsAttributes['dim']) && ($outerDsAttributes['dim'] > 1)); // look for data elements OR another ds under this ds // get every data or ds element under here. if ($underDs = $ds->xpath('data|ds')) { // we have an array of ds elements or data elements. Loop through them. foreach ($underDs as $indexNum=>$subElement) { $attrs = $subElement->attributes(); // if we're to treat outer ds as an array, // OR the subparam has no var/name for some reason, // use a numeric index as key. $givenSubelementName = (isset($attrs['var'])) ? $attrs['var'] : ''; $givenSubelementName = (string) $givenSubelementName; if ($outerDsIsArray || empty($givenSubelementName)) { $subElementName = $indexNum; } else { // else elememnt has its own var/name. $subElementName = $givenSubelementName; } // is it another ds? $elType = $subElement->getName(); // getName returns type if ($elType == 'ds') { // yes, another DS. Get contents recursively. $data = $this->getSingleParamFromXml($subElement); // ignore inner array name because we have outer numbering name. // drill down one level past inner array name. //echo "Array: " . printArray($data) . " with given name: $givenSubelementName and nametouse: $subElementName<BR>"; $data = $data[$givenSubelementName]; } else { // single data element. present its value. $data = (string) $subElement; // if $attrs['hex'] == on, decode the data. if (isset($attrs['hex']) && $attrs['hex'] == 'on') { $data = pack("H*" , $data); // reverse of bin2hex() } // if data is a DTS date that needs to be converted to a regular date. // and data is not empty or blank (hex ebcdic) if (isset($subElement['dtsdate']) && ($subElement['dtsdate'] == 'on') && $data && ($data != '4040404040404040')) { // instantiate dateTimeApi if not instantiated yet in the loop if (!isset($dateTimeApi)) { $dateTimeApi = new DateTimeApi($this->ToolkitSrvObj); } // replace DTS date with "real" date $data = $dateTimeApi->dtsToYymmdd($data); } //(if a DTS date) // @todo check performance of type casting. if ($setTypes) { $type = $attrs->type; $this->updateType($data, $type); } } // add data element to ds $subElementArray[$subElementName] = $data; } } // Set ds and its contents to be returned to caller // though if in "old" DS mode, don't include DS structure--just add elements individually (single level). // check condition: if dataStructureIntegrity global setting or NEED that integrity to interpret array/dim if ($this->getOption('dataStructureIntegrity') || $outerDsIsArray || $outerDsIsDim) { // keep $outerDsName as index for inner array $element[$outerDsName] = $subElementArray; } else { /* no data structure integrity requested. * Return without a name. Later that will be intepreted as being able to flatten the structure. * This non-inegrity feature included for backward compatibility. */ // $element[''] = $subElementArray; } } elseif ($elementType == 'data') { // we're exploring a single outer data element. return simple name/value pair $attr = $simpleXmlElement->attributes(); $dataVarName = (string)$attr->var; // name=>value $element[$dataVarName] = (string) $simpleXmlElement; // if $attr['hex'] == on, decode the data. if (isset($attr['hex']) && $attr['hex'] == 'on') { $element[$dataVarName] = pack("H*" , $element[$dataVarName]); // reverse of bin2hex() } // other types (old toolkit cast output values as correct types) if ($setTypes) { $type = $attr->type; $this->updateType($data, $type); // @todo interesting--shouldn't this be $element[$dataVarName], not $data? } // Similar to code above in "single data element under a DS" // if data is a DTS date that needs to be converted to a regular date. // and data is not empty or blank (hex ebcdic) // @todo could convert 4040 into blanks if (isset($attr->dtsdate) && (((string) $attr->dtsdate) == 'on') && $element[$dataVarName] && ($element[$dataVarName] != '4040404040404040')) { if (!isset($dateTimeApi)) { $dateTimeApi = new DateTimeApi($this->ToolkitSrvObj); } // replace DTS date with "real" date $element[$dataVarName] = $dateTimeApi->dtsToYymmdd($element[$dataVarName]); } } return $element; }
Parse a piece of XML representing a single parameter (whether output or return type). Can all itself recursively for infinitely deep data structures. Returns an array containing nested key/value pairs for the parameter. typical XML program call <script> <pgm name='ZZCALL'> <parm> <data type='1A'>a</data> </parm> <parm> <data type='2s'>23</data> </parm> <return> <data type='10i0' comment='Could be a data structure, too'>0</data> </return> </pgm> </script> @param \SimpleXMLElement $simpleXmlElement @return array
entailment
public function getParamsFromXml($xml) { // initialize results array to empty arrays for both regular in/out params and return params $callResults = array('io_param'=>array(), 'retvals'=>array()); $xmlobj = simplexml_load_string($xml); // note: outer, ignored node name will be <script> (if successful call) // or <report> (if unsuccessful) // Outer node is discarded in parsed XML objects. if (!$xmlobj instanceof \SimpleXMLElement) { $badXmlLog = '/tmp/bad.xml'; $this->error = "Unable to parse output XML, which has been logged in $badXmlLog. Possible problems: CCSID, encoding, binary data in an alpha field (use binary/BYTE type instead); if < or > are the problem, consider using CDATA tags."; error_log($xml, 3, $badXmlLog); return false; } if (isset($xmlobj->error)) { // capture XML error and joblog. // In PgmCall method we will try to get a better error than the XML error. $this->error =(string)$xmlobj->error->xmlerrmsg . ' (' . (string)$xmlobj->error->xmlhint . ')'; $this->joblog = (string)$xmlobj->joblog; return false; } // array to provide both 'io_param/parm' and 'retvals/return' parameter types. $xmlParamElements = array(); // get XML elements for regular input/output parameters $xmlParamElements['io_param'] = $xmlobj->xpath('/script/pgm/parm'); // get XML elements for return parameter(s) $xmlParamElements['retvals'] = $xmlobj->xpath('/script/pgm/return'); // read through elements foreach ($xmlParamElements as $paramType=>$elements) { // within a given element type (parm or return) foreach ($elements as $simpleXmlElement) { // pass parms into a recursive function to get ds/data elements // process and get value(s) from that parm. $param = $this->getSingleParamFromXml($simpleXmlElement); // Append this single element (a key=>value pair) to the proper array. // $paramType will be 'io_param' or 'retvals'. $paramName = key($param); $paramValue = $param[$paramName]; // if it's a flattened data structure (i.e. without data structure integrity), // add the individual elements instead of the structure. if ($paramName) { $callResults[$paramType][$paramName] = $paramValue; } else { // structure name is blank. Append array elements as if they were separate values. // (Backward compability with original new toolkit behavior) if ($paramValue) { // nonempty foreach ($paramValue as $subFieldName=>$subFieldValue) { $callResults[$paramType][$subFieldName] = $subFieldValue; } } } } } return $callResults; }
Given the full XML received from XMLSERVICE program call, parse it into an array of parameter key/value pairs (can be nested if complex DSes) ready to use. The array will contain both 'io_param' (regular output params) and 'retvals' (return param) elements. sample <parm io='both' comment='PS'> <ds var='PS' array='on'> <ds var='PS_0'> <data var='PS1' type='10a' varying='off'>test1</data> <data var='PS2' type='10a' varying='off'>test2</data> <data var='PS3' type='10a' varying='off'>test3</data> </ds> <ds var='PS_1'> <data var='PS1' type='10a' varying='off'>test3</data> <data var='PS2' type='10a' varying='off'>test4</data> <data var='PS3' type='10a' varying='off'>test5</data> </ds> </ds> </parm> </pgm> @param $xml @return array
entailment
public function buildCommandXmlIn($cmd, $exec = 'pase') { $xmlIn = ''; // get hex/ccsid information to pass along on the command. $propArray = array(); $this->processParamProps($propArray); $ccsidHexStr = "{$propArray['ccsidStr']}{$propArray['hexStr']}"; // if a string, make a single-item array from it. if (is_string($cmd)) { $cmdArray = array($cmd); } else { // already multiple. $cmdArray = $cmd; } foreach ($cmdArray as $oneCmd) { // Run PASE utility 'system', which runs an IBM i native command. // We call this an "interactive" command because it can return output from DSP* interactive commands. // Use double quotes around $cmd so that $cmd can safely contain single quotes. if ($exec == 'pase') { // -i is nice. @todo test speed $oneCmd = '/QOpenSys/usr/bin/system "' . $oneCmd . '"'; } // if need to convert to hex, do so. $encodedCmd = $this->encodeString($oneCmd); // with pase and pasecmd is <sh, not <cmd. // inner command depends on what was passed in. if ($exec == 'pase' || $exec == 'pasecmd') { $xmlIn .= "<sh rows='on'$ccsidHexStr>$encodedCmd</sh>"; } else { // Not a "<sh>" tag. Try one of the cmd exec= command styles. // check that our exec value is in whitelist. // blank is a synonym for default of cmd. if ($exec && in_array($exec, $this->_cmdTypes)) { $execStr = " exec='$exec'"; // e.g. <cmd exec='rexx'> } else { $execStr = ''; // OK because blank string defaults to cmd on XMLSERVICE side } $xmlIn .= "<cmd$execStr$ccsidHexStr>$encodedCmd</cmd>"; } } return $this->addOuterTags($xmlIn); }
It's more efficient to run multiple commands with one XMLSERVICE call than to do many calls @param array $cmd string will be turned into an array @param string $exec @return string
entailment
public function getCmdResultFromXml($xml, $parentTag = 'sh') { $this->error = ''; $xmlobj = simplexml_load_string($xml); if (!$xmlobj instanceof \SimpleXMLElement) { /*bad xml returned*/ $this->error = "Can't read output xml"; error_log($xml, 3, '/tmp/bad.xml'); return false; } $retval = true; // assume OK unless error found. Was false, but sh doesn't return success flag. $params = $xmlobj->xpath("/script/$parentTag"); foreach ($params as $simpleXMLElement) { // Note: there may be multiple ->error tags if (isset($simpleXMLElement->error)) {//*** error // newer way in XMLSERVICE ///bookstore/book[last()] // get last joblogscan/joblogrec nested tags in the XML section. Returned as one-element array. function 'current' returns the one element. $lastJoblogTag = current($simpleXMLElement->xpath("joblogscan/joblogrec[last()]")); // if last job log tag contained a real CPF-style code, of length 7 (e.g. CPF1234), parsed for us. if ($lastJoblogTag && isset($lastJoblogTag->jobcpf) && (strlen($lastJoblogTag->jobcpf) == 7)) { $this->cpfErr = (string) $lastJoblogTag->jobcpf; $this->error = $this->cpfErr; // ->error has ambiguous meaning. Include for backward compatibility. $this->errorText = (string) $lastJoblogTag->jobtext; $retval = false; break; } /** * <joblogscan> * <joblogrec> * <jobcpf>CPF1124</jobcpf> * <jobtime><![CDATA[10/11/12 19:33:54.102423]]></jobtime> * <jobtext><![CDATA[Job 127257/ASEIDEN/XTOOLKIT started on 10/11/12 at Job 127257/ASEIDEN/XTOOLKIT submitted.]]></jobtext> * </joblogrec> * <joblogrec> * <jobcpf>*NONE</jobcpf> * <jobtime><![CDATA[10/11/12 19:33:54.102423]]></jobtime> * <jobtext><![CDATA[CALL PGM(XMLSERVICE/XMLSERVICE) PARM('/tmp/ASEIDEN_abc')]]></jobtext> * </joblogrec> * <joblogrec> * <jobcpf>CPF3142</jobcpf> * <jobtime><![CDATA[10/11/12 19:33:54.102423]]></jobtime> * <jobtext><![CDATA[PLUGILE ILECMDEXC 5116 File NONEXIST in library *LIBL not found.]]></jobtext> * </joblogrec> * </joblogscan> */ // xpath(joblogscan/joblogrec[last()]) // then ->jobcpf and ->jobtext // Note: there may be multiple ->error tags // As of XMLSERVICE 1.60: // array element[0] is probably the *** error text. // array element[1] may be the CPF code (not likely). if (isset($simpleXMLElement->error[1])) { $this->error = (string) $simpleXMLElement->error[1]; } else { $this->error = "Command execute failed."; } //$err = (string )$simpleXMLElement->error; // there's an error code of some kind. use it. // A change: get rid of standard msg. Only return the err, which may be a CPF. //$this->error = "Command execute failed. ".$err; $retval = false; break; } // Older style. Now, *** error appears in ->error tag if (strstr(((string)$simpleXMLElement),"*** error")){ // this message is a generic failure so it's OK. $this->error = "Command execute failed. "; $retval = false; break; } // in the case of interactive commands, there may be no "success" msg. if (isset($simpleXMLElement->success)) { $retval = true; break; } // Older style. Now, +++ success appears in ->success tag if (strstr(((string)$simpleXMLElement),"+++ success")) { $retval = true; break; } } return $retval; }
gets any error code and sets it in toolkit. returns true or false depending on interpretation of status @param $xml @param string $parentTag @return bool
entailment
public function getRowsFromXml($xml, $parent = 'sh') { $this->error = ''; $values = array(); $xmlobj = @simplexml_load_string($xml); if (!$xmlobj instanceof \SimpleXMLElement) { /* bad xml returned*/ $this->error = "Can't read output xml"; return false; } // get all rows of data $params = $xmlobj->xpath("/script/$parent/row"); // get data for each row found. foreach ($params as $simpleXMLElement) { // If hex, get data from script->$parent->hex // Then can un-hex (pack) that and do simplexml load string on it, and proceed as below afterward. // Examples from XMLSERVICE documentation: http://174.79.32.155/wiki/index.php/XMLSERVICE/XMLSERVICECCSID // if hex info was sent back // <sh rows='on' hex='on' before='819/37' after='37/819'> // <row><hex>746F74616C2031363636313034</hex></row> // </sh> /* <cmd exec='rexx' hex='on' before='819/37' after='37/819'> * <success><![CDATA[+++ success RTVJOBA USRLIBL(?) SYSLIBL(?)]]></success> * <row><data desc='USRLIBL'><hex><![CDATA[5147504C20202020202020]]></hex></data></row> * <row><data desc='SYSLIBL'><hex><![CDATA[5153595320202020202020]]></hex></data></row> * </cmd> */ // if there's a data element, go down one level to it (->data). $element = (isset($simpleXMLElement->data)) ? $simpleXMLElement->data : $simpleXMLElement; // if a hex tag is present, de-hex (pack) the data inside that hex tag; otherwise, use the outer element's value directly. $data = (isset($element->hex)) ? pack("H*", (string)$element->hex) : (string)$element; // process data string received, then add to $values array. // rows will either be from parent 'cmd' or 'sh'. if ($parent == 'cmd') { // for RTV* commands, // attribute 'desc' of data tag will hold the output field name to which the data belongs. $outputFieldName = (string) $element->attributes()->desc; $data = trim($data, " \n"); // trim spaces and end-of-line chars of data that comes from REXX RTV* commands ('cmd') $values[$outputFieldName] = $data; } else { // 'sh' $values[] = $data; // no particular index } } if (count($params)==0) { $this->error = "No rows"; $params = $xmlobj->xpath("/script/$parent"); foreach ($params as $simpleXMLElement) { if (strstr(((string)$simpleXMLElement),"+++ no output")) { $this->error = "Command does not return output"; } break; } } return $values; }
Get rows from command output. @param $xml @param string $parent @return array
entailment
public function singlePcmlToParam(\SimpleXmlElement $dataElement) { $tagName = $dataElement->getName(); // get attributes of this element. $attrs = $dataElement->attributes(); // both struct and data have name, count (optional), usage $name = (isset($attrs['name'])) ? (string) $attrs['name'] : ''; $count = (isset($attrs['count'])) ? (string) $attrs['count'] : ''; $usage = (isset($attrs['usage'])) ? (string) $attrs['usage'] : ''; $structName = (isset($attrs['struct'])) ? (string) $attrs['struct'] : ''; // fill this if we have a struct $subElements = array(); // each item should have tag name <data> if ($tagName != 'data') { return false; } $type = (isset($attrs['type'])) ? (string) $attrs['type'] : ''; // Get initial value, if specified by PCML. $dataValue = (isset($attrs['init'])) ? (string) $attrs['init'] : ''; // if a struct then we need to recurse. if ($type == 'struct') { $theStruct = null; // init // look for matching struct definition encountered earlier. if ($this->_pcmlStructs) { // @todo verify type with is_array and count foreach ($this->_pcmlStructs as $possibleStruct) { $possStructAttrs = $possibleStruct->attributes(); if ($possStructAttrs['name'] == $structName) { $theStruct = $possibleStruct; $structAttrs = $possStructAttrs; break; } } } // if struct was not found, generate error for log if (!$theStruct) { // $this->getConnection->logThis("PCML structure '$structName' not found."); return null; } // count can also be defined at the structure level. If so, it will override count from data level) if (isset($structAttrs['count'])) { $count = (string) $structAttrs['count']; } // "usage" (in/out/inherit) can be defined here, at the structure level. $structUsage = (isset($structAttrs['usage'])) ? (string) $structAttrs['usage'] : ''; // if we're not inheriting from our parent data element, but there is a struct usage, use the struct's usage (input, output, or inputoutput). if (!empty($structUsage) && ($structUsage != 'inherit')) { $usage = $structUsage; } $structSubDataElementsXmlObj = $theStruct->xpath('data'); if ($structSubDataElementsXmlObj) { foreach ($structSubDataElementsXmlObj as $subDataElementXmlObj) { if ($subDataElementXmlObj->attributes()->usage == 'inherit') { // subdata is inheriting type from us. Give it to them. $subDataElementXmlObj->attributes()->usage = $usage; } // here's where the recursion comes in. Convert data and add to array for our struct. $subElements[] = $this->singlePcmlToParam($subDataElementXmlObj); } } } /* explanation of the terms "length" and "precision" in PCML: * http://publib.boulder.ibm.com/infocenter/iadthelp/v6r0/index.jsp?topic=/com.ibm.etools.iseries.webtools.doc/ref/rdtcattr.htm * * For "int" values, length is the number of bytes; precision represents the number of bits. (Can be ignored here) * For zoned and packed values, length is the maximum number of digits; precision represents the maximum decimal places. * */ $length = (isset($attrs['length'])) ? (string) $attrs['length'] : ''; $precision = (isset($attrs['precision'])) ? (string) $attrs['precision'] : ''; $passBy = ''; // default of blank will become 'ref'/Reference in XMLSERVICE. Blank is fine here. if (isset($attrs['passby']) && ($attrs['passby'] == 'value')) { $passBy = 'val'; // rare. PCML calls it 'value'. XMLSERVICE calls it 'val'. } // find new toolkit equivalent of PCML data type if (isset($this->_pcmlTypeMap[$type])) { // a simple type mapping $newType = (string) $this->_pcmlTypeMap[$type]; } elseif ($type == 'int') { // one of the integer types. Need to use length to determine which one. if ($length == '2') { $newType = '5i0'; // short ints have two bytes } elseif ($length == '4') { $newType = '10i0'; // normal ints have four bytes } else { $newType = ''; // no match } //(length == 2, et al.) } else { $newType = ''; } $newInout = (isset($this->_pcmlInoutMap[$usage])) ? (string) $this->_pcmlInoutMap[$usage] : ''; // @todo correct all this isArray business. // Can we manage without isArray? // well, it's already handled by toolkit....try and see, though. // poss. eliminate extra object levels, at least? if ($count > 1) { $isArray = true; } else { // no need for any dummy value.Could be 'init' from above, or leave the default. $isArray = false; } // @todo I think simply add 'counterLabel' and 'countedLabel'. // count $newCount = 0; // initialize // @todo deal with this. Really need a better way to find the counter data elements. // Allow a countref, too, in PCML??? Maybe! Count will be the dim (max) and countref is the actual name. // Some customers have done it wrong. Instead of specifying a field as count, gave max count. // "count can be a number where number defines a fixed, never-changing number of elements in a sized array. // OR a data-name where data-name defines the name of a <data> element within the PCML document that will contain, at runtime, the number of elements in the array. The data-name specified can be a fully qualified name or a name that is relative to the current element. In either case, the name must reference a <data> element that is defined with type="int". See Resolving Relative Names for more information about how relative names are resolved. // about finding the element: http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Frzahh%2Flengthprecisionrelative.htm // Names are resolved by seeing if the name can be resolved as a child or descendent of the tag containing the current tag. If the name cannot be resolved at this level, the search continues with the next highest containing tag. This resolution must eventually result in a match of a tag that is contained by either the <pcml> tag or the <rfml> tag, in which case the name is considered to be an absolute name, not a relative name."" // Let's simply use $countersAndCounted. If necessary, pre-process PCML to create $countersAndCounted. if (is_numeric($count) && ($count > 0)) { $newCount = $count; } // $subElements are if this is a struct. if (count($subElements)) { $dataValue = $subElements; } $param = new ProgramParameter(sprintf($newType, $length, $precision), $newInout, '', $name, $dataValue, 'off', $newCount, $passBy, $isArray); if ($this->_countersAndCounted) { // some counters were configured // counter item reference was specified. if (isset($this->_countersAndCounted[$name])) { $param->setParamLabelCounter($name); } // counted item reference was specified as value in array. // look for value ($name). if found, counter is key. if ($counter = array_search($name, $this->_countersAndCounted)) { $param->setParamLabelCounted($counter); } } return $param; }
given a single ->data or ->struct element, return a parameter object in the new toolkit style. @todo this needs more validation. It is possible that all parts are not set to create return @param \SimpleXmlElement $dataElement @return ProgramParameter
entailment
public function initDappur() { echo $this->logEntry("Initializing Dappur Framework..."); $this->validateDocumentRoot(); $this->installUpdateComposer(); $this->checkGit(); $this->checkInstallRepo(); $this->checkPhinx(); $this->migrateUp(); echo $this->logEntry("Framework initialization complete."); }
Initialize Dappur
entailment
public function execute() { echo $this->logEntry("Checking requirements..."); $this->validateDocumentRoot(); $this->installUpdateComposer(); $this->checkGit(); $this->checkInstallRepo(); $this->checkConnection(); echo $this->logEntry("Requirements validated!"); }
Execute
entailment