/** * Returns stream only including * lines from the original stream which don't start with any of the * specified comment prefixes. * * @param null $len * @return mixed the resulting stream, or -1 * if the end of the resulting stream has been reached. * */ public function read($len = null) { if (!$this->getInitialized()) { $this->_initialize(); $this->setInitialized(true); } $buffer = $this->in->read($len); if ($buffer === -1) { return -1; } $lines = explode("\n", $buffer); $filtered = array(); $commentsSize = count($this->_comments); foreach ($lines as $line) { for ($i = 0; $i < $commentsSize; $i++) { $comment = $this->_comments[$i]->getValue(); if (StringHelper::startsWith($comment, ltrim($line))) { $line = null; break; } } if ($line !== null) { $filtered[] = $line; } } $filtered_buffer = implode("\n", $filtered); return $filtered_buffer; }
/** * Returns next query from SQL source, null if no more queries left * * In case of "row" delimiter type this searches for strings containing only * delimiters. In case of "normal" delimiter type, this uses simple regular * expression logic to search for delimiters. * * @return string|null */ public function nextQuery() { $sql = ""; $hasQuery = false; while (($line = $this->sqlReader->readLine()) !== null) { $delimiter = $this->parent->getDelimiter(); $project = $this->parent->getOwningTarget()->getProject(); $line = ProjectConfigurator::replaceProperties($project, trim($line), $project->getProperties()); if ($line != $delimiter && (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line))) { continue; } if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { continue; } // MySQL supports defining new delimiters if (preg_match('/DELIMITER [\'"]?([^\'" $]+)[\'"]?/i', $line, $matches)) { $this->parent->setDelimiter($matches[1]); continue; } if ($this->sqlBacklog !== "") { $sql = $this->sqlBacklog; $this->sqlBacklog = ""; } $sql .= " " . $line . "\n"; // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (strpos($line, "--") !== false) { $sql .= "\n"; } // DELIM_ROW doesn't need this (as far as i can tell) if ($this->delimiterType == PDOSQLExecTask::DELIM_NORMAL) { $reg = "#((?:\"(?:\\\\.|[^\"])*\"?)+|'(?:\\\\.|[^'])*'?|" . preg_quote($delimiter) . ")#"; $sqlParts = preg_split($reg, $sql, 0, PREG_SPLIT_DELIM_CAPTURE); $this->sqlBacklog = ""; foreach ($sqlParts as $sqlPart) { // we always want to append, even if it's a delim (which will be stripped off later) $this->sqlBacklog .= $sqlPart; // we found a single (not enclosed by ' or ") delimiter, so we can use all stuff before the delim as the actual query if ($sqlPart === $delimiter) { $sql = $this->sqlBacklog; $this->sqlBacklog = ""; $hasQuery = true; } } } if ($hasQuery || $this->delimiterType == PDOSQLExecTask::DELIM_ROW && $line == $delimiter) { // this assumes there is always a delimter on the end of the SQL statement. $sql = StringHelper::substring($sql, 0, strlen($sql) - strlen($delimiter) - ($this->delimiterType == PDOSQLExecTask::DELIM_ROW ? 2 : 1)); return $sql; } } // Catch any statements not followed by ; if ($sql !== "") { return $sql; } return null; }
function main($_sourceFileName) { if ($this->fromPrefix === null || !StringHelper::startsWith($this->fromPrefix, $_sourceFileName) || !StringHelper::endsWith($this->fromPostfix, $_sourceFileName)) { return null; } $varpart = $this->_extractVariablePart($_sourceFileName); $substitution = $this->toPrefix . $varpart . $this->toPostfix; return array($substitution); }
public static function MaskCheck($item, $masks) { $maskCheck = false; foreach ($masks as $mask) { if (\StringHelper::startsWith($item, $mask) || \StringHelper::endsWith($item, $mask)) { $maskCheck = true; } } return $maskCheck; }
function normalizeSlashes($path) { // Url must not end with slash while (StringHelper::endsWith($path, '/')) { $path = substr($path, 0, -1); } // Url must start with slash if (!StringHelper::startsWith($path, '/')) { $path = '/' . $path; } return $path; }
public function execute(IWebRequest $request, IWebResponse $response) { $this->model->setTemplateName($this->getTemplateName()); $this->model->setFeeding($this->feedingRepository->getInProgress()); $feeding = $this->model->getFeeding(); if ($feeding->hasBottle() && !$this->stringHelper->startsWith($request->path(), '/bottle')) { $response->redirect('/bottle'); } else { if ($feeding->hasMilking() && !$this->stringHelper->startsWith($request->path(), '/milking')) { $response->redirect('/milking'); } else { if ($feeding->hasBreastFeeding() && !$this->stringHelper->startsWith($request->path(), '/breast')) { $response->redirect('/breast'); } else { if ($feeding->hasDiaper() && !$this->stringHelper->startsWith($request->path(), '/diaper')) { $response->redirect('/diaper'); } } } } return $this->model; }
/** * Returns entire SQL source * * @return string|null */ public function nextQuery() { $sql = null; while (($line = $this->sqlReader->readLine()) !== null) { $delimiter = $this->parent->getDelimiter(); $project = $this->parent->getOwningTarget()->getProject(); $line = ProjectConfigurator::replaceProperties($project, trim($line), $project->getProperties()); if ($line != $delimiter && (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line))) { continue; } $sql .= " " . $line . "\n"; } return $sql; }
/** * Does the work. * * @throws BuildException if someting goes wrong with the build */ public final function main() { if ($this->cvsRoot === null) { throw new BuildException("cvsroot is required"); } if ($this->password === null) { throw new BuildException("password is required"); } $this->log("cvsRoot: " . $this->cvsRoot, Project::MSG_DEBUG); $this->log("password: "******"passFile: " . $this->passFile->__toString(), Project::MSG_DEBUG); $reader = null; $writer = null; try { $buf = ""; if ($this->passFile->exists()) { $reader = new BufferedReader(new FileReader($this->passFile)); $line = null; while (($line = $reader->readLine()) !== null) { if (!StringHelper::startsWith($this->cvsRoot, $line)) { $buf .= $line . PHP_EOL; } } } $pwdfile = $buf . $this->cvsRoot . " A" . $this->mangle($this->password); $this->log("Writing -> " . $pwdfile, Project::MSG_DEBUG); $writer = new BufferedWriter(new FileWriter($this->passFile)); $writer->write($pwdfile); $writer->newLine(); $writer->close(); if ($reader) { $reader->close(); } } catch (IOException $e) { if ($reader) { try { $reader->close(); } catch (Exception $e) { } } if ($writer) { try { $writer->close(); } catch (Exception $e) { } } throw new BuildException($e); } }
function evaluate() { $osName = strtolower(Phing::getProperty("os.name")); if ($this->family !== null) { if ($this->family === "windows") { return StringHelper::startsWith("win", $osName); } elseif ($this->family === "mac") { return strpos($osName, "mac") !== false || strpos($osName, "darwin") !== false; } elseif ($this->family === "unix") { return StringHelper::endsWith("ix", $osName) || StringHelper::endsWith("ux", $osName) || StringHelper::endsWith("bsd", $osName) || StringHelper::startsWith("sunos", $osName) || StringHelper::startsWith("darwin", $osName); } throw new BuildException("Don't know how to detect os family '" . $this->family . "'"); } return false; }
/** * Returns entire SQL source * * @return string|null */ public function nextQuery() { $sql = null; while (($line = $this->sqlReader->readLine()) !== null) { $delimiter = $this->parent->getDelimiter(); $project = $this->parent->getOwningTarget()->getProject(); $line = ProjectConfigurator::replaceProperties($project, trim($line), $project->getProperties()); if ($line != $delimiter && (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line))) { continue; } $sql .= " " . $line . "\n"; /** * fix issue with PDO and wrong formated multistatements * @issue 1108 */ if (StringHelper::endsWith($delimiter, $line)) { break; } } return $sql; }
/** * Tests whether or not a given path matches the start of a given * pattern up to the first "**". * <p> * This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>. * * @param string $pattern * @param string $str * @param bool $isCaseSensitive * * @internal param The $pattern pattern to match against. Must not be * <code>null</code>. * @internal param The $str path to match, as a String. Must not be * <code>null</code>. * @internal param Whether $isCaseSensitive or not matching should be performed * case sensitively. * * @return bool whether or not a given path matches the start of a given * pattern up to the first "**". */ public static function matchPatternStart($pattern, $str, $isCaseSensitive = true) { // When str starts with a DIRECTORY_SEPARATOR, pattern has to start with a // DIRECTORY_SEPARATOR. // When pattern starts with a DIRECTORY_SEPARATOR, str has to start with a // DIRECTORY_SEPARATOR. if (StringHelper::startsWith(DIRECTORY_SEPARATOR, $str) !== StringHelper::startsWith(DIRECTORY_SEPARATOR, $pattern)) { return false; } $patDirs = explode(DIRECTORY_SEPARATOR, $pattern); $strDirs = explode(DIRECTORY_SEPARATOR, $str); $patIdxStart = 0; $patIdxEnd = count($patDirs) - 1; $strIdxStart = 0; $strIdxEnd = count($strDirs) - 1; // up to first '**' while ($patIdxStart <= $patIdxEnd && $strIdxStart <= $strIdxEnd) { $patDir = $patDirs[$patIdxStart]; if ($patDir == "**") { break; } if (!self::match($patDir, $strDirs[$strIdxStart], $isCaseSensitive)) { return false; } $patIdxStart++; $strIdxStart++; } if ($strIdxStart > $strIdxEnd) { // String is exhausted return true; } elseif ($patIdxStart > $patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } else { // pattern now holds ** while string is not exhausted // this will generate false positives but we can live with that. return true; } }
/** * Read the statements from the .sql file and execute them. * Lines starting with '//', '--' or 'REM ' are ignored. * * Developer note: must be public in order to be called from * sudo-"inner" class PropelSQLExecTransaction. * * @param Reader $reader * @param $out Optional output stream. * @throws SQLException * @throws IOException */ public function runStatements(Reader $reader, $out = null) { $sql = ""; $line = ""; $sqlBacklog = ""; $hasQuery = false; $in = new BufferedReader($reader); try { while (($line = $in->readLine()) !== null) { $line = trim($line); $line = ProjectConfigurator::replaceProperties($this->project, $line, $this->project->getProperties()); if (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line)) { continue; } if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { continue; } if ($sqlBacklog !== "") { $sql = $sqlBacklog; $sqlBacklog = ""; } $sql .= " " . $line . "\n"; // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (strpos($line, "--") !== false) { $sql .= "\n"; } // DELIM_ROW doesn't need this (as far as i can tell) if ($this->delimiterType == self::DELIM_NORMAL) { $reg = "#((?:\"(?:\\\\.|[^\"])*\"?)+|'(?:\\\\.|[^'])*'?|" . preg_quote($this->delimiter) . ")#"; $sqlParts = preg_split($reg, $sql, 0, PREG_SPLIT_DELIM_CAPTURE); $sqlBacklog = ""; foreach ($sqlParts as $sqlPart) { // we always want to append, even if it's a delim (which will be stripped off later) $sqlBacklog .= $sqlPart; // we found a single (not enclosed by ' or ") delimiter, so we can use all stuff before the delim as the actual query if ($sqlPart === $this->delimiter) { $sql = $sqlBacklog; $sqlBacklog = ""; $hasQuery = true; } } } if ($hasQuery || $this->delimiterType == self::DELIM_ROW && $line == $this->delimiter) { // this assumes there is always a delimter on the end of the SQL statement. $sql = StringHelper::substring($sql, 0, strlen($sql) - 1 - strlen($this->delimiter)); $this->log("SQL: " . $sql, PROJECT_MSG_VERBOSE); $this->execSQL($sql, $out); $sql = ""; $hasQuery = false; } } // Catch any statements not followed by ; if ($sql !== "") { $this->execSQL($sql, $out); } } catch (SQLException $e) { throw $e; } }
/** * Setup/initialize Phing environment from commandline args. * @param array $args commandline args passed to phing shell. * @return void */ public function execute($args) { self::$definedProps = new Properties(); $this->searchForThis = null; // 1) First handle any options which should always // Note: The order in which these are executed is important (if multiple of these options are specified) if (in_array('-help', $args) || in_array('-h', $args)) { $this->printUsage(); return; } if (in_array('-version', $args) || in_array('-v', $args)) { $this->printVersion(); return; } // 2) Next pull out stand-alone args. // Note: The order in which these are executed is important (if multiple of these options are specified) if (false !== ($key = array_search('-quiet', $args, true))) { self::$msgOutputLevel = Project::MSG_WARN; unset($args[$key]); } if (false !== ($key = array_search('-verbose', $args, true))) { self::$msgOutputLevel = Project::MSG_VERBOSE; unset($args[$key]); } if (false !== ($key = array_search('-debug', $args, true))) { self::$msgOutputLevel = Project::MSG_DEBUG; unset($args[$key]); } // 3) Finally, cycle through to parse remaining args // $keys = array_keys($args); // Use keys and iterate to max(keys) since there may be some gaps $max = $keys ? max($keys) : -1; for ($i = 0; $i <= $max; $i++) { if (!array_key_exists($i, $args)) { // skip this argument, since it must have been removed above. continue; } $arg = $args[$i]; if ($arg == "-logfile") { try { // see: http://phing.info/trac/ticket/65 if (!isset($args[$i + 1])) { $msg = "You must specify a log file when using the -logfile argument\n"; throw new ConfigurationException($msg); } else { $logFile = new PhingFile($args[++$i]); $out = new FileOutputStream($logFile); // overwrite self::setOutputStream($out); self::setErrorStream($out); self::$isLogFileUsed = true; } } catch (IOException $ioe) { $msg = "Cannot write on the specified log file. Make sure the path exists and you have write permissions."; throw new ConfigurationException($msg, $ioe); } } elseif ($arg == "-buildfile" || $arg == "-file" || $arg == "-f") { if (!isset($args[$i + 1])) { $msg = "You must specify a buildfile when using the -buildfile argument."; throw new ConfigurationException($msg); } else { $this->buildFile = new PhingFile($args[++$i]); } } elseif ($arg == "-listener") { if (!isset($args[$i + 1])) { $msg = "You must specify a listener class when using the -listener argument"; throw new ConfigurationException($msg); } else { $this->listeners[] = $args[++$i]; } } elseif (StringHelper::startsWith("-D", $arg)) { $name = substr($arg, 2); $value = null; $posEq = strpos($name, "="); if ($posEq !== false) { $value = substr($name, $posEq + 1); $name = substr($name, 0, $posEq); } elseif ($i < count($args) - 1 && !StringHelper::startsWith("-D", $arg)) { $value = $args[++$i]; } self::$definedProps->setProperty($name, $value); } elseif ($arg == "-logger") { if (!isset($args[$i + 1])) { $msg = "You must specify a classname when using the -logger argument"; throw new ConfigurationException($msg); } else { $this->loggerClassname = $args[++$i]; } } elseif ($arg == "-inputhandler") { if ($this->inputHandlerClassname !== null) { throw new ConfigurationException("Only one input handler class may be specified."); } if (!isset($args[$i + 1])) { $msg = "You must specify a classname when using the -inputhandler argument"; throw new ConfigurationException($msg); } else { $this->inputHandlerClassname = $args[++$i]; } } elseif ($arg == "-longtargets") { self::$definedProps->setProperty('phing.showlongtargets', 1); } elseif ($arg == "-projecthelp" || $arg == "-targets" || $arg == "-list" || $arg == "-l" || $arg == "-p") { // set the flag to display the targets and quit $this->projectHelp = true; } elseif ($arg == "-find") { // eat up next arg if present, default to build.xml if ($i < count($args) - 1) { $this->searchForThis = $args[++$i]; } else { $this->searchForThis = self::DEFAULT_BUILD_FILENAME; } } elseif (substr($arg, 0, 1) == "-") { // we don't have any more args self::$err->write("Unknown argument: {$arg}" . PHP_EOL); self::printUsage(); return; } else { // if it's no other arg, it may be the target array_push($this->targets, $arg); } } // if buildFile was not specified on the command line, if ($this->buildFile === null) { // but -find then search for it if ($this->searchForThis !== null) { $this->buildFile = $this->_findBuildFile(self::getProperty("user.dir"), $this->searchForThis); } else { $this->buildFile = new PhingFile(self::DEFAULT_BUILD_FILENAME); } } // make sure buildfile exists if (!$this->buildFile->exists()) { throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " does not exist!"); } // make sure it's not a directory if ($this->buildFile->isDirectory()) { throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " is a dir!"); } $this->readyToRun = true; }
function resolveFile(PhingFile $f) { $path = $f->getPath(); $pl = (int) $f->getPrefixLength(); if ($pl === 2 && $path[0] === $this->slash) { return path; // UNC } if ($pl === 3) { return $path; // Absolute local } if ($pl === 0) { return (string) ($this->_getUserPath() . $this->slashify($path)); //Completely relative } if ($pl === 1) { // Drive-relative $up = (string) $this->_getUserPath(); $ud = (string) $this->_getDrive($up); if ($ud !== null) { return (string) $ud . $path; } return (string) $up . $path; //User dir is a UNC path } if ($pl === 2) { // Directory-relative $up = (string) $this->_getUserPath(); $ud = (string) $this->_getDrive($up); if ($ud !== null && StringHelper::startsWith($ud, $path)) { return (string) ($up . $this->slashify(substr($path, 2))); } $drive = (string) $path[0]; $dir = (string) $this->_getDriveDirectory($drive); $np = (string) ""; if ($dir !== null) { /* When resolving a directory-relative path that refers to a drive other than the current drive, insist that the caller have read permission on the result */ $p = (string) $drive . (':' . $dir . $this->slashify(substr($path, 2))); if (!$this->checkAccess($p, false)) { // FIXME // throw security error die("Can't resolve path {$p}"); } return $p; } return (string) $drive . ':' . $this->slashify(substr($path, 2)); //fake it } throw new Exception("Unresolvable path: " . $path); }
/** * * Enter description here ... * @param PhingFile|string $path * @param boolean $isDirectory * @return string */ public function _slashify($path, $isDirectory) { $p = (string) $path; if (self::$separator !== '/') { $p = str_replace(self::$separator, '/', $p); } if (!StringHelper::startsWith('/', $p)) { $p = '/' . $p; } if (!StringHelper::endsWith('/', $p) && $isDirectory) { $p = $p . '/'; } return $p; }
/** * Create a relative path from one path to another. * * @param string $from * @param string $to * @return string */ public static function getRelative($from, $to) { $from = self::getAbsolute($from); $to = self::getAbsolute($to); $relative = ""; while ($from && $from !== $to && !StringHelper::startsWith($to, $from . '/')) { $relative .= '../'; $from = dirname($from); if ($from == '/') { break; } } if ($from !== $to) { $relative .= substr($to, strlen($from) + 1) . '/'; } return $relative; }
/** * Normalize the given absolute path. * * This includes: * - Uppercase the drive letter if there is one. * - Remove redundant slashes after the drive spec. * - resolve all ./, .\, ../ and ..\ sequences. * - DOS style paths that start with a drive letter will have * \ as the separator. * @param string $path Path to normalize. * @return string */ function normalize($path) { $path = (string) $path; $orig = $path; $path = str_replace('/', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, $path)); // make sure we are dealing with an absolute path if (!StringHelper::startsWith(DIRECTORY_SEPARATOR, $path) && !(strlen($path) >= 2 && Character::isLetter($path[0]) && $path[1] === ':')) { throw new IOException("{$path} is not an absolute path"); } $dosWithDrive = false; $root = null; // Eliminate consecutive slashes after the drive spec if (strlen($path) >= 2 && Character::isLetter($path[0]) && $path[1] === ':') { $dosWithDrive = true; $ca = str_replace('/', '\\', $path); $ca = StringHelper::toCharArray($ca); $path = strtoupper($ca[0]) . ':'; for ($i = 2, $_i = count($ca); $i < $_i; $i++) { if ($ca[$i] !== '\\' || $ca[$i] === '\\' && $ca[$i - 1] !== '\\') { $path .= $ca[$i]; } } $path = str_replace('\\', DIRECTORY_SEPARATOR, $path); if (strlen($path) == 2) { $root = $path; $path = ""; } else { $root = substr($path, 0, 3); $path = substr($path, 3); } } else { if (strlen($path) == 1) { $root = DIRECTORY_SEPARATOR; $path = ""; } else { if ($path[1] == DIRECTORY_SEPARATOR) { // UNC drive $root = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR; $path = substr($path, 2); } else { $root = DIRECTORY_SEPARATOR; $path = substr($path, 1); } } } $s = array(); array_push($s, $root); $tok = strtok($path, DIRECTORY_SEPARATOR); while ($tok !== false) { $thisToken = $tok; if ("." === $thisToken) { $tok = strtok(DIRECTORY_SEPARATOR); continue; } elseif (".." === $thisToken) { if (count($s) < 2) { // using '..' in path that is too short throw new IOException("Cannot resolve path: {$orig}"); } else { array_pop($s); } } else { // plain component array_push($s, $thisToken); } $tok = strtok(DIRECTORY_SEPARATOR); } $sb = ""; for ($i = 0, $_i = count($s); $i < $_i; $i++) { if ($i > 1) { // not before the filesystem root and not after it, since root // already contains one $sb .= DIRECTORY_SEPARATOR; } $sb .= (string) $s[$i]; } $path = (string) $sb; if ($dosWithDrive === true) { $path = str_replace('/', '\\', $path); } return $path; }
/** * read in lines and execute them * @throws SQLException, IOException */ public function runStatements(Reader $reader, $out = null) { $sql = ""; $line = ""; $in = new BufferedReader($reader); try { while (($line = $in->readLine()) !== null) { $line = trim($line); $line = ProjectConfigurator::replaceProperties($this->project, $line, $this->project->getProperties()); if (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line)) { continue; } if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { continue; } $sql .= " " . $line; $sql = trim($sql); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (strpos($line, "--") !== false) { $sql .= "\n"; } if ($this->delimiterType == self::DELIM_NORMAL && StringHelper::endsWith($this->delimiter, $sql) || $this->delimiterType == self::DELIM_ROW && $line == $this->delimiter) { $this->log("SQL: " . $sql, PROJECT_MSG_VERBOSE); $this->execSQL(StringHelper::substring($sql, 0, strlen($sql) - strlen($this->delimiter) - 1), $out); $sql = ""; } } // Catch any statements not followed by ; if ($sql !== "") { $this->execSQL($sql, $out); } } catch (SQLException $e) { throw new BuildException("Error running statements", $e); } }
/** * read in lines and execute them * @param Reader $reader * @param null $out * @throws BuildException */ public function runStatements(Reader $reader, $out = null) { $sql = ""; $line = ""; $buffer = ''; if (is_array($this->filterChains) && !empty($this->filterChains)) { $in = FileUtils::getChainedReader(new BufferedReader($reader), $this->filterChains, $this->getProject()); while (-1 !== ($read = $in->read())) { // -1 indicates EOF $buffer .= $read; } $lines = explode("\n", $buffer); } else { $in = new BufferedReader($reader); while (($line = $in->readLine()) !== null) { $lines[] = $line; } } try { foreach ($lines as $line) { $line = trim($line); $line = ProjectConfigurator::replaceProperties($this->project, $line, $this->project->getProperties()); if (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line)) { continue; } if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { continue; } $sql .= " " . $line; $sql = trim($sql); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (strpos($line, "--") !== false) { $sql .= "\n"; } if ($this->delimiterType == self::DELIM_NORMAL && StringHelper::endsWith($this->delimiter, $sql) || $this->delimiterType == self::DELIM_ROW && $line == $this->delimiter) { $this->log("SQL: " . $sql, Project::MSG_VERBOSE); $this->execSQL(StringHelper::substring($sql, 0, strlen($sql) - strlen($this->delimiter)), $out); $sql = ""; } } // Catch any statements not followed by ; if ($sql !== "") { $this->execSQL($sql, $out); } } catch (SQLException $e) { throw new BuildException("Error running statements", $e); } }
/** * Tests whether or not a given path matches a given pattern. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * @return <code>true</code> if the pattern matches against the string, * or <code>false</code> otherwise. */ public static function matchPath($pattern, $str, $isCaseSensitive = true) { // When str starts with a DIRECTORY_SEPARATOR, pattern has to start with a // DIRECTORY_SEPARATOR. // When pattern starts with a DIRECTORY_SEPARATOR, str has to start with a // DIRECTORY_SEPARATOR. if (StringHelper::startsWith(DIRECTORY_SEPARATOR, $str) !== StringHelper::startsWith(DIRECTORY_SEPARATOR, $pattern)) { return false; } $patDirs = explode(DIRECTORY_SEPARATOR, $pattern); $strDirs = explode(DIRECTORY_SEPARATOR, $str); $patIdxStart = 0; $patIdxEnd = count($patDirs) - 1; $strIdxStart = 0; $strIdxEnd = count($strDirs) - 1; // up to first '**' while ($patIdxStart <= $patIdxEnd && $strIdxStart <= $strIdxEnd) { $patDir = $patDirs[$patIdxStart]; if ($patDir == "**") { break; } if (!self::match($patDir, $strDirs[$strIdxStart], $isCaseSensitive)) { return false; } $patIdxStart++; $strIdxStart++; } if ($strIdxStart > $strIdxEnd) { // String is exhausted for ($i = $patIdxStart; $i <= $patIdxEnd; $i++) { if ($patDirs[$i] != "**") { return false; } } return true; } elseif ($patIdxStart > $patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } // up to last '**' while ($patIdxStart <= $patIdxEnd && $strIdxStart <= $strIdxEnd) { $patDir = $patDirs[$patIdxEnd]; if ($patDir == "**") { break; } if (!self::match($patDir, $strDirs[$strIdxEnd], $isCaseSensitive)) { return false; } $patIdxEnd--; $strIdxEnd--; } if ($strIdxStart > $strIdxEnd) { // String is exhausted for ($i = $patIdxStart; $i <= $patIdxEnd; $i++) { if ($patDirs[$i] != "**") { return false; } } return true; } while ($patIdxStart != $patIdxEnd && $strIdxStart <= $strIdxEnd) { $patIdxTmp = -1; for ($i = $patIdxStart + 1; $i <= $patIdxEnd; $i++) { if ($patDirs[$i] == "**") { $patIdxTmp = $i; break; } } if ($patIdxTmp == $patIdxStart + 1) { // '**/**' situation, so skip one $patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd $patLength = $patIdxTmp - $patIdxStart - 1; $strLength = $strIdxEnd - $strIdxStart + 1; $foundIdx = -1; //strLoop: (start of outer loop) for ($i = 0; $i <= $strLength - $patLength; $i++) { for ($j = 0; $j < $patLength; $j++) { $subPat = $patDirs[$patIdxStart + $j + 1]; $subStr = $strDirs[$strIdxStart + $i + $j]; if (!self::match($subPat, $subStr, $isCaseSensitive)) { continue 2; // continue up two levels (to strLoop:) } } $foundIdx = $strIdxStart + $i; // only reached if all sub patterns matched break; } if ($foundIdx == -1) { return false; } $patIdxStart = $patIdxTmp; $strIdxStart = $foundIdx + $patLength; } for ($i = $patIdxStart; $i <= $patIdxEnd; $i++) { if ($patDirs[$i] != "**") { return false; } } return true; }
/** * Returns the next path element from this tokenizer. * * @return the next path element from this tokenizer. * * @throws Exception if there are no more elements in this tokenizer's path. */ public function nextToken() { if ($this->lookahead !== null) { $token = $this->lookahead; $this->lookahead = null; } else { $token = trim(array_shift($this->tokens)); } if (strlen($token) === 1 && Character::isLetter($token[0]) && $this->dosStyleFilesystem && !empty($this->tokens)) { // we are on a dos style system so this path could be a drive // spec. We look at the next token $nextToken = trim(array_shift($this->tokens)); if (StringHelper::startsWith('\\', $nextToken) || StringHelper::startsWith('/', $nextToken)) { // we know we are on a DOS style platform and the next path // starts with a slash or backslash, so we know this is a // drive spec $token .= ':' . $nextToken; } else { // store the token just read for next time $this->lookahead = $nextToken; } } return $token; }
/** * Read the statements from the .sql file and execute them. * Lines starting with '//', '--' or 'REM ' are ignored. * * Developer note: must be public in order to be called from * sudo-"inner" class PropelSQLExecTransaction. * * @param Reader $reader * @param $out Optional output stream. * @throws PDOException * @throws IOException */ public function runStatements(Reader $reader, $out = null) { $sql = ""; $line = ""; $sqlBacklog = ""; $hasQuery = false; $in = new BufferedReader($reader); $parser['pointer'] = 0; $parser['isInString'] = false; $parser['stringQuotes'] = ""; $parser['backslashCount'] = 0; $parser['parsedString'] = ""; $sqlParts = array(); while (($line = $in->readLine()) !== null) { $line = trim($line); $line = ProjectConfigurator::replaceProperties($this->project, $line, $this->project->getProperties()); if (StringHelper::startsWith("//", $line) || StringHelper::startsWith("--", $line) || StringHelper::startsWith("#", $line)) { continue; } if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { continue; } if ($sqlBacklog !== "") { $sql = $sqlBacklog; $sqlBacklog = ""; } $sql .= " " . $line . PHP_EOL; // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (strpos($line, "--") !== false) { $sql .= PHP_EOL; } // DELIM_ROW doesn't need this (as far as i can tell) if ($this->delimiterType == self::DELIM_NORMAL) { // old regex, being replaced due to segfaults: // See: http://propel.phpdb.org/trac/ticket/294 //$reg = "#((?:\"(?:\\\\.|[^\"])*\"?)+|'(?:\\\\.|[^'])*'?|" . preg_quote($this->delimiter) . ")#"; //$sqlParts = preg_split($reg, $sql, 0, PREG_SPLIT_DELIM_CAPTURE); $i = $parser['pointer']; $c = strlen($sql); while ($i < $c) { $char = $sql[$i]; switch ($char) { case "\\": $parser['backslashCount']++; $this->log("c{$i}: found " . $parser['backslashCount'] . " backslash(es)", Project::MSG_VERBOSE); break; case "'": case "\"": if ($parser['isInString'] && $parser['stringQuotes'] == $char) { if (($parser['backslashCount'] & 1) == 0) { #$this->log("$i: out of string", Project::MSG_VERBOSE); $parser['isInString'] = false; } else { $this->log("c{$i}: rejected quoted delimiter", Project::MSG_VERBOSE); } } elseif (!$parser['isInString']) { $parser['stringQuotes'] = $char; $parser['isInString'] = true; #$this->log("$i: into string with $parser['stringQuotes']", Project::MSG_VERBOSE); } break; } if ($char == $this->delimiter && !$parser['isInString']) { $this->log("c{$i}: valid end of command found!", Project::MSG_VERBOSE); $sqlParts[] = $parser['parsedString']; $sqlParts[] = $this->delimiter; break; } $parser['parsedString'] .= $char; if ($char !== "\\") { if ($parser['backslashCount']) { $this->log("{$i}: backslash reset", Project::MSG_VERBOSE); } $parser['backslashCount'] = 0; } $i++; $parser['pointer']++; } $sqlBacklog = ""; foreach ($sqlParts as $sqlPart) { // we always want to append, even if it's a delim (which will be stripped off later) $sqlBacklog .= $sqlPart; // we found a single (not enclosed by ' or ") delimiter, so we can use all stuff before the delim as the actual query if ($sqlPart === $this->delimiter) { $sql = $sqlBacklog; $sqlBacklog = ""; $hasQuery = true; } } } if ($hasQuery || $this->delimiterType == self::DELIM_ROW && $line == $this->delimiter) { // this assumes there is always a delimter on the end of the SQL statement. $sql = StringHelper::substring($sql, 0, strlen($sql) - 1 - strlen($this->delimiter)); $this->log("SQL: " . $sql, Project::MSG_VERBOSE); $this->execSQL($sql, $out); $sql = ""; $hasQuery = false; $parser['pointer'] = 0; $parser['isInString'] = false; $parser['stringQuotes'] = ""; $parser['backslashCount'] = 0; $parser['parsedString'] = ""; $sqlParts = array(); } } // Catch any statements not followed by ; if ($sql !== "") { $this->execSQL($sql, $out); } }
/** * Setup/initialize Phing environment from commandline args. * @param array $args commandline args passed to phing shell. * @return void */ public function execute($args) { self::$definedProps = new Properties(); $this->searchForThis = null; // cycle through given args for ($i = 0, $argcount = count($args); $i < $argcount; ++$i) { // ++$i intentional here, as first param is script name $arg = $args[$i]; if ($arg == "-help" || $arg == "-h") { $this->printUsage(); return; } elseif ($arg == "-version" || $arg == "-v") { $this->printVersion(); return; } elseif ($arg == "-quiet" || $arg == "-q") { self::$msgOutputLevel = PROJECT_MSG_WARN; } elseif ($arg == "-verbose") { $this->printVersion(); self::$msgOutputLevel = PROJECT_MSG_VERBOSE; } elseif ($arg == "-debug") { $this->printVersion(); self::$msgOutputLevel = PROJECT_MSG_DEBUG; } elseif ($arg == "-logfile") { try { // try to set logfile if (!isset($args[$i + 1])) { print "You must specify a log file when using the -logfile argument\n"; return; } else { $logFile = new PhingFile($args[++$i]); $this->loggerClassname = 'phing.listener.PearLogger'; $this->setDefinedProperty('pear.log.name', $logFile->getAbsolutePath()); } } catch (IOException $ioe) { print "Cannot write on the specified log file. Make sure the path exists and you have write permissions.\n"; throw $ioe; } } elseif ($arg == "-buildfile" || $arg == "-file" || $arg == "-f") { if (!isset($args[$i + 1])) { print "You must specify a buildfile when using the -buildfile argument\n"; return; } else { $this->buildFile = new PhingFile($args[++$i]); } } elseif ($arg == "-listener") { if (!isset($args[$i + 1])) { print "You must specify a listener class when using the -listener argument\n"; return; } else { $this->listeners[] = $args[++$i]; } } elseif (StringHelper::startsWith("-D", $arg)) { $name = substr($arg, 2); $value = null; $posEq = strpos($name, "="); if ($posEq !== false) { $value = substr($name, $posEq + 1); $name = substr($name, 0, $posEq); } elseif ($i < count($args) - 1) { $value = $args[++$i]; } self::$definedProps->setProperty($name, $value); } elseif ($arg == "-logger") { if (!isset($args[$i + 1])) { print "You must specify a classname when using the -logger argument\n"; return; } else { $this->loggerClassname = $args[++$i]; } } elseif ($arg == "-inputhandler") { if ($this->inputHandlerClassname !== null) { throw new BuildException("Only one input handler class may be specified."); } if (!isset($args[$i + 1])) { print "You must specify a classname when using the -inputhandler argument\n"; return; } else { $this->inputHandlerClassname = $args[++$i]; } } elseif ($arg == "-projecthelp" || $arg == "-targets" || $arg == "-list" || $arg == "-l") { // set the flag to display the targets and quit $this->projectHelp = true; } elseif ($arg == "-find") { // eat up next arg if present, default to build.xml if ($i < count($args) - 1) { $this->searchForThis = $args[++$i]; } else { $this->searchForThis = self::DEFAULT_BUILD_FILENAME; } } elseif (substr($arg, 0, 1) == "-") { // we don't have any more args print "Unknown argument: {$arg}\n"; $this->printUsage(); return; } else { // if it's no other arg, it may be the target array_push($this->targets, $arg); } } // if buildFile was not specified on the command line, if ($this->buildFile === null) { // but -find then search for it if ($this->searchForThis !== null) { $this->buildFile = $this->_findBuildFile(self::getProperty("user.dir"), $this->searchForThis); } else { $this->buildFile = new PhingFile(self::DEFAULT_BUILD_FILENAME); } } // make sure buildfile exists if (!$this->buildFile->exists()) { throw new BuildException("Buildfile: " . $this->buildFile->__toString() . " does not exist!"); } // make sure it's not a directory if ($this->buildFile->isDirectory()) { throw new BuildException("Buildfile: " . $this->buildFile->__toString() . " is a dir!"); } $this->readyToRun = true; }
/** * Apply this map entry to a given path element * * @param string $elem Path element to process * @return string Updated path element after mapping * * @throws BuildException */ public function apply($elem) { if ($this->outer->from === null || $this->outer->to === null) { throw new BuildException("Both 'from' and 'to' must be set " . "in a map entry"); } // If we're on windows, then do the comparison ignoring case $cmpElem = $this->outer->onWindows ? strtolower($elem) : $elem; $cmpFrom = $this->outer->onWindows ? strtolower(str_replace('/', '\\', $this->outer->from)) : $this->outer->from; // If the element starts with the configured prefix, then // convert the prefix to the configured 'to' value. if (StringHelper::startsWith($cmpFrom, $cmpElem)) { $len = strlen($this->outer->from); if ($len >= strlen($elem)) { $elem = $this->outer->to; } else { $elem = $this->outer->to . StringHelper::substring($elem, $len); } } return $elem; }