本文整理汇总了PHP中wfShellExec函数的典型用法代码示例。如果您正苦于以下问题:PHP wfShellExec函数的具体用法?PHP wfShellExec怎么用?PHP wfShellExec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了wfShellExec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: compile
/**
* Compile the given SASS source
*
* @param Source $source Sass source
* @throws Wikia\Sass\Exception
* @return string CSS stylesheet
*/
public function compile(Source $source)
{
wfProfileIn(__METHOD__);
$tempDir = $this->tempDir ?: sys_get_temp_dir();
//replace \ to / is needed because escapeshellcmd() replace \ into spaces (?!!)
$outputFile = str_replace('\\', '/', tempnam($tempDir, uniqid('Sass')));
$tempDir = str_replace('\\', '/', $tempDir);
$sassVariables = urldecode(http_build_query($this->sassVariables, '', ' '));
$debugMode = $this->useSourceMaps ? '--debug-in' : '';
$hasLocalFile = $source->hasPermanentFile();
$localFile = $source->getLocalFile();
$inputFile = $hasLocalFile ? $localFile : '-s';
$cmd = "{$this->sassExecutable} {$inputFile} {$outputFile} --scss -t {$this->outputStyle} " . "-I {$this->rootDir} {$debugMode} " . "--cache-location {$tempDir}/sass2 -r {$this->rootDir}/extensions/wikia/SASS/wikia_sass.rb {$sassVariables}";
$cmd = escapeshellcmd($cmd) . " 2>&1";
if (!$hasLocalFile) {
$cmd = escapeshellcmd("cat {$localFile}") . " | " . $cmd;
}
$sassOutput = wfShellExec($cmd, $status);
if ($status !== 0) {
// 0 => success
if (file_exists($outputFile)) {
unlink($outputFile);
}
$this->error("SASS rendering failed", ['cmd' => $cmd, 'output' => preg_replace('#\\n\\s+#', ' ', trim($sassOutput)), 'status' => $status]);
throw new Wikia\Sass\Exception("SASS compilation failed: {$sassOutput}\nFull commandline: {$cmd}");
}
$styles = file_get_contents($outputFile);
unlink($outputFile);
if ($styles === false) {
$this->error("Reading SASS file failed", ['input' => $inputFile, 'output' => $outputFile]);
throw new Wikia\Sass\Exception("Reading SASS file failed");
}
wfProfileOut(__METHOD__);
return $styles;
}
示例2: testPixelFormatRendering
/**
*
* @dataProvider providePixelFormats
*/
public function testPixelFormatRendering($sourceFile, $pixelFormat, $samplingFactor)
{
global $wgUseImageMagick, $wgUseImageResize;
if (!$wgUseImageMagick) {
$this->markTestSkipped("This test is only applicable when using ImageMagick thumbnailing");
}
if (!$wgUseImageResize) {
$this->markTestSkipped("This test is only applicable when using thumbnailing");
}
$fmtStr = var_export($pixelFormat, true);
$this->setMwGlobals('wgJpegPixelFormat', $pixelFormat);
$file = $this->dataFile($sourceFile, 'image/jpeg');
$params = ['width' => 320];
$thumb = $file->transform($params, File::RENDER_NOW | File::RENDER_FORCE);
$this->assertTrue(!$thumb->isError(), "created JPEG thumbnail for pixel format {$fmtStr}");
$path = $thumb->getLocalCopyPath();
$this->assertTrue(is_string($path), "path returned for JPEG thumbnail for {$fmtStr}");
$cmd = ['identify', '-format', '%[jpeg:sampling-factor]', $path];
$retval = null;
$output = wfShellExec($cmd, $retval);
$this->assertTrue($retval === 0, "ImageMagick's identify command should return success");
$expected = $samplingFactor;
$actual = trim($output);
$this->assertEquals($expected, trim($output), "IM identify expects JPEG chroma subsampling \"{$expected}\" for {$fmtStr}");
}
示例3: __construct
protected function __construct() {
$idFile = wfTempDir() . '/mw-' . __CLASS__ . '-UID-nodeid';
$nodeId = is_file( $idFile ) ? file_get_contents( $idFile ) : '';
// Try to get some ID that uniquely identifies this machine (RFC 4122)...
if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
wfSuppressWarnings();
if ( wfIsWindows() ) {
// http://technet.microsoft.com/en-us/library/bb490913.aspx
$csv = trim( wfShellExec( 'getmac /NH /FO CSV' ) );
$line = substr( $csv, 0, strcspn( $csv, "\n" ) );
$info = str_getcsv( $line );
$nodeId = isset( $info[0] ) ? str_replace( '-', '', $info[0] ) : '';
} elseif ( is_executable( '/sbin/ifconfig' ) ) { // Linux/BSD/Solaris/OS X
// See http://linux.die.net/man/8/ifconfig
$m = array();
preg_match( '/\s([0-9a-f]{2}(:[0-9a-f]{2}){5})\s/',
wfShellExec( '/sbin/ifconfig -a' ), $m );
$nodeId = isset( $m[1] ) ? str_replace( ':', '', $m[1] ) : '';
}
wfRestoreWarnings();
if ( !preg_match( '/^[0-9a-f]{12}$/i', $nodeId ) ) {
$nodeId = MWCryptRand::generateHex( 12, true );
$nodeId[1] = dechex( hexdec( $nodeId[1] ) | 0x1 ); // set multicast bit
}
file_put_contents( $idFile, $nodeId ); // cache
}
$this->nodeId32 = wfBaseConvert( substr( sha1( $nodeId ), 0, 8 ), 16, 2, 32 );
$this->nodeId48 = wfBaseConvert( $nodeId, 16, 2, 48 );
// If different processes run as different users, they may have different temp dirs.
// This is dealt with by initializing the clock sequence number and counters randomly.
$this->lockFile88 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-88';
$this->lockFile128 = wfTempDir() . '/mw-' . __CLASS__ . '-UID-128';
}
示例4: addWatermark
function addWatermark($srcPath, $dstPath, $width, $height)
{
global $IP, $wgImageMagickConvertCommand, $wgImageMagickCompositeCommand;
// do not add a watermark if the image is too small
if (WatermarkSupport::validImageSize($width, $height) == false) {
return;
}
$wm = $IP . '/skins/WikiHow/images/watermark.svg';
$watermarkWidth = 1074.447;
$targetWidth = $width / 8;
$density = 72 * $targetWidth / $watermarkWidth;
// we have a lower limit on density so the watermark is readable
if ($density < 4.0) {
$density = 4.0;
}
$cmd = "";
// make sure image is rgb format so the watermark applies correctly
if (WatermarkSupport::isCMYK($srcPath)) {
$cmd = wfEscapeShellArg($wgImageMagickConvertCommand) . " " . wfEscapeShellArg($srcPath) . " " . "-colorspace RGB " . wfEscapeShellArg($dstPath) . ";";
$srcPath = $dstPath;
}
$cmd = $cmd . wfEscapeShellArg($wgImageMagickConvertCommand) . " -density {$density} -background none " . wfEscapeShellArg($wm) . " miff:- | " . wfEscapeShellArg($wgImageMagickCompositeCommand) . " -gravity southeast -quality 100 -geometry +8+10 - " . wfEscapeShellArg($srcPath) . " " . wfEscapeShellArg($dstPath) . " 2>&1";
$beforeExists = file_exists($dstPath);
wfDebug(__METHOD__ . ": running ImageMagick: {$cmd}\n");
$err = wfShellExec($cmd, $retval);
$afterExists = file_exists($dstPath);
$currentDate = `date`;
wfErrorLog(trim($currentDate) . " {$cmd} b:" . ($beforeExists ? 't' : 'f') . " a:" . ($afterExists ? 't' : 'f') . "\n", '/tmp/watermark.log');
wfProfileOut('watermark');
}
示例5: doTransform
function doTransform($image, $dstPath, $dstUrl, $params, $flags = 0)
{
global $wgFLVConverters, $wgFLVConverter, $wgFLVConverterPath;
if (!$this->normaliseParams($image, $params)) {
return new TransformParameterError($params);
}
$clientWidth = $params['width'];
$clientHeight = $params['height'];
$physicalWidth = $params['physicalWidth'];
$physicalHeight = $params['physicalHeight'];
$srcPath = $image->getPath();
if ($flags & self::TRANSFORM_LATER) {
return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
}
if (!wfMkdirParents(dirname($dstPath), null, __METHOD__)) {
return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, wfMsg('thumbnail_dest_directory'));
}
$err = false;
if (isset($wgFLVConverters[$wgFLVConverter])) {
$cmd = str_replace(array('$path/', '$width', '$height', '$input', '$output'), array($wgFLVConverterPath ? wfEscapeShellArg("{$wgFLVConverterPath}/") : "", intval($physicalWidth), intval($physicalHeight), wfEscapeShellArg($srcPath), wfEscapeShellArg($dstPath)), $wgFLVConverters[$wgFLVConverter]) . " 2>&1";
wfProfileIn('rsvg');
wfDebug(__METHOD__ . ": {$cmd}\n");
$err = wfShellExec($cmd, $retval);
wfProfileOut('rsvg');
}
$removed = $this->removeBadFile($dstPath, $retval);
if ($retval != 0 || $removed) {
wfDebugLog('thumbnail', sprintf('thumbnail failed on %s: error %d "%s" from "%s"', wfHostname(), $retval, trim($err), $cmd));
return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, $err);
} else {
return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
}
}
示例6: execute
public function execute($params = null)
{
global $IP, $wgWikiaLocalSettingsPath;
$this->mParams = unserialize($params->task_arguments);
$this->users = $this->mParams['users'];
$this->time = $this->mParams['time'];
$userNames = array();
foreach ($this->users as $u) {
$userNames[] = $u['canonical'];
}
// Save initial log line
$processSummary = "Processing UserRollback request:\n";
$processSummary .= " - users: " . implode(', ', $userNames) . "\n";
$processSummary .= " - from: " . $this->time;
$this->log($processSummary);
// ...
$wikiIds = $this->findWikis($this->users);
$noErrors = true;
$allUsers = implode('|', $userNames);
foreach ($wikiIds as $wikiId) {
$cmd = "SERVER_ID={$wikiId} php {$IP}/extensions/wikia/UserRollback/maintenance/rollbackEditsMulti.php " . "--users " . escapeshellarg($allUsers) . " --time " . escapeshellarg($this->time) . " --onlyshared --conf {$wgWikiaLocalSettingsPath}";
$this->log("Running {$cmd}");
$exitCode = null;
$output = wfShellExec($cmd, $exitCode);
if ($exitCode == 1) {
$noErrors = false;
}
$this->log("--- Command output ---\n{$output}\n--- End of command output ---");
$this->log("Finished processing wiki with ID {$wikiId}.");
}
$this->log("Finished processing work.");
return $noErrors;
}
示例7: applyDefaultParameters
/**
* @param array $params
* @param Config $mainConfig
* @return array
*/
public static function applyDefaultParameters(array $params, Config $mainConfig)
{
$logger = LoggerFactory::getInstance('Mime');
$params += ['typeFile' => $mainConfig->get('MimeTypeFile'), 'infoFile' => $mainConfig->get('MimeInfoFile'), 'xmlTypes' => $mainConfig->get('XMLMimeTypes'), 'guessCallback' => function ($mimeAnalyzer, &$head, &$tail, $file, &$mime) use($logger) {
// Also test DjVu
$deja = new DjVuImage($file);
if ($deja->isValid()) {
$logger->info(__METHOD__ . ": detected {$file} as image/vnd.djvu\n");
$mime = 'image/vnd.djvu';
return;
}
// Some strings by reference for performance - assuming well-behaved hooks
Hooks::run('MimeMagicGuessFromContent', [$mimeAnalyzer, &$head, &$tail, $file, &$mime]);
}, 'extCallback' => function ($mimeAnalyzer, $ext, &$mime) {
// Media handling extensions can improve the MIME detected
Hooks::run('MimeMagicImproveFromExtension', [$mimeAnalyzer, $ext, &$mime]);
}, 'initCallback' => function ($mimeAnalyzer) {
// Allow media handling extensions adding MIME-types and MIME-info
Hooks::run('MimeMagicInit', [$mimeAnalyzer]);
}, 'logger' => $logger];
if ($params['infoFile'] === 'includes/mime.info') {
$params['infoFile'] = __DIR__ . "/libs/mime/mime.info";
}
if ($params['typeFile'] === 'includes/mime.types') {
$params['typeFile'] = __DIR__ . "/libs/mime/mime.types";
}
$detectorCmd = $mainConfig->get('MimeDetectorCommand');
if ($detectorCmd) {
$params['detectCallback'] = function ($file) use($detectorCmd) {
return wfShellExec("{$detectorCmd} " . wfEscapeShellArg($file));
};
}
return $params;
}
示例8: execute
/**
* execute
*
* Main entry point, TaskManagerExecutor run this method
*
* @access public
* @author bartek@wikia
* @author eloy@wikia
*
* @param mixed $params default null: task params from wikia_tasks table
*
* @return boolean: status of operation, true = success, false = failure
*/
function execute($params = null)
{
global $wgWikiaLocalSettingsPath;
$this->mTaskID = $params->task_id;
$this->mParams = $params;
$task_arguments = unserialize($params->task_arguments);
$this->mSourceTaskId = $task_arguments["source-task-id"];
$this->mTargetWikiId = $task_arguments["target-wiki-id"];
#--- get data for previous task
$oPreviousTask = BatchTask::newFromID($this->mSourceTaskId);
if (is_null($oPreviousTask)) {
$this->addLog("Previous task nr {$this->mSourceTaskId} doesn't exist in database");
return false;
}
$sWorkDir = $oPreviousTask->getTaskDirectory();
$this->addLog("Opennig {$sWorkDir} directory");
$i = 0;
while (file_exists(sprintf("%s/%03d_dump.xml", $sWorkDir, $i))) {
$phpFile = "php";
$importDumpFile = $GLOBALS["IP"] . "/maintenance/importDump.php";
$command = sprintf("SERVER_ID=%s %s %s --conf %s %s/%03d_dump.xml", $this->mTargetWikiId, $phpFile, $importDumpFile, $wgWikiaLocalSettingsPath, $sWorkDir, $i);
$this->addLog("Running: {$command}");
$out = wfShellExec($command, $retval);
$this->addLog($out);
$i++;
}
if (empty($i)) {
$this->addLog("Nothing was imported. There is no dump file to process");
}
return true;
}
示例9: execute
function execute($params = null)
{
global $IP, $wgWikiaLocalSettingsPath;
$this->mTaskID = $params->task_id;
$oUser = User::newFromId($params->task_user_id);
$oUser->load();
$this->mUser = $oUser->getName();
$data = unserialize($params->task_arguments);
$articles = $data["articles"];
$username = escapeshellarg($data["username"]);
$this->addLog("Starting task.");
$this->addLog("List of restored articles (by " . $this->mUser . ' as ' . $username . "):");
for ($i = 0; $i < count($articles); $i++) {
$titleobj = Title::makeTitle($articles[$i]["namespace"], $articles[$i]["title"]);
$article_to_do = $titleobj->getText();
$namespace = intval($articles[$i]["namespace"]);
$reason = $articles[$i]['reason'] ? ' -r ' . escapeshellarg($articles[$i]['reason']) : '';
$sCommand = "SERVER_ID=" . $articles[$i]["wikiid"] . " php {$IP}/maintenance/wikia/restoreOn.php -u " . $username . " -t " . escapeshellarg($article_to_do) . " -n " . $namespace . $reason . " --conf " . escapeshellarg($wgWikiaLocalSettingsPath);
$city_url = WikiFactory::getVarValueByName("wgServer", $articles[$i]["wikiid"]);
if (empty($city_url)) {
$city_url = 'wiki id in WikiFactory: ' . $articles[$i]["wikiid"];
}
$city_path = WikiFactory::getVarValueByName("wgScript", $articles[$i]["wikiid"]);
$actual_title = wfShellExec($sCommand, $retval);
if ($retval) {
$this->addLog('Article undeleting error! (' . $city_url . '). Error code returned: ' . $retval . ' Error was: ' . $actual_title);
} else {
$this->addLog('<a href="' . $city_url . $city_path . '?title=' . $actual_title . '">' . $city_url . $city_path . '?title=' . $actual_title . '</a>');
}
}
return true;
}
示例10: callFontConfig
protected static function callFontConfig($code)
{
if (ini_get('open_basedir')) {
wfDebugLog('fcfont', 'Disabled because of open_basedir is active');
// Most likely we can't access any fonts we might find
return false;
}
$cache = self::getCache();
$cachekey = wfMemckey('fcfont', $code);
$timeout = 60 * 60 * 12;
$cached = $cache->get($cachekey);
if (is_array($cached)) {
return $cached;
} elseif ($cached === 'NEGATIVE') {
return false;
}
$code = wfEscapeShellArg(":lang={$code}");
$ok = 0;
$cmd = "fc-match {$code}";
$suggestion = wfShellExec($cmd, $ok);
wfDebugLog('fcfont', "{$cmd} returned {$ok}");
if ($ok !== 0) {
wfDebugLog('fcfont', "fc-match error output: {$suggestion}");
$cache->set($cachekey, 'NEGATIVE', $timeout);
return false;
}
$pattern = '/^(.*?): "(.*)" "(.*)"$/';
$matches = array();
if (!preg_match($pattern, $suggestion, $matches)) {
wfDebugLog('fcfont', "fc-match: return format not understood: {$suggestion}");
$cache->set($cachekey, 'NEGATIVE', $timeout);
return false;
}
list(, $file, $family, $type) = $matches;
wfDebugLog('fcfont', "fc-match: got {$file}: {$family} {$type}");
$file = wfEscapeShellArg($file);
$family = wfEscapeShellArg($family);
$type = wfEscapeShellArg($type);
$cmd = "fc-list {$family} {$type} {$code} file | grep {$file}";
$candidates = trim(wfShellExec($cmd, $ok));
wfDebugLog('fcfont', "{$cmd} returned {$ok}");
if ($ok !== 0) {
wfDebugLog('fcfont', "fc-list error output: {$candidates}");
$cache->set($cachekey, 'NEGATIVE', $timeout);
return false;
}
# trim spaces
$files = array_map('trim', explode("\n", $candidates));
$count = count($files);
if (!$count) {
wfDebugLog('fcfont', "fc-list got zero canditates: {$candidates}");
}
# remove the trailing ":"
$chosen = substr($files[0], 0, -1);
wfDebugLog('fcfont', "fc-list got {$count} candidates; using {$chosen}");
$data = array('family' => $family, 'type' => $type, 'file' => $chosen);
$cache->set($cachekey, $data, $timeout);
return $data;
}
示例11: callScribeProducer
function callScribeProducer($page_id, $page_ns, $rev_id, $user_id) {
global $IP, $wgWikiaLocalSettingsPath, $wgCityId;
$script_path = $_SERVER['PHP_SELF'];
$path = "SERVER_ID={$wgCityId} php {$script_path} --scribe=1 --conf {$wgWikiaLocalSettingsPath} --page_id=$page_id --page_ns=$page_ns --rev_id=$rev_id --user_id=$user_id";
#echo $path . " \n";
$return = wfShellExec( $path );
echo $return;
}
示例12: execute
public function execute()
{
global $wgCaptchaSecret, $wgCaptchaDirectoryLevels;
$instance = ConfirmEditHooks::getInstance();
if (!$instance instanceof FancyCaptcha) {
$this->error("\$wgCaptchaClass is not FancyCaptcha.\n", 1);
}
$backend = $instance->getBackend();
$countAct = $instance->estimateCaptchaCount();
$this->output("Estimated number of captchas is {$countAct}.\n");
$countGen = (int) $this->getOption('fill') - $countAct;
if ($countGen <= 0) {
$this->output("No need to generate anymore captchas.\n");
return;
}
$tmpDir = wfTempDir() . '/mw-fancycaptcha-' . time() . '-' . wfRandomString(6);
if (!wfMkdirParents($tmpDir)) {
$this->error("Could not create temp directory.\n", 1);
}
$e = null;
// exception
try {
$cmd = sprintf("python %s --key %s --output %s --count %s --dirs %s", wfEscapeShellArg(__DIR__ . '/../captcha.py'), wfEscapeShellArg($wgCaptchaSecret), wfEscapeShellArg($tmpDir), wfEscapeShellArg($countGen), wfEscapeShellArg($wgCaptchaDirectoryLevels));
foreach (array('wordlist', 'font', 'font-size', 'blacklist', 'verbose') as $par) {
if ($this->hasOption($par)) {
$cmd .= " --{$par} " . wfEscapeShellArg($this->getOption($par));
}
}
$this->output("Generating {$countGen} new captchas...\n");
$retVal = 1;
wfShellExec($cmd, $retVal, array(), array('time' => 0));
if ($retVal != 0) {
wfRecursiveRemoveDir($tmpDir);
$this->error("Could not run generation script.\n", 1);
}
$flags = FilesystemIterator::SKIP_DOTS;
$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpDir, $flags), RecursiveIteratorIterator::CHILD_FIRST);
$this->output("Copying the new captchas to storage...\n");
foreach ($iter as $fileInfo) {
if (!$fileInfo->isFile()) {
continue;
}
list($salt, $hash) = $instance->hashFromImageName($fileInfo->getBasename());
$dest = $instance->imagePath($salt, $hash);
$backend->prepare(array('dir' => dirname($dest)));
$status = $backend->quickStore(array('src' => $fileInfo->getPathname(), 'dst' => $dest));
if (!$status->isOK()) {
$this->error("Could not save file '{$fileInfo->getPathname()}'.\n");
}
}
} catch (Exception $e) {
wfRecursiveRemoveDir($tmpDir);
throw $e;
}
$this->output("Removing temporary files...\n");
wfRecursiveRemoveDir($tmpDir);
$this->output("Done.\n");
}
示例13: checkNYAvatar
function checkNYAvatar($city_id, $user_id) {
global $IP, $wgWikiaLocalSettingsPath;
$script_path = $_SERVER['PHP_SELF'];
$path = "SERVER_ID={$city_id} php {$script_path} --ny --user={$user_id} --conf {$wgWikiaLocalSettingsPath}";
#echo $path . " \n";
$return = wfShellExec( $path );
return $return;
}
示例14: testBug67870
public function testBug67870()
{
$command = wfIsWindows() ? 'for /l %i in (1, 1, 1001) do @echo ' . str_repeat('*', 331) : 'printf "%-333333s" "*"';
// Test several times because it involves a race condition that may randomly succeed or fail
for ($i = 0; $i < 10; $i++) {
$output = wfShellExec($command);
$this->assertEquals(333333, strlen($output));
}
}
示例15: doRollback
/**
* Perform a rollback of all revisions published by the given user
* after the given time
*
* @param array $identifiers list of user names or IPs whose revisions should be reverted
* @param int $timestamp Unix time after which revisions should be reverted
*/
public function doRollback(array $identifiers, $timestamp)
{
global $wgCityId, $IP;
$phpScript = $IP . '/extensions/wikia/UserRollback/maintenance/rollbackEditsMulti.php';
$cmd = sprintf("SERVER_ID=%d php {$phpScript} --users %s --time %s --onlyshared", $wgCityId, escapeshellarg(implode('|', $identifiers)), escapeshellarg($timestamp));
$this->info("Running {$phpScript}", ['users' => $identifiers, 'time' => $timestamp]);
$retval = wfShellExec($cmd, $status);
return $retval;
}