public static function logout() { $username = $GLOBALS['user']->getUsername(); $GLOBALS['user'] = null; unset($GLOBALS['user']); session_destroy(); SystemEvent::raise(SystemEvent::DEBUG, "User logged out. [ID={$username}]", __METHOD__); return true; }
protected static function _expandStr($str, array &$context = array()) { return preg_replace_callback('/\\$\\{(\\w*)\\}/', function ($matches) use(&$context) { if (isset($context['properties'][$matches[1]])) { return $context['properties'][$matches[1]]; } else { SystemEvent::raise(SystemEvent::INFO, "Couldn't expand user variable {$matches[0]}, no such property was found. Assumed value '{$matches[1]}'.", __METHOD__); return $matches[1]; } }, $str); }
private static function _workersDir() { $result = false; $dir = dirname(dirname(dirname(__FILE__))) . '/workers'; $dir = str_replace(array('\\', '//'), '/', $dir); if (is_dir($dir) && is_writable($dir)) { $result = $dir; } else { SystemEvent::raise(SystemEvent::ERROR, " The workers dir is not writable!", __METHOD__); } return $result; }
public function update(&$rev) { if (!$this->_connector->update($rev)) { SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, trying a few tricks before quiting. [DIR={$this->_connector->getLocal()}]", __METHOD__); if (!is_writable($this->_connector->getLocal()) && !@mkdir($this->_connector->getLocal(), DEFAULT_DIR_MASK, true)) { SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, dir was either not writable or didn't exist. [DIR={$this->_connector->getLocal()}]", __METHOD__); return false; } if (!$this->checkout()) { SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, trying 'checking out' the sources again, but couldn't. [DIR={$this->_connector->getLocal()}]", __METHOD__); return false; } if (!$this->_connector->update($rev)) { SystemEvent::raise(SystemEvent::INFO, "Definitely could not update local working copy. [DIR={$this->_connector->getLocal()}]", __METHOD__); return false; } } SystemEvent::raise(SystemEvent::DEBUG, "Updated local working copy. [DIR={$this->_connector->getLocal()}]", __METHOD__); return true; }
public function toPhp(array &$context = array()) { $php = ''; // // Generic class to process the includes/excludes filters // //TODO: Implement $isCaseSensitive!!!! //TODO: Implement only a single top level class for this $php = "\nif (!class_exists('FilesetFilterIterator', false)) {\n class FilesetFilterIterator extends FilterIterator\n {\n private \$_filesetId;\n private \$_type;\n\n public function __construct(\$o, \$filesetId, \$type = " . Build_BuilderElement_Type_Fileset::FILE . ")\n {\n \$this->_filesetId = \$filesetId;\n \$this->_type = \$type;\n parent::__construct(\$o);\n }\n\n public function accept()\n {\n // Check for type, first of all\n if (\$this->_type == " . Build_BuilderElement_Type_Fileset::FILE . " && !is_file(\$this->current()) ||\n \t\t\$this->_type == " . Build_BuilderElement_Type_Fileset::DIR . " && !is_dir(\$this->current()))\n {\n return false;\n }\n\n // if it is default excluded promptly return false\n foreach (\$GLOBALS['filesets'][\$this->_filesetId]['defaultExcludes'] as \$exclude) {\n if (\$this->_isMatch(\$exclude)) {\n return false;\n }\n }\n // if it is excluded promptly return false\n foreach (\$GLOBALS['filesets'][\$this->_filesetId]['exclude'] as \$exclude) {\n if (\$this->_isMatch(\$exclude)) {\n return false;\n }\n }\n // if it is included promptly return true\n foreach (\$GLOBALS['filesets'][\$this->_filesetId]['include'] as \$include) {\n if (\$this->_isMatch(\$include)) {\n return true;\n }\n }\n }\n\n private function _isMatch(\$pattern)\n {\n \$current = \$this->current();\n \$dir = \$GLOBALS['filesets'][\$this->_filesetId]['dir'];\n /*if (substr(\$dir, -1) != DIRECTORY_SEPARATOR) {\n \$dir .= DIRECTORY_SEPARATOR;\n }\n \$current = \$dir . \$current;*/\n \$isCaseSensitive = true;\n \$rePattern = preg_quote(\$GLOBALS['filesets'][\$this->_filesetId]['dir'] . \$pattern, '/');\n \$dirSep = preg_quote(DIRECTORY_SEPARATOR, '/');\n \$patternReplacements = array(\n \$dirSep.'\\*\\*' => '\\/?.*',\n '\\*\\*'.\$dirSep => '.*',\n '\\*\\*' => '.*',\n '\\*' => '[^'.\$dirSep.']*',\n '\\?' => '[^'.\$dirSep.']'\n );\n \$rePattern = str_replace(array_keys(\$patternReplacements), array_values(\$patternReplacements), \$rePattern);\n \$rePattern = '/^'.\$rePattern.'\$/'.(\$isCaseSensitive ? '' : 'i');\n return (bool) preg_match(\$rePattern, \$current);\n }\n }\n}\n"; if (!$this->getDir()) { SystemEvent::raise(SystemEvent::ERROR, 'Root dir not set for type fileset.', __METHOD__); return false; } $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}'] = array();\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'] = '';\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['defaultExcludes'] = array(\n '**/*~',\n '**/#*#',\n '**/.#*',\n '**/%*%',\n '**/._*',\n '**/CVS',\n '**/CVS/**',\n '**/.cvsignore',\n '**/SCCS',\n '**/SCCS/**',\n '**/vssver.scc',\n '**/.svn',\n '**/.svn/**',\n '**/.DS_Store',\n '**/.git',\n '**/.git/**',\n '**/.gitattributes',\n '**/.gitignore',\n '**/.gitmodules',\n '**/.hg',\n '**/.hg/**',\n '**/.hgignore',\n '**/.hgsub',\n '**/.hgsubstate',\n '**/.hgtags',\n '**/.bzr',\n '**/.bzr/**',\n '**/.bzrignore',\n);\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['exclude'] = array();\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'] = array();\n"; if ($this->getDir()) { $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'] = expandStr('{$this->getDir()}');\n"; } if ($this->getDefaultExcludes() === false) { $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['defaultExcludes'] = array();\n"; } if ($this->getInclude()) { $includes = $this->getInclude(); foreach ($includes as $include) { $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'][] = expandStr('{$include}');\n"; } } if ($this->getExclude()) { $excludes = $this->getExclude(); foreach ($excludes as $exclude) { $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['exclude'][] = expandStr('{$exclude}');\n"; } } $php .= "\nif (!function_exists('fileset{$this->getId()}_{$context['id']}')) {\n function fileset{$this->getId()}_{$context['id']}(\$callback)\n {\n \$recursiveIt = false;\n \$dirIt = 'DirectoryIterator';\n \$itIt = 'IteratorIterator';\n foreach (\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'] as \$include) {\n /*if (strpos(\$include, '**') !== false ||\n (substr_count(\$include, '/') > 1 && substr_count(\$include, '//') === 0) ||\n substr_count(\$include, '/') == 1 && strpos(\$include, '/') !== 0)\n {*/\n \$recursiveIt = true;\n \$dirIt = 'Recursive' . \$dirIt;\n \$itIt = 'Recursive' . \$itIt;\n break;\n /*}*/\n }\n try {\n foreach (new FilesetFilterIterator(new \$itIt(new \$dirIt(\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir']), (!\$recursiveIt?:" . (!empty($context['iteratorMode']) ?: "\$itIt::CHILD_FIRST") . "), (!\$recursiveIt?:\$itIt::CATCH_GET_CHILD)), '{$this->getId()}_{$context['id']}', {$this->getType()}) as \$entry) {\n if (!\$callback(\$entry, \$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'])) {\n //\$GLOBALS['result']['ok'] = false; // This should be relegated to the caller task\n \$msg = 'Callback applied to fileset returned false [CALLBACK=\$callback] [FILESET={$this->getId()}_{$context['id']}]';\n \$GLOBALS['result']['output'] = \$msg;\n //output(\$msg);\n return false;\n }\n }\n } catch (UnexpectedValueException \$e) { // Typical permission denied\n //\$GLOBALS['result']['ok'] = false; // This should be relegated to the caller task\n \$GLOBALS['result']['output'] = \$e->getMessage();\n output(\$e->getMessage());\n return false;\n }\n return true;\n }\n}\n"; return $php; }
public static function redirectToUri($url) { SystemEvent::raise(SystemEvent::DEBUG, "Redirecting from [URI={$GLOBALS['uri']}] to [URL={$url}]"); header('Location: ' . $url); exit; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getFiles()) { SystemEvent::raise(SystemEvent::ERROR, 'No files/dirs not set for task PHPCodeSniffer.', __METHOD__); return false; } if (!$this->getStandard()) { SystemEvent::raise(SystemEvent::ERROR, 'No standard defined for task PHPCodeSniffer.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'phpcodesniffer';\n// To avoid the 'PHP Notice: Undefined index: argc' that happens when\n// manually triggering a build\nif (!isset(\$_SERVER['argc'])) {\n \$_SERVER['argc'] = 1;\n}\n\$getFailOnError = " . (int) $this->getFailOnError() . ";\nrequire_once '" . CINTIENT_PHPCODESNIFFER_INCLUDE_FILE . "';\n\$getFileExtensions = expandStr('{$this->getFileExtensions()}');\n\$getFiles = expandStr('{$this->getFiles()}');\n\$getSniffs = expandStr('{$this->getSniffs()}');\n\$phpcs = new PHP_CodeSniffer_CLI();\n\$values = \$phpcs->getDefaults();\n\$values['extensions'] = (empty(\$getFileExtensions)?array():explode(' ', \$getFileExtensions));\n\$values['files'] = (empty(\$getFiles)?array():explode(' ', \$getFiles));\n\$values['reports']['xml'] = '{$this->getReportXmlFile()}';\n\$values['reports']['full'] = '{$this->getReportFullFile()}';\n\$values['reports']['source'] = null; // null means cout it, instead of file\n\$values['sniffs'] = (empty(\$getSniffs)?array():explode(' ', \$getSniffs));\n\$values['standard'] = expandStr('{$this->getStandard()}');\n\$values['reportWidth'] = 110;\nob_start();\n\$numErrors = \$phpcs->process(\$values);\noutput(ob_get_contents());\nob_end_clean();\n// Try to clean up as much as we can\n\$phpcs = null;\nunset(\$phpcs);\nif (\$numErrors === 0) {\n output(\"No code violations found. All code respects the '{\$values['standard']}' standard.\");\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n} else {\n output(\"Total of \$numErrors violation(s) found.\");\n if (\$getFailOnError) {\n \$GLOBALS['result']['ok'] = false;\n\t return false;\n } else {\n\t \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n\t}\n}\n"; return $php; }
public static function settings_notificationsSave() { SystemEvent::raise(SystemEvent::DEBUG, "Called.", __METHOD__); if (empty($GLOBALS['user']) || !$GLOBALS['user'] instanceof User) { $msg = 'Invalid request'; SystemEvent::raise(SystemEvent::INFO, $msg, __METHOD__); echo json_encode(array('success' => false, 'error' => $msg)); exit; } $notifications = array(); foreach ($_REQUEST as $handler => $payload) { $notificationClass = $handler; if (!class_exists($notificationClass)) { SystemEvent::raise(SystemEvent::INFO, "Invalid notification handler specified for save. [METHOD={$handler}]", __METHOD__); continue; } $notification = new $notificationClass(); foreach ($payload as $attribute => $data) { $setter = 'set' . ucfirst($attribute); if (!is_callable(array($notification, $setter))) { // method_exists() does not invoke __call() to check the method exists SystemEvent::raise(SystemEvent::INFO, "Invalid notification handler attribute specified for save. [METHOD={$handler}] [ATTRIBUTE={$attribute}]", __METHOD__); continue; } $notification->{$setter}($data['value']); } $notifications[$handler] = $notification; } $GLOBALS['user']->setNotifications($notifications); SystemEvent::raise(SystemEvent::DEBUG, "Notification settings changed for user {$GLOBALS['user']->getUsername()}.", __METHOD__); echo json_encode(array('success' => true, 'error' => 'Notification settings successfully changed.')); exit; }
} // // Set a special cookie "one-time" cookie so that right after the // installation we can show a message. This is just temporary until // system-user messages are implemented. This cookie will be imediately // erased by webHandler, after a GLOBAL flag is set. Right now a modal // is being shown in header.inc.tpl and this cookie is there removed. // setcookie('cintientInstalled', time()); $ok = true; if ($upgrade) { $msg = "Cintient was successfully updated. Please refresh this page when you're ready."; } else { $msg = "Use 'root' and the password you provided to login. Please refresh this page when you're ready."; } SystemEvent::raise(CINTIENT_LOG_SEVERITY_INFO, "Installation successful.", "Installer"); sendResponse($ok, $msg); } // // Ok ready to start installation! // $greetings = array('Greetings human.', "I'm sorry, Dave, I'm afraid I can't do that.", "They'll fix you. They fix everything.", 'Looking for me?', 'Stay out of trouble.', "This will all end in tears.", "Danger, Will Robinson!", "Thank you for a very enjoyable game.", "Shall we play a game?", "Wouldn't you prefer a nice game of chess?", "Greetings, Professor Falken.", "I've seen things you people wouldn't believe.", "Do... or do not. There is no try.", "Live long and prosper.", "The beginning is a very delicate time.", "Tell me of your homeworld, Usul."); ?> <!DOCTYPE html> <html dir="ltr" lang="en-US"> <head> <meta charset="UTF-8" /> <title>Cintient Installation</title> <link rel="stylesheet" href="www/css/reset.css" /> <link rel="stylesheet" href="www/css/font_anonymouspro.css" /> <link rel="stylesheet" href="www/css/font_orbitron.css" />
public function getViewData(array $params = array()) { $junitReportFile = $this->getPtrProjectBuild()->getBuildDir() . CINTIENT_JUNIT_REPORT_FILENAME; if (!is_file($junitReportFile)) { SystemEvent::raise(SystemEvent::ERROR, "Junit file not found. [PID={$this->getProjectId()}] [BUILD={$this->getProjectBuildId()}] [FILE={$junitReportFile}]", __METHOD__); return false; } try { $xml = new SimpleXMLElement($junitReportFile, 0, true); } catch (Exception $e) { SystemEvent::raise(SystemEvent::ERROR, "Problems processing Junit XML file. [PID={$this->getProjectId()}] [BUILD={$this->getProjectBuildId()}]", __METHOD__); return false; } // Apparently using call_user_func(__FUNCTION__) inside a closure, // doesn't work... Anyway I'm just going for a closure here, to // avoid the whole function definition crap here, inside a method. // // This closure takes a SimpleXMLElement loaded with the Junit report // and searches for the first element with a file attribute. That // level is the Class Test level, and what we want here is to iterate // over all class tests. $f = function ($node) use(&$parent, &$f) { if (isset($node->attributes()->file)) { return $parent->children(); } else { $parent = $node; return $f($node->children()); } }; $parent = $xml; $classTestsXml = $f($xml->children()); $classes = array(); foreach ($classTestsXml as $node) { $imageFilename = ''; $methodsNames = array(); $methods = array(); $class = new TestClass(); $class->setName((string) $node->attributes()->name); $class->setFile((string) $node->attributes()->file); $class->setTests((string) $node->attributes()->tests); $class->setAssertions((string) $node->attributes()->assertions); $class->setFailures((string) $node->attributes()->failures); $class->setErrors((string) $node->attributes()->errors); $class->setTime((string) $node->attributes()->time); $class->setChartFilename(md5($this->getProjectId() . $this->getProjectBuildId() . $class->getFile()) . '.png'); // Right here we're exactly at the test class (file) root level, // with level 1 being the unit test (method of the original class) // and level 2 being the various datasets used in the test (each a // test case). foreach ($node->children() as $methodXml) { $time = (double) $methodXml->attributes()->time * 1000; // to milliseconds $methodsNames[] = (string) $methodXml->attributes()->name; $f = (double) $methodXml->attributes()->failures * $time / (double) $methodXml->attributes()->assertions; $method = new TestMethod(); $method->setName((string) $methodXml->attributes()->name); $method->setTests((string) $methodXml->attributes()->tests); $method->setAssertions((string) $methodXml->attributes()->assertions); $method->setFailures((string) $methodXml->attributes()->failures); $method->setErrors((string) $methodXml->attributes()->errors); $method->setTime((string) $methodXml->attributes()->time); $method->setCalculatedOks((double) $time - (double) $f); $method->setCalculatedFaileds($f); $methods[] = $method; } $class->setTestMethods($methods); $classes[] = $class; } $ret = array(); $ret['project_buildJunit'] = $classes; return $ret; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getDir()) { SystemEvent::raise(SystemEvent::ERROR, 'Dir not set for mkdir task.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'mkdir';\n\$getDir = expandStr('{$this->getDir()}');\nif (!file_exists(\$getDir)) {\n if (mkdir(\$getDir, " . DEFAULT_DIR_MASK . ", true) === false && {$this->getFailOnError()}) {\n \$GLOBALS['result']['ok'] = false;\n output('Could not create ' . \$getDir . '.');\n return false;\n } else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n output('Created ' . \$getDir . '.');\n }\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n output(\$getDir . ' already exists.');\n}\n"; return $php; }
/** * * @param unknown_type $rs */ private static function &_getObject(Resultset $rs, array $options = array()) { isset($options['loadUsers']) ?: ($options['loadUsers'] = true); $ret = new Project(); $ret->setAvatar($rs->getAvatar()); $ret->setScmConnectorType($rs->getScmConnectorType()); $ret->setScmRemoteRepository($rs->getScmRemoteRepository()); $ret->setScmUsername($rs->getScmUsername()); $ret->setScmPassword($rs->getScmPassword()); $ret->setScmCheckChangesTimeout($rs->getScmCheckChangesTimeout()); $ret->setWorkDir($rs->getWorkDir()); $ret->setReleaseLabel($rs->getReleaseLabel()); $ret->setDateCreation($rs->getDateCreation()); $ret->setDateCheckedForChanges($rs->getDateCheckedForChanges()); $ret->setDescription($rs->getDescription()); $ret->setId($rs->getId()); $specialTasks = @unserialize($rs->getSpecialTasks()); if ($specialTasks === false) { $specialTasks = array(); } $ret->setSpecialTasks($specialTasks); $ret->setStatsNumBuilds($rs->getStatsNumBuilds()); $ret->setStatus($rs->getStatus()); $ret->setTitle($rs->getTitle()); $ret->setVisits($rs->getVisits()); $ret->setOptionReleasePackage($rs->getOptionReleasePackage()); $ret->setScmEnvVars($rs->getScmEnvVars()); // // Builders // // // The following is a workaround on the fact that the translation of this // serialized object to the database gets all broken, due to the fact of PHP // introducing NULL bytes around the '*' that is prepended before protected // variable members, in the serialized mode. This method replaces those // problematic NULL bytes with an identifier string '~~NULL_BYTE~~', // rendering serialization and unserialization of these specific kinds of // object safe. Credits to travis@travishegner.com on: // http://pt.php.net/manual/en/function.serialize.php#96504 // $unsafeSerializedIntegrationBuilder = str_replace(CINTIENT_NULL_BYTE_TOKEN, "", $rs->getIntegrationBuilder()); if (($integrationBuilder = unserialize($unsafeSerializedIntegrationBuilder)) === false) { SystemEvent::raise(SystemEvent::ERROR, "Couldn't unserialize integration builder for this project [PID={$ret->getId()}]"); $integrationBuilder = new Build_BuilderElement_Project(); } $ret->setIntegrationBuilder($integrationBuilder); $unsafeSerializedDeploymentBuilder = str_replace(CINTIENT_NULL_BYTE_TOKEN, "", $rs->getDeploymentBuilder()); if (($deploymentBuilder = unserialize($unsafeSerializedDeploymentBuilder)) === false) { SystemEvent::raise(SystemEvent::ERROR, "Couldn't unserialize deployment builder for this project [PID={$ret->getId()}]"); $deploymentBuilder = new Build_BuilderElement_Project(); } $ret->setDeploymentBuilder($deploymentBuilder); if ($options['loadUsers']) { $ret->loadUsers(); } $ret->resetSignature(); return $ret; }
protected function _save($force = false) { if (!$this->hasChanged()) { if (!$force) { return false; } SystemEvent::raise(SystemEvent::DEBUG, "Forced object save.", __METHOD__); } /* if (!Database::beginTransaction()) { return false; } $sql = 'REPLACE INTO phpdepend' . $this->getProjectId() . ' (buildid, date, version, ahh, andc, calls, ccn, ccn2, cloc,' . ' clsa, clsc, eloc, fanout, leafs, lloc, loc, maxdit, ncloc,' . ' noc, nof, noi, nom, nop, roots)' . ' VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'; $val = array( $this->getBuildId(), $this->getDate(), $this->getVersion(), $this->getAhh(), $this->getAndc(), $this->getCalls(), $this->getCcn(), $this->getCcn2(), $this->getCloc(), $this->getClsa(), $this->getClsc(), $this->getEloc(), $this->getFanout(), $this->getLeafs(), $this->getLloc(), $this->getLoc(), $this->getMaxDit(), $this->getNcloc(), $this->getNoc(), $this->getNof(), $this->getNoi(), $this->getNom(), $this->getNop(), $this->getRoots(), ); if (!Database::execute($sql, $val)) { Database::rollbackTransaction(); SystemEvent::raise(SystemEvent::ERROR, "Problems saving to db.", __METHOD__); return false; } if (!Database::endTransaction()) { SystemEvent::raise(SystemEvent::ERROR, "Something occurred while finishing transaction. The object might not have been saved.", __METHOD__); return false; } #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Saved.", __METHOD__); #endif $this->resetSignature();*/ return true; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getFilesets()) { SystemEvent::raise(SystemEvent::ERROR, 'No files not set for task PHPUnit.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'phpunit';\noutput('Starting unit tests...');\n"; // PHPUnit's internals always preemptively array_shift(), supposedly // the executable script's complete filename $php .= "\n\$args = array('dummyfirstentry');"; // Omit --no-globals-backup to see all kinds of weird shit happen, // like for instance a project's OK status not being saved after a // successful build. Don't know if this will ever be required by // anyone doing unit tests, but really hope not. With the current // Cintient implementation, we'd be in trouble if backup was on. $php .= "\n\$args[] = '--no-globals-backup';\n"; if ($this->getLogJunitXmlFile()) { $php .= "\n\$args[] = '--log-junit';\n\$args[] = '{$this->getLogJunitXmlFile()}';\n"; } if ($this->getCodeCoverageXmlFile()) { $php .= "\nif (!extension_loaded('xdebug')) {\n output('Code coverage only possible with the Xdebug extension loaded. Option \"--coverage-clover\" disabled.');\n} else {\n\t\$args[] = '--coverage-clover';\n\t\$args[] = '{$this->getCodeCoverageXmlFile()}';\n}\n"; } if ($this->getCodeCoverageHtmlDir()) { $php .= "\nif (!extension_loaded('xdebug')) {\n\toutput('Code coverage only possible with the Xdebug extension loaded. Option \"--coverage-html\" disabled.');\n} else {\n\t\$args[] = '--coverage-html';\n\t\$args[] = '{$this->getCodeCoverageHtmlDir()}';\n}\n"; } if ($this->getBootstrapFile()) { $php .= "\n\$args[] = '--bootstrap';\n\$args[] = expandStr('{$this->getBootstrapFile()}');\n"; } if ($this->getFilesets()) { $filesets = $this->getFilesets(); foreach ($filesets as $fileset) { $php .= "\n" . $fileset->toPhp($context) . "\nrequire_once 'PHPUnit/Autoload.php';\ndefine('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main');\n\$callback = function (\$entry) use (\$args) {\n \$ret = true;\n if (is_file(\$entry)) {\n \$_SERVER['argv'] = \$args; // This resets \$_SERVER['argv'] so that \$entry comes up next\n \$_SERVER['argv'][] = \"\$entry\"; // \$entry is a SlpFileInfo, force it __toString()\n \$_SERVER['argc'] = count(\$_SERVER['argv']); // For consistency sake\n ob_start();\n \$ret = PHPUnit_TextUI_Command::main(false);\n output(ob_get_contents());\n ob_end_clean();\n if (\$ret > 0) {\n \$ret = false;\n } else {\n \$ret = true;\n }\n unset(\$_SERVER['argv']);\n unset(\$_SERVER['argc']);\n }\n return \$ret;\n};\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n output('Unit testing failed.');\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n\t\$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n output('All tests ok.');\n}\n"; } } return $php; }
/** * The Project builder element is the top level container for a builder, * and on the Php connector it is responsible for setting up a whole * host of variables that will be set throughout the whole builder * script's execution. These variables should then be checked by the * script execution caller's environment. * * The following are available within the builder, and afterwards on * the callers scope: * * $GLOBALS['filesets'][<ID>] Holds all filesets * $GLOBALS['filesets'][<ID>]['dir'] The fileset root dir * $GLOBALS['filesets'][<ID>]['defaultExcludes'] Holds default exclusions (optional, default is use them) * $GLOBALS['filesets'][<ID>]['exclude'] Holds files/dirs to exclude * $GLOBALS['filesets'][<ID>]['include'] Holds files/dirs to include * $GLOBALS['id'] Holds an ID of the current builder * $GLOBALS['properties'][] Holds global project properties * $GLOBALS['properties'][<TASK>][] Holds local task related properties * $GLOBALS['result']['ok'] Holds the success or failure of last task's execution * $GLOBALS['result']['output'] Holds the output of the last task's execution, if any * $GLOBALS['result']['stacktrace'] The stacktrace of the error * $GLOBALS['result']['task'] Holds the last task executed * $GLOBALS['targets'][] 0-index based array with all the targets in their actual execution order * $GLOBALS['targetsDefault'] Holds the name of the default target to execute * $GLOBALS['targetsDeps'][<ID>][] Holds the names of the target's dependency targets */ public function toPhp() { $php = ''; $context = array(); $context['id'] = $this->getInternalId(); $context['properties'] = array(); // User properties might be needed at builder code generation time (see the copy task, for instance) if (empty($context['id'])) { SystemEvent::raise(SystemEvent::ERROR, 'A unique identifier for the project is required.', __METHOD__); return false; } if (!$this->getTargets()) { SystemEvent::raise(SystemEvent::ERROR, 'No targets set for the project.', __METHOD__); return false; } if (!$this->getDefaultTarget()) { SystemEvent::raise(SystemEvent::ERROR, 'No default target set for the project.', __METHOD__); return false; } // // TODO: uncomment this in production // $php .= "\n<?php\n//error_reporting(0);\n// Allow as much memory as possible by default\nini_set('memory_limit', -1);\nini_set('max_execution_time', 0);\nini_set('display_errors', 'stderr');\n// Define the CLI specific stream constants, that are not availble in\n// the web server versions. PHP_Depend for instance relies on the STDERR\n// one; don't know if any other also.\nif (!defined('STDIN')) {\n\tdefine('STDIN', @fopen('php://stdin', 'r'));\n}\nif (!defined('STDOUT')) {\n\tdefine('STDOUT', @fopen('php://stdout', 'w'));\n}\nif (!defined('STDERR')) {\n\tdefine('STDERR', @fopen('php://stderr', 'w'));\n}\nstream_set_blocking(STDERR, false); // Don't let stderr block, it's only a 16KB buffer\nregister_shutdown_function('cleanup');\nfunction cleanup()\n{\n // Output globals result vars\n foreach (\$GLOBALS['result'] as \$key => \$value) {\n \$value = str_replace(PHP_EOL, '" . CINTIENT_NEWLINE_TOKEN . "', \$value);\n fwrite(STDOUT, \"\$key=\$value\\n\");\n }\n // Flush buffered output to stderr. This also means that almost certainly\n // something brought the builder to a halt before its end, so just\n // assume an error.\n if ((\$buffer = ob_get_clean()) && !empty(\$buffer)) {\n \t\$value = PHP_EOL.\"[ Following is buffered output that wasn't flushed properly ]" . PHP_EOL . "\$buffer\".PHP_EOL;\n \tfwrite(STDERR, \$value);\n \tfwrite(STDOUT, \"ok=0\");\n }\n // In case fatal occurred, last task didn't have time to finish and the\n // build could come out successful. Check for errors, to avoid this.\n if (error_get_last() != null) {\n \tfwrite(STDOUT, \"ok=0\");\n }\n @fclose(STDOUT);\n @fclose(STDERR);\n}\nset_include_path(get_include_path() . PATH_SEPARATOR . '" . CINTIENT_INSTALL_DIR . "lib/');\nset_include_path(get_include_path() . PATH_SEPARATOR . '" . CINTIENT_INSTALL_DIR . "lib/PEAR/');\nset_include_path(get_include_path() . PATH_SEPARATOR . '" . CINTIENT_INSTALL_DIR . "lib/PEAR/PHP/');\n"; if ($this->getBaseDir() !== null) { $php .= "\nset_include_path(get_include_path() . PATH_SEPARATOR . '{$this->getBaseDir()}');\n"; } if ($this->getDefaultTarget() !== null) { $php .= <<<EOT \$GLOBALS['targets'] = array(); \$GLOBALS['targetDefault'] = '{$this->getDefaultTarget()}_{$context['id']}'; \$GLOBALS['result'] = array(); \$GLOBALS['result']['ok'] = true; \$GLOBALS['result']['output'] = ''; \$GLOBALS['result']['stacktrace'] = ''; \$GLOBALS['result']['task'] = null; EOT; // // The following because the internal cron emulation process runs // without exiting, and the second time around will redeclare // ilegally this function. // if (!function_exists('output')) { $php .= <<<EOT function output(\$message) { \$GLOBALS['result']['stacktrace'] .= "[" . date('H:i:s') . "] [{\$GLOBALS['result']['task']}] {\$message} "; } function expandStr(\$str) { return preg_replace_callback('/\\\$\\{(\\w*)\\}/', function(\$matches) { \t\$key = \$matches[1] . '_{$context['id']}'; if (isset(\$GLOBALS['properties'][\$key])) { return \$GLOBALS['properties'][\$key]; } else { output("Couldn't expand user variable {\$matches[0]}, no such property was found. Assumed value '{\$matches[1]}'."); return \$matches[1]; } }, \$str); } EOT; } } $properties = $this->getProperties(); if ($this->getProperties()) { foreach ($properties as $property) { $php .= $property->toPhp($context); } } $targets = $this->getTargets(); if ($this->getTargets()) { foreach ($targets as $target) { $php .= $target->toPhp($context); } } $php .= "\nforeach (\$GLOBALS['targets'] as \$target) {\n \$GLOBALS['result']['task'] = 'target';\n output(\"Executing target \$target...\");\n if (\$target() === false) {\n \$GLOBALS['result']['task'] = 'target';\n \$error = error_get_last();\n \$GLOBALS['result']['output'] = \$error['message'] . ', on line ' . \$error['line'] . '.';\n output(\"Target \$target failed.\");\n return false;\n } else {\n \$GLOBALS['result']['task'] = 'target';\n output(\"Target \$target executed.\");\n }\n}\nexit;\n"; return $php; }
public static function project_history() { if (!isset($GLOBALS['project']) || !$GLOBALS['project'] instanceof Project) { SystemEvent::raise(SystemEvent::ERROR, "Problems fetching requested project.", __METHOD__); // // TODO: Notification // // // TODO: this should really be a redirect to the previous page. // return false; } // // Viewing project build details // $build = null; // It's possible that no build was triggered yet. if (isset($_GET['bid']) && !empty($_GET['bid'])) { $build = Project_Build::getById($_GET['bid'], $GLOBALS['project'], $GLOBALS['user']); } else { $build = Project_Build::getLatest($GLOBALS['project'], $GLOBALS['user']); } // // TODO: don't let user access the build history of a still unfinished build! // if ($build instanceof Project_Build) { // // Special tasks. This is post build, so we're fetching an existing special task (never creating it) // $specialTasks = $build->getSpecialTasks(); $GLOBALS['smarty']->assign('project_specialTasks', $specialTasks); if (!empty($specialTasks)) { foreach ($specialTasks as $task) { if (!class_exists($task)) { SystemEvent::raise(SystemEvent::ERROR, "Unexisting special task. [PID={$GLOBALS['project']->getId()}] [BUILD={$build->getId()}] [TASK={$task}]", __METHOD__); continue; } $o = $task::getById($build, $GLOBALS['user'], Access::READ); //$GLOBALS['smarty']->assign($task, $o); // Register for s if (!$o instanceof Build_SpecialTaskInterface) { SystemEvent::raise(SystemEvent::ERROR, "Unexisting special task ID. [PID={$GLOBALS['project']->getId()}] [BUILD={$build->getId()}] [TASK={$task}] [TASKID={$build->getId()}]", __METHOD__); continue; } $viewData = $o->getViewData(); if (is_array($viewData)) { foreach ($viewData as $key => $value) { $GLOBALS['smarty']->assign($key, $value); } } $o = null; unset($o); } } } // Last assignments $GLOBALS['smarty']->assign('project_buildList', Project_Build::getList($GLOBALS['project'], $GLOBALS['user'])); $GLOBALS['smarty']->assign('project_build', $build); }
/** * * Enter description here ... * @param unknown_type $dir */ public static function emptyDir($dir) { $ret = true; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($iterator as $path) { if ($path->isDir() && !$path->isLink()) { if ($res = @rmdir($path->getPathName())) { SystemEvent::raise(SystemEvent::DEBUG, "Removed dir {$path->getPathName()}", __METHOD__); } else { SystemEvent::raise(SystemEvent::ERROR, "Couldn't remove dir {$path->getPathName()}", __METHOD__); } $ret = $ret & $res; } else { if ($res = @unlink($path->getPathName())) { SystemEvent::raise(SystemEvent::DEBUG, "Removed file {$path->getPathName()}", __METHOD__); } else { SystemEvent::raise(SystemEvent::ERROR, "Couldn't remove file {$path->getPathName()}", __METHOD__); } $ret = $ret & $res; } } return $ret; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getName() || !$this->getValue()) { SystemEvent::raise(SystemEvent::ERROR, 'Name and value not set for type property.', __METHOD__); return false; } $context['properties'][self::_expandStr($this->getName(), $context)] = self::_expandStr($this->getValue(), $context); $php .= <<<EOT \$GLOBALS['properties'][expandStr('{$this->getName()}') . '_{$context['id']}'] = expandStr('{$this->getValue()}'); \$GLOBALS['result']['ok'] = (\$GLOBALS['result']['ok'] & true); EOT; return $php; }
array_walk($subSectionPieces, function (&$value) { $value = ucfirst($value); }); $GLOBALS['templateMethod'] = lcfirst(implode($subSectionPieces)); } if ($GLOBALS['section'] != 'default') { $GLOBALS['templateFile'] = $GLOBALS['section'] . '/' . $GLOBALS['subSection'] . '.tpl'; $GLOBALS['templateMethod'] = $GLOBALS['section'] . '_' . $GLOBALS['templateMethod']; } if (method_exists('TemplateManager', $GLOBALS['templateMethod'])) { #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Routing to known template function. [FUNCTION=TemplateManager::{$GLOBALS['templateMethod']}] [URI={$GLOBALS['uri']}]", __METHOD__); #endif TemplateManager::$GLOBALS['templateMethod'](); $GLOBALS['smarty']->assign('globals_settings', $GLOBALS['settings']); $GLOBALS['smarty']->assign('globals_section', $GLOBALS['section']); $GLOBALS['smarty']->assign('globals_subSection', $GLOBALS['subSection']); $GLOBALS['smarty']->assign('globals_user', $GLOBALS['user']); $GLOBALS['smarty']->assign('globals_project', $GLOBALS['project']); ob_end_clean(); $GLOBALS['smarty']->display($GLOBALS['templateFile']); exit; } #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Unknown template function. [FUNCTION=TemplateManager::{$GLOBALS['templateMethod']}] [URI={$GLOBALS['uri']}]", __METHOD__); #endif } /* +----------------------------------------------------------------+ *\ |* | RESTAURANT AT THE END OF THE UNIVERSE | *| \* +----------------------------------------------------------------+ */ Redirector::redirectAndExit(Redirector::NOT_FOUND);
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getMessage()) { SystemEvent::raise(SystemEvent::ERROR, 'Message not set for echo task.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'echo';\n"; $msg = addslashes($this->getMessage()); $php .= "\n\$getMessage = expandStr('{$msg}');\n"; if ($this->getFile()) { $append = 'w'; // the same as append == false (default for Ant and Phing) if ($this->getAppend()) { $append = 'a'; } $php .= <<<EOT \$getFile = expandStr('{$this->getFile()}'); if (!(\$fp = @fopen(\$getFile, '{$append}'))) { output("Couldn't open file \$getFile for output."); if ({$this->getFailOnError()}) { \$GLOBALS['result']['ok'] = false; return false; } else { \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true; } } \$res = (fwrite(\$fp, \$getMessage) === false ?:true); fclose(\$fp); if (!\$res) { output("Couldn't write message to file."); if ({$this->getFailOnError()}) { \$GLOBALS['result']['ok'] = false; return false; } else { \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true; } } else { \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true; } EOT; } else { $php .= <<<EOT \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true; output(\$getMessage); EOT; } return $php; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; $getFailedOnError = $this->getFailOnError() ? "true" : "false"; if (!$this->getIncludeDirs()) { SystemEvent::raise(SystemEvent::ERROR, 'No include dirs set for task PhpDepend.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'phpdepend';\n\$_SERVER['argv'] = array('dummyfirstentry');\n"; if ($this->getJdependChartFile()) { $php .= "\n\$_SERVER['argv'][] = expandStr('--jdepend-chart={$this->getJdependChartFile()}');\n"; } if ($this->getOverviewPyramidFile()) { $php .= "\n\$_SERVER['argv'][] = expandStr('--overview-pyramid={$this->getOverviewPyramidFile()}');\n"; } if ($this->getSummaryFile()) { $php .= "\n\$_SERVER['argv'][] = expandStr('--summary-xml={$this->getSummaryFile()}');\n"; } if ($this->getExcludeDirs()) { $php .= "\n\$_SERVER['argv'][] = expandStr('--ignore=" . str_replace(' ', ',', trim($this->getExcludeDirs())) . "');\n"; } if ($this->getExcludePackages()) { $php .= "\n\$_SERVER['argv'][] = expandStr('--exclude=" . str_replace(' ', ',', trim($this->getExcludePackages())) . "');\n"; } // Cintient's space separated to PHP_Depend's comma separated $php .= "\n\$_SERVER['argv'][] = expandStr('" . str_replace(' ', ',', trim($this->getIncludeDirs())) . "');\n"; $php .= "\n// To avoid the 'PHP Notice: Undefined index: argc' that happens when\n// manually triggering a build\n\$_SERVER['argc'] = count(\$_SERVER['argv']);\nrequire_once 'PHP/Depend/Autoload.php';\n\$autoload = new PHP_Depend_Autoload();\n\$autoload->register();\nPHP_Depend_Util_Log::setSeverity(-1); // to set PHP_Depend debug to false\nob_start();\n\$ret = PHP_Depend_TextUI_Command::main();\noutput(ob_get_contents());\nob_end_clean();\nunset(\$_SERVER['argv']);\nunset(\$_SERVER['argc']);\nif (\$ret > 0) {\n output('PHP_Depend analysis failed.');\n \$GLOBALS['result']['ok'] = false;\n if (" . $getFailedOnError . ") {\n return false;\n }\n} else {\n output('PHP_Depend analysis successful.');\n\t\$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n"; return $php; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return true; } $php = ''; if (!$this->getExecutable()) { SystemEvent::raise(SystemEvent::ERROR, 'Executable not set for exec task.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'exec';\n\$getBaseDir = '';\n"; if ($this->getBaseDir()) { $php .= "\n\$getBaseDir = \"cd \" . expandStr('{$this->getBaseDir()}') . \"; \";\n"; } $php .= "\n\$args = '';\n"; if ($this->getArgs()) { $php .= "\n\$getArgs = expandStr(' {$this->getArgs()}');\n"; } $php .= "\n\$getExecutable = expandStr('{$this->getExecutable()}');\n\$GLOBALS['result']['task'] = 'exec';\noutput(\"Executing '\$getBaseDir\$getExecutable\$getArgs'.\");\n\$ret = exec(\"\$getBaseDir\$getExecutable\$getArgs\", \$lines, \$retval);\nforeach (\$lines as \$line) {\n output(\$line);\n}\n"; if ($this->getOutputProperty()) { $php .= "\n\$GLOBALS['properties']['{$this->getOutputProperty()}_{$context['id']}'] = \$ret;\n"; } $php .= "\nif (\$retval > 0) {\n output('Failed.');\n if ({$this->getFailOnError()}) {\n \$GLOBALS['result']['ok'] = false;\n return false;\n } else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n }\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n output('Success.');\n}\n"; //TODO: bullet proof this for boolean falses (they're not showing up) /* $php .= "if ({$this->getFailOnError()} && !\$ret) { \$GLOBALS['result']['ok'] = false; return false; } \$GLOBALS['result']['ok'] = true; return true; ";*/ return $php; }
public static function uninstall(Project $project) { $sql = "DROP TABLE projectlog{$project->getId()}"; if (!Database::execute($sql)) { SystemEvent::raise(SystemEvent::ERROR, "Couldn't delete project log table. [TABLE={$project->getId()}]", __METHOD__); return false; } return true; }
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cintient. If not, see <http://www.gnu.org/licenses/>. * */ // TODO: centralize the initalization stuff that is common to web, ajax // and builder handlers. (this builder could be called by a crontab) require_once dirname(__FILE__) . '/../config/cintient.conf.php'; SystemEvent::setSeverityLevel(CINTIENT_LOG_SEVERITY); $GLOBALS['settings'] = SystemSettings::load(); // Pull up system settings // Temporarily disable the background build handler in Windows, while // binaries aren't being dealt with in the installer. if (Framework_HostOs::isWindows()) { SystemEvent::raise(SystemEvent::INFO, "Background builds are temporarily disabled in Windows.", 'buildHandler'); return false; } $buildProcess = new Framework_Process($GLOBALS['settings'][SystemSettings::EXECUTABLE_PHP]); $buildProcess->addArg(CINTIENT_INSTALL_DIR . 'src/workers/runBuildWorker.php'); if (!$buildProcess->isRunning()) { if (!$buildProcess->run(true)) { SystemEvent::raise(SystemEvent::ERROR, "Problems starting up build worker.", 'buildHandler'); } else { SystemEvent::raise(SystemEvent::INFO, "Build worker left running in the background.", 'buildHandler'); } } else { SystemEvent::raise(SystemEvent::DEBUG, "Build process already running.", 'buildHandler'); } #endif
public static function install() { SystemEvent::raise(SystemEvent::INFO, "Creating systemsettings table...", __METHOD__); $tableName = 'systemsettings'; $sql = <<<EOT DROP TABLE IF EXISTS {$tableName}NEW; CREATE TABLE IF NOT EXISTS {$tableName}NEW( key VARCHAR(255) PRIMARY KEY, value TEXT NOT NULL DEFAULT '' ); EOT; if (!Database::setupTable($tableName, $sql)) { SystemEvent::raise(SystemEvent::ERROR, "Problems setting up {$tableName} table.", __METHOD__); return false; } $self = new SystemSettings(); $self->_save(true); // This allows us to save the default system settings values at install time. SystemEvent::raise(SystemEvent::INFO, "{$tableName} table created.", __METHOD__); return true; }
// Ajax related // if (!empty($GLOBALS['section'])) { $GLOBALS['ajaxMethod'] = $GLOBALS['subSection']; if (strpos($GLOBALS['subSection'], '-') !== false) { $subSectionPieces = explode('-', $GLOBALS['subSection']); array_walk($subSectionPieces, function (&$value) { $value = ucfirst($value); }); $GLOBALS['ajaxMethod'] = lcfirst(implode($subSectionPieces)); } if ($GLOBALS['section'] != 'default') { $GLOBALS['ajaxMethod'] = $GLOBALS['section'] . '_' . $GLOBALS['ajaxMethod']; } if (method_exists('AjaxManager', $GLOBALS['ajaxMethod'])) { #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Routing to known ajax function. [FUNCTION=AjaxManager::{$GLOBALS['ajaxMethod']}] [URI={$GLOBALS['uri']}]", "ajaxHandler"); #endif AjaxManager::$GLOBALS['ajaxMethod'](); exit; } #if DEBUG SystemEvent::raise(SystemEvent::DEBUG, "Unknown ajax function. [FUNCTION=AjaxManager::{$GLOBALS['ajaxMethod']}] [URI={$GLOBALS['uri']}]", "ajaxHandler"); #endif } /* +----------------------------------------------------------------+ *\ |* | RESTAURANT AT THE END OF THE UNIVERSE | *| \* +----------------------------------------------------------------+ */ SystemEvent::raise(SystemEvent::INFO, "Not found. [URI={$GLOBALS['uri']}] [USER=" . ($GLOBALS['user'] instanceof User ? $GLOBALS['user']->getUsername() : 'N/A') . ']'); // TODO: send error here exit;
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getFilesets()) { SystemEvent::raise(SystemEvent::ERROR, 'No files not set for task Perl syntax.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'perlsyntax';\noutput('Starting...');\n"; if ($this->getFilesets()) { $filesets = $this->getFilesets(); foreach ($filesets as $fileset) { $php .= "\n" . $fileset->toPhp($context) . "\n"; // // In the following callback we assume that the fileset returns a // directory only *after* all it's content. // $php .= "\n\$callback = function (\$entry, \$baseDir) {\n \$ret = true;\n if (is_file(\$entry)) {\n \$output = array();\n exec(\"perl -c \$entry\", \$output, \$ret);\n if (\$ret > 0) {\n output('Errors parsing ' . substr(\$entry, strlen(\$baseDir)) . '.');\n \$ret = false;\n } else {\n output('No syntax errors detected in ' . substr(\$entry, strlen(\$baseDir)) . '.');\n \$ret = true;\n }\n }\n return \$ret;\n};\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n output('Failed.');\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n output('Done.');\n}\n"; } } return $php; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getText()) { SystemEvent::raise(SystemEvent::ERROR, 'Empty properties text.', __METHOD__); return false; } $properties = parse_ini_string($this->getText()); foreach ($properties as $key => $value) { $context['properties'][self::_expandStr($key, $context)] = self::_expandStr($value, $context); $php .= <<<EOT \$GLOBALS['properties'][expandStr('{$key}') . '_{$context['id']}'] = expandStr('{$value}'); EOT; } return $php; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getFile() && !$this->getFilesets()) { SystemEvent::raise(SystemEvent::ERROR, 'No source files set for task copy.', __METHOD__); return false; } if (!$this->getToFile() && !$this->getToDir()) { SystemEvent::raise(SystemEvent::ERROR, 'No destination set for task copy.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'copy';\n\$baseToFilename = '';\n"; if ($this->getToFile()) { $php .= "\n\$path = pathinfo(expandStr('{$this->getToFile()}'));\n\$baseToDir = \$path['dirname'];\n\$baseToFilename = '/' . \$path['basename']; // pathinfo's dirname *always* returns the dirname without the trailing slash.\n"; } elseif ($this->getToDir()) { $php .= "\n\$baseToDir = expandStr('{$this->getToDir()}');\n"; } // // TODO: Potential bug here. If the following generated mkdir does // indeed fail and failOnError == true, the execution will continue // because we are not returning true... A return true here would // halt the generated script execution (that's what return false does // in case of error...) // // Wrapping this whole element into a generated auto-executing closure // a la Javascript would be awesome, because that way we could just // force a return and not risk shutting down the whole builder script // $php .= "\nif (!file_exists(\$baseToDir) && !@mkdir(\$baseToDir, 0755, true)) {\n output(\"Failed creating dir \$baseToDir.\");\n\tif ({$this->getFailOnError()}) {\n \$GLOBALS['result']['ok'] = false;\n return false;\n } else {\n\t \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n }\n}"; // // Internally treat $this->getFile() as a fileset. // $filesets = array(); if ($this->getFile()) { $getFile = self::_expandStr($this->getFile(), $context); $pathFrom = pathinfo($getFile); $fileset = new Build_BuilderElement_Type_Fileset(); if (!file_exists($getFile)) { $php .= "\noutput(\"No such file or directory {$getFile}.\");\nif ({$this->getFailOnError()}) { // failonerror\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n"; } elseif (is_file($getFile)) { $fileset->addInclude($pathFrom['basename']); $fileset->setDir($pathFrom['dirname']); $fileset->setType(Build_BuilderElement_Type_Fileset::FILE); $php .= "\n\$baseFromDir = '{$pathFrom['dirname']}';\n"; } else { // It's a directory $fileset->addInclude('**/*'); $fileset->setDir($getFile); $fileset->setType(Build_BuilderElement_Type_Fileset::BOTH); // Very important default!!! $php .= "\n\$baseFromDir = '{$getFile}';\n"; } $filesets[] = $fileset; } elseif ($this->getFilesets()) { // If file exists, it takes precedence over filesets $realFilesets = $this->getFilesets(); // Not to be overwritten if (!$realFilesets[0]->getDir() || !$realFilesets[0]->getInclude()) { SystemEvent::raise(SystemEvent::ERROR, 'No source files set for task copy.', __METHOD__); return false; } // Iterator mode for copy() must enforce parent dirs before their children, // so that we can mkdir the parent without first trying to copy in the children // on a non-existing dir. $fileset = new Build_BuilderElement_Type_Fileset(); $fileset->setDir(self::_expandStr($realFilesets[0]->getDir(), $context)); $fileset->setInclude(explode(' ', self::_expandStr(implode(' ', $realFilesets[0]->getInclude()), $context))); $fileset->setExclude(explode(' ', self::_expandStr(implode(' ', $realFilesets[0]->getExclude()), $context))); $filesets[] = $fileset; $php .= "\n\$baseFromDir = '{$fileset->getDir()}';\n"; } $php .= "\n\$callback = function (\$entry) use (\$baseToDir, \$baseFromDir, \$baseToFilename) {\n \$dest = \$baseToDir . (!empty(\$baseToFilename)?\$baseToFilename:substr(\$entry, strlen(\$baseFromDir)));\n if (is_file(\$entry)) {\n \$ret = @copy(\$entry, \$dest);\n } elseif (is_dir(\$entry)) {\n \tif (!file_exists(\$dest) && !@mkdir(\$dest, 0755, true)) {\n \t \$ret = false;\n \t} else {\n \t \$ret = true;\n }\n } else {\n \$ret = false;\n }\n if (!\$ret) {\n output(\"Failed copy of \$entry to \$dest.\");\n } else {\n output(\"Copied \$entry to \$dest.\");\n }\n return \$ret;\n};\n"; $context['iteratorMode'] = RecursiveIteratorIterator::SELF_FIRST; // Make sure dirs come before their children, in order to be created first foreach ($filesets as $fileset) { $php .= "\n" . $fileset->toPhp($context) . "\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n"; } return $php; }
public function toPhp(array &$context = array()) { if (!$this->isActive()) { return ''; } $php = ''; if (!$this->getFile() && !$this->getFilesets()) { SystemEvent::raise(SystemEvent::ERROR, 'No files not set for task chmod.', __METHOD__); return false; } $mode = $this->getMode(); if (empty($mode) || !preg_match('/^(?:\\d{3}|\\$\\{\\w*\\})$/', $mode)) { // It must be a 3 digit decimal or a property SystemEvent::raise(SystemEvent::ERROR, 'No mode set for chmod.', __METHOD__); return false; } $php .= "\n\$GLOBALS['result']['task'] = 'chmod';\n\$callback = function (\$entry) {\n \$getModeInt = expandStr('{$this->getMode()}');\n \$getModeOctal = intval(\$getModeInt, 8); // Casts the decimal string representation into an octal (8 is for base 8 conversion)\n \$ret = @chmod(\$entry, \$getModeOctal);\n if (!\$ret) {\n output(\"Failed setting \$getModeInt on \$entry.\");\n } else {\n output(\"Ok setting \$getModeInt on \$entry.\");\n }\n return \$ret;\n};"; if ($this->getFile()) { $php .= "\n\$getFile = expandStr('{$this->getFile()}');\nif (!\$callback(\$getFile) && {$this->getFailOnError()}) { // failonerror\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n"; } elseif ($this->getFilesets()) { // If file exists, it takes precedence over filesets $filesets = $this->getFilesets(); foreach ($filesets as $fileset) { $php .= "\n" . $fileset->toPhp($context) . "\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n \$GLOBALS['result']['ok'] = false;\n return false;\n} else {\n \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n"; } } return $php; }