Exemplo n.º 1
1
 static function open($exec, $cwd = null)
 {
     if (!is_string($cwd)) {
         $cwd = @getcwd();
     }
     @chdir($cwd);
     if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
         $WshShell = new \COM("WScript.Shell");
         $WshShell->CurrentDirectory = str_replace('/', '\\', $cwd);
         $WshShell->Run($exec, 0, false);
     } else {
         exec($exec . " > /dev/null 2>&1 &");
     }
 }
Exemplo n.º 2
1
function shelL($command)
{
    global $windows, $disablefunctions;
    $exec = '';
    $output = '';
    $dep[] = array('pipe', 'r');
    $dep[] = array('pipe', 'w');
    if (is_callable('passthru') && !strstr($disablefunctions, 'passthru')) {
        @ob_start();
        passthru($command);
        $exec = @ob_get_contents();
        @ob_clean();
        @ob_end_clean();
    } elseif (is_callable('system') && !strstr($disablefunctions, 'system')) {
        $tmp = @ob_get_contents();
        @ob_clean();
        system($command);
        $output = @ob_get_contents();
        @ob_clean();
        $exec = $tmp;
    } elseif (is_callable('exec') && !strstr($disablefunctions, 'exec')) {
        exec($command, $output);
        $output = join("\n", $output);
        $exec = $output;
    } elseif (is_callable('shell_exec') && !strstr($disablefunctions, 'shell_exec')) {
        $exec = shell_exec($command);
    } elseif (is_resource($output = popen($command, "r"))) {
        while (!feof($output)) {
            $exec = fgets($output);
        }
        pclose($output);
    } elseif (is_resource($res = proc_open($command, $dep, $pipes))) {
        while (!feof($pipes[1])) {
            $line = fgets($pipes[1]);
            $output .= $line;
        }
        $exec = $output;
        proc_close($res);
    } elseif ($windows && is_object($ws = new COM("WScript.Shell"))) {
        $dir = isset($_SERVER["TEMP"]) ? $_SERVER["TEMP"] : ini_get('upload_tmp_dir');
        $name = $_SERVER["TEMP"] . namE();
        $ws->Run("cmd.exe /C {$command} >{$name}", 0, true);
        $exec = file_get_contents($name);
        unlink($name);
    }
    return $exec;
}
Exemplo n.º 3
0
function _exec($cmd)
{
    $WshShell = new COM("WScript.Shell");
    $oExec = $WshShell->Run("{$cmd}", 3, false);
    //echo $cmd;
    return $oExec == 0 ? true : false;
}
Exemplo n.º 4
0
 function execBg2()
 {
     $tmpBat = $this->tempBat();
     $WshShell = new COM("WScript.Shell");
     $oExec = $WshShell->Run($tmpBat, 0, false);
     return $oExec == 0 ? true : false;
 }
Exemplo n.º 5
0
function RemoveDir($dir, $verbose)
{
    if (!($dh = @opendir($dir))) {
        if ($verbose) {
            echo "can't open {$dir}                                                                                                    \r";
        }
        return;
    } else {
        while (false !== ($obj = readdir($dh))) {
            if ($obj == '.' || $obj == '..') {
                continue;
            }
            $newDir = $dir . '\\' . $obj;
            if (@unlink($newDir)) {
                if ($verbose) {
                    echo "file deleted {$newDir}...                                                                                           \r";
                }
                //$file_deleted++;
            } else {
                RemoveDir($newDir, $verbose);
            }
        }
    }
    $cmdline = "cmd /c rmdir {$dir}";
    $WshShell = new COM("WScript.Shell");
    // Make the command window but dont show it.
    $oExec = $WshShell->Run($cmdline, 0, false);
}
Exemplo n.º 6
0
function notify($type, $title, $message)
{
    $WshShell = new COM("WScript.Shell");
    $command = 'cmd /C %cd%/exe/notifu.exe /t ' . $type . ' /p "' . $title . '" /m "' . $message . '"';
    exec($command);
    $WshShell->Run($command, 0, false);
}
Exemplo n.º 7
0
function runServer()
{
    $WshShell = new COM("WScript.Shell");
    if (!file_exists('server.cmd')) {
        fwrite(fopen('server.cmd', 'w'), 'start C:\\xampp\\php\\php.exe ' . getcwd() . '\\server.php');
    }
    $WshShell->Run(getcwd() . '\\server.cmd', 7, false);
}
Exemplo n.º 8
0
function on_click($widget, $event, $title, $url)
{
    $shell = new COM('WScript.Shell');
    // note 1
    $shell->Run('cmd /c start "" "' . $url . '"', 0, FALSE);
    // note 1
    unset($shell);
}
Exemplo n.º 9
0
 /**
  * Execute the command.
  *
  * @param Command $command
  * @param bool    $background
  *
  * @return null|string|array
  */
 public function execute(Command $command, $background = false)
 {
     $cmd = $command->getCommandLine();
     if ($background) {
         $WshShell = new \COM("WScript.Shell");
         return $WshShell->Run($cmd, 7, false);
     } else {
         exec($cmd, $exec);
         return $exec;
     }
 }
Exemplo n.º 10
0
function runAsyncBatch($command, $filename)
{
    $BatchFile = fopen("Power106.bat", 'w');
    fwrite($BatchFile, "@Echo off\r\n");
    fwrite($BatchFile, "Title {$filename}\r\n");
    fwrite($BatchFile, "{$command}\r\n");
    fwrite($BatchFile, "Pause\r\n");
    fclose($BatchFile);
    $WshShell = new COM("WScript.Shell");
    $oExec = $WshShell->Run("Power106.bat", 1, false);
    unset($WshShell, $oExec);
}
Exemplo n.º 11
0
function email($to, $sub, $txt, $html)
{
    $json = array();
    $json["who"] = $to;
    $json["sub"] = $sub;
    $json["txt"] = $txt;
    $json["html"] = $html;
    $jso = json_encode($json);
    $name = var_export(rand(0, 99), true) . "_" . var_export(rand(0, 99), true) . "_" . var_export(rand(0, 99), true) . "_" . var_export(rand(0, 99), true);
    file_put_contents(realpath(dirname(__FILE__)) . '\\' . $name . ".txt", $jso);
    $handle = new COM('WScript.Shell');
    $handle->Run('"' . realpath(dirname(__FILE__)) . '\\EasyMail.exe" -fb "-path:' . realpath(dirname(__FILE__)) . '\\' . $name . ".txt", 0, false);
    return '"' . realpath(dirname(__FILE__)) . '\\EasyMail.exe" -fb "-path:' . realpath(dirname(__FILE__)) . '\\' . $name . ".txt";
}
Exemplo n.º 12
0
 /**
  * Run daemon in background
  *
  * @throws \RuntimeException
  * @return int|null          The process id if running successfully, null otherwise
  */
 public function run()
 {
     if ($this->getPid()) {
         throw new \RuntimeException('Daemon process already started');
     }
     // workaround for Windows
     if (defined('PHP_WINDOWS_VERSION_BUILD')) {
         $wsh = new \COM('WScript.shell');
         $wsh->Run($this->getQueueRunCmd(), 0, false);
         return $this->getPid();
     }
     $process = $this->getQueueRunProcess();
     $process->run();
     return $this->getPid();
 }
Exemplo n.º 13
0
 protected function runWindows($job)
 {
     if (!$this->checkPHPBinary($job)) {
         return;
     }
     if (!extension_loaded("COM")) {
         $this->fail("Cannot run PHP binary, please enable COM extension");
     }
     $WshShell = new COM("WScript.Shell");
     chdir(dirname(__FILE__) . "/../../");
     $command = sprintf("%s -f run_job.php %s %s", $sugar_config['cron']['php_binary'], $job->id, $this->getMyId());
     $WshShell->Run($command, 0, false);
     // no window, don't wait for return
     $WshShell->Release();
 }
Exemplo n.º 14
0
 /**
  * Open a File Dialog
  * @param $file File Name
  */
 public function openFile($file)
 {
     $ini = parse_ini_file('application.ini');
     $viewer = $ini['viewer'];
     if (file_exists($viewer)) {
         if (OS != 'WIN') {
             exec("{$viewer} {$file} >/dev/null &");
         } else {
             $WshShell = new COM("WScript.Shell");
             $WshShell->Run("{$file}", 0, true);
         }
     } else {
         throw new Exception(AdiantiCoreTranslator::translate('File not found') . ': ' . $viewer);
     }
 }
Exemplo n.º 15
0
 /**
  * Run daemon in background
  *
  * @param string $outputFile
  * @throws \RuntimeException
  * @return int|null The process id if running successfully, null otherwise
  */
 public function run($outputFile = '/dev/null')
 {
     if ($this->getPid()) {
         throw new \RuntimeException('Daemon process already started');
     }
     // workaround for Windows
     if (defined('PHP_WINDOWS_VERSION_BUILD')) {
         $wsh = new \COM('WScript.shell');
         $wsh->Run($this->getQueueRunCmd(), 0, false);
         $this->dateStart = new \DateTime('now');
         return $this->getPid();
     }
     $this->pid = shell_exec(sprintf('%s > %s 2>&1 & echo $!', $this->getQueueRunCmd(), $outputFile));
     $this->dateStart = new \DateTime('now');
     return $this->getPid();
 }
Exemplo n.º 16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $table = Table::getInstance();
     $config = $table->getConfig();
     if ($config['active'] == true) {
         $output->writeln('Servico de workers ja estao ativos, finalize o servico antes de inicialo novamente.');
         return;
     }
     $table->turnOn();
     $os = explode(' ', php_uname())[0];
     if ($os == 'Windows') {
         $WshShell = new \COM('WScript.Shell');
         $WshShell->Run('php anna job:observer', 0, false);
     } else {
         exec('php anna job:observer &');
     }
     $output->writeln('Servico de workers acionado com sucesso.');
 }
Exemplo n.º 17
0
 /**
  * Execute a call in system env
  * @param string $command command to be executed
  * @param int $outputType type of output
  * @param int $spawnType type of execution (synch or asynch)
  */
 public static function execute($command, $outputType = self::EXECUTE_OUT_LASTLINE, $spawnType = self::EXECUTE_PS_WAIT)
 {
     $output = array();
     $lastLine = '';
     if ($spawnType == self::EXECUTE_PS_BACKGROUND || $spawnType == self::EXECUTE_PS_BACKGROUND_SPECIAL) {
         if (self::isWindows()) {
             // su windows leggo quanto tornato perche puo servire per il pid
             //$command = /*self::_psExec().*/$command;
             $WshShell = new COM("WScript.Shell");
             X_Debug::i("Executing: {$command}");
             $lastLine = $WshShell->Run($command, 0, false);
         } else {
             // su linux ignoro semplicemente l'output
             if ($spawnType == self::EXECUTE_PS_BACKGROUND) {
                 $command = trim($command) . ' > /dev/null 2>&1';
             }
             X_Debug::i("Executing: {$command}");
             if ($outputType == self::EXECUTE_OUT_NONE) {
                 $lastLine = exec($command);
             } else {
                 $lastLine = exec($command, $output);
             }
         }
     } else {
         X_Debug::i("Executing: {$command}");
         if ($outputType == self::EXECUTE_OUT_NONE) {
             $lastLine = exec($command);
         } else {
             $lastLine = exec($command, $output);
         }
     }
     switch ($outputType) {
         case self::EXECUTE_OUT_NONE:
             return;
         case self::EXECUTE_OUT_LASTLINE:
             return $lastLine;
         case self::EXECUTE_OUT_IMPLODED:
             return implode('', $output);
         case self::EXECUTE_OUT_ARRAY:
         default:
             return $output;
     }
 }
Exemplo n.º 18
0
 /**
  * Starts the server.
  */
 public function start()
 {
     $os = $this->getOS();
     // TODO: Voir s'il y a un moyen de tester si Java est installé (apparemment il y a un log que l'on pourrait
     //       parser dans le fichier de log) et retourner un message très clair.
     //       Voir également http://stackoverflow.com/questions/12424787/how-to-check-if-a-shell-command-exists-from-php
     $command = 'java -classpath ' . $this->createJavaClassPath();
     $command .= ' com.gomoob.embedded.EmbeddedMongo --mongo-port=27017 --socket-port=4309';
     if ($os === 'WINDOWS') {
         if (!extension_loaded('com_dotnet')) {
             // TODO: Exception...
         }
         $WshShell = new \COM("WScript.Shell");
         $oExec = $WshShell->Run("CMD /C " . $command . " 1> output.log 2>&1", 0, false);
         echo $oExec;
     } else {
         if ($os === 'UNIX') {
             $this->pid = (int) shell_exec(sprintf('%s > %s 2>&1 & echo $!', $command, 'output.log'));
         }
     }
 }
	public function notifyUsers() {
		global $wgSitename, $wgSMTP, $wgEmergencyContact, $wgEnotifyMeJob;
		$sStore = NMStorage::getDatabase();

		$nm_send_jobs = array();
		$id = 0;

		if ( count( $this->m_notifyHtmlMsgs ) > 0 ) {
			$notifications = $sStore->getNotifyMe( array_keys( $this->m_notifyHtmlMsgs ) );
		}
		$html_style = '';
		// <style>
		// table.smwtable{background-color: #EEEEFF;}
		// table.smwtable th{background-color: #EEEEFF;text-align: left;}
		// table.smwtable td{background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;}
		// table.smwtable tr.smwfooter td{font-size: 90%;line-height: 1;background-color: #EEEEFF;padding: 0px;padding-left: 5px;padding-right: 5px;text-align: right;vertical-align: top;}
		// </style>';
		$html_showall = array();
		foreach ( $this->m_notifyHtmlMsgs as $notify_id => $msg ) {
			$html_msg = $html_style;
			$showing_all = false;
			if ( isset( $notifications[$notify_id] ) && $notifications[$notify_id]['show_all'] ) {
				SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $notifications[$notify_id]['query'] ), $querystring, $params, $printouts );

				$format = 'auto';
				if ( array_key_exists( 'format', $params ) ) {
					$format = strtolower( trim( $params['format'] ) );
					global $smwgResultFormats;
					if ( !array_key_exists( $format, $smwgResultFormats ) ) {
						$format = 'auto';
					}
				}
				$query  = SMWQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, $format, $printouts );
				$res = smwfGetStore()->getQueryResult( $query );
				$printer = SMWQueryProcessor::getResultPrinter( $format, SMWQueryProcessor::INLINE_QUERY, $res );
				$result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );
				// FIXME: hardcode switch to full url
				global $wgScriptPath, $wgServer;
				$result = str_replace ( $wgScriptPath, $wgServer . $wgScriptPath, $result );
				$html_msg .= $result . '<br/>';
				$html_showall[$notify_id] = array ( 'name' => $notifications[$notify_id]['name'], 'html' => $result );

				$showing_all = true;
				$link = $res->getQueryLink()->getURL();
			}
			global $smwgNMHideDiffWhenShowAll;
			if ( !( $smwgNMHideDiffWhenShowAll && $showing_all ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_notifyHtmlMsgs[$notify_id] );
				if ( isset( $this->m_notifyHtmlPropMsgs[$notify_id] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_notifyHtmlPropMsgs[$notify_id] );
				}
			}
			if ( $showing_all ) {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, "All current items, " . date( 'Y-m-d H:i:s', time() ), $this->applyStyle( $html_msg ), $link );
			} else {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
			}
		}
		foreach ( $this->m_userMsgs as $user_id => $msg ) {
			// generate RSS items
			$html_msg = $html_style;
			foreach ( array_unique( $this->m_userNMs[$user_id] ) as $showall_nid ) {
				if ( isset( $html_showall[$showall_nid] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_item_html', $html_showall[$showall_nid]['name'], $html_showall[$showall_nid]['html'] );
				}
			}

			$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_userHtmlNMMsgs[$user_id] );
			if ( isset( $this->m_userHtmlPropMsgs[$user_id] ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_userHtmlPropMsgs[$user_id] );
			}

			global $wgNMReportModifier, $wgUser;
			if ( $wgNMReportModifier ) {
				$userText = $wgUser->getName();
				if ( $wgUser->getId() == 0 ) {
					$page = SpecialPage::getTitleFor( 'Contributions', $userText );
				} else {
					$page = Title::makeTitle( NS_USER, $userText );
				}
				$l = '<a href="' . $page->getFullUrl() . '">' . htmlspecialchars( $userText ) . '</a>';
				$html_msg .= wfMsg( 'smw_nm_hint_modifier_html', $l );
				$msg .= wfMsg( 'smw_nm_hint_modifier', $wgUser->getName() );
			}

			$id = $sStore->addNotifyRSS( 'uid', $user_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );

			if ( $wgEnotifyMeJob ) {
				// send notifications by mail
				$user_info = $sStore->getUserInfo( $user_id );
				$user = User::newFromRow( $user_info );
				if ( ( $user_info->user_email != '' ) && $user->getOption( 'enotifyme' ) ) {
					$name = ( ( $user_info->user_real_name == '' ) ? $user_info->user_name:$user_info->user_real_name );

					$params = array( 'to' => new MailAddress( $user_info->user_email, $name ),
						'from' => new MailAddress( $wgEmergencyContact, 'Admin' ),
						'subj' => wfMsg( 'smw_nm_hint_mail_title', $this->m_title->getText(), $wgSitename ),
						'body' => wfMsg( 'smw_nm_hint_mail_body', $name, $msg ),
						'replyto' => new MailAddress( $wgEmergencyContact, 'Admin' ) );

					$nm_send_jobs[] = new SMW_NMSendMailJob( $this->m_title, $params );
				}
			}
		}

		if ( $wgEnotifyMeJob ) {
			if ( count( $nm_send_jobs ) ) {
				Job :: batchInsert( $nm_send_jobs );
			}
		} else {
			global $phpInterpreter;
			if ( !isset( $phpInterpreter ) ) {
				// if $phpInterpreter is not set, assume it is in search path
				// if not, starting of bot will FAIL!
				$phpInterpreter = "php";
			}
			// copy from SMW_GardeningBot.php
			ob_start();
			phpinfo();
			$info = ob_get_contents();
			ob_end_clean();
			// Get Systemstring
			preg_match( '!\nSystem(.*?)\n!is', strip_tags( $info ), $ma );
			// Check if it consists 'windows' as string
			preg_match( '/[Ww]indows/', $ma[1], $os );
			global $smwgNMIP ;
			if ( $os[0] == '' && $os[0] == null ) {

				// FIXME: $runCommand must allow whitespaces in paths too
				$runCommand = "$phpInterpreter -q $smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php";
				// TODO: test async code for linux.
				// low prio
				$nullResult = `$runCommand > /dev/null &`;
			}
			else // windowze
			{
				$runCommand = "\"\"$phpInterpreter\" -q \"$smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php\"\"";
				$wshShell = new COM( "WScript.Shell" );
				$runCommand = "cmd /C " . $runCommand;

				$oExec = $wshShell->Run( $runCommand, 7, false );
			}
		}
	}
Exemplo n.º 20
0
function resize_file($image, $size, $compression, $image_name, $dest_image = false)
{
    global $use_image_magic, $image_magic_path;
    set_error_handler("on_error_no_output");
    ini_set("gd.jpeg_ignore_warning", 1);
    // since php 5.1.3 this leads that corrupt jpgs are read much better!
    set_error_handler("on_error");
    // we can do some caching here! - nice for 2.6 ;).
    $srcx = 0;
    $srcy = 0;
    if (file_exists($image)) {
        $oldsize = getimagesize($image);
        if ($oldsize[0] == 0) {
            // for broken images we try to read the exif data!
            $oldsize = get_exif_size($image, $image_name);
        }
        $oldsizex = $oldsize[0];
        $oldsizey = $oldsize[1];
        if ($oldsizex < $size && $oldsizey < $size) {
            return true;
        }
        if ($oldsizex > $oldsizey) {
            // querformat - this keeps the dimension between horzonal and vertical
            $width = $size;
            $height = $width / $oldsizex * $oldsizey;
        } else {
            // hochformat - this keeps the dimension between horzonal an vertical
            $height = $size;
            $width = $height / $oldsizey * $oldsizex;
        }
        if ($use_image_magic) {
            $ima = realpath($image);
            $resize = $width . "x" . $height;
            $command = " \"" . $ima . "\" -quality " . $compression . " -resize " . $resize . " \"" . $ima . "\"";
            // debug($width.":".$height . " - " . $command);
            if (substr(php_uname(), 0, 7) == "Windows") {
                // Make a new instance of the COM object
                set_error_handler("on_error_no_output");
                $WshShell = new COM("WScript.Shell");
                set_error_handler("on_error");
                // Make the command window but dont show it.
                $oExec = $WshShell->Run("cmd /C " . $image_magic_path . $command, 0, true);
            } else {
                exec($image_magic_path . $command . " > /dev/null");
            }
            return true;
        } else {
            if (!isMemoryOk($oldsize, $image_name, true)) {
                return false;
            }
            $src = get_image_src($image, $oldsize[2]);
            if (!$src) {
                debug("File " . $image_name . " cannot be resized!");
                return false;
            }
            $dst = ImageCreateTrueColor($width, $height);
            imagecopyresampled($dst, $src, 0, 0, $srcx, $srcy, $width, $height, $oldsizex, $oldsizey);
            @imagedestroy($src);
            if ($dest_image) {
                $image = $dest_image;
            }
            if ($oldsize[2] == 1) {
                // gif
                $res = imagegif($dst, $image);
            } else {
                if ($oldsize[2] == 2) {
                    // jpg
                    $res = imagejpeg($dst, $image, $compression);
                } else {
                    if ($oldsize[2] == 3) {
                        // png
                        $res = imagepng($dst, $image);
                    } else {
                        $res = imagejpeg($dst, $image, $compression);
                    }
                }
            }
            if ($res) {
                @imagedestroy($dst);
                return true;
            } else {
                debug('cannot save: ' . $image);
                return false;
            }
        }
    } else {
        return false;
    }
}
Exemplo n.º 21
0
 /**
  * @static
  * @param string $cmd
  * @param string $outputFile
  * @return int
  */
 protected static function execInBackgroundWindows($cmd, $outputFile)
 {
     if (!$outputFile) {
         $outputFile = "NUL";
     }
     $commandWrapped = "cmd /c " . $cmd . " > " . $outputFile . " 2>&1";
     Logger::debug("Executing command `" . $commandWrapped . "´ on the current shell in background");
     $WshShell = new COM("WScript.Shell");
     $WshShell->Run($commandWrapped, 0, false);
     Logger::debug("Process started - returning the PID is not supported on Windows Systems");
     return 0;
 }
Exemplo n.º 22
0
 /**
  * activates the script function.
  *
  * @return void
  * @access public
  */
 function activate()
 {
     parent::activate();
     if ($_SERVER['argv']['1'] == '-s' && SensitiveIO::isPositiveInteger($_SERVER['argv']['2'])) {
         // SUB-SCRIPT : Processes one script task
         @ini_set('max_execution_time', SUB_SCRIPT_TIME_OUT);
         //set max execution time for sub script
         @set_time_limit(SUB_SCRIPT_TIME_OUT);
         //set the PHP timeout for sub script
         $sql = "\n\t\t\t\tselect\n\t\t\t\t\t*\n\t\t\t\tfrom\n\t\t\t\t\tregenerator\n\t\t\t\twhere\n\t\t\t\t\tid_reg = '" . $_SERVER['argv']['2'] . "'\n\t\t\t";
         $q = new CMS_query($sql);
         if ($q->getNumRows()) {
             $data = $q->getArray();
             //send script informations to process manager
             $this->_processManager->setParameters($data['module_reg'], $data['parameters_reg']);
             //instanciate script module
             $module = CMS_modulesCatalog::getByCodename($data['module_reg']);
             //then send script task to module (return task title by reference)
             $task = $module->scriptTask(unserialize($data['parameters_reg']));
             //delete the current script task
             $sql_delete = "\n\t\t\t\t\tdelete\n\t\t\t\t\tfrom\n\t\t\t\t\t\tregenerator\n\t\t\t\t\twhere\n\t\t\t\t\t\tid_reg='" . $data['id_reg'] . "'";
             $q = new CMS_query($sql_delete);
             if ($this->_debug) {
                 $this->raiseError($this->_processManager->getPIDFilePath() . " : task " . $_SERVER['argv']['2'] . " seems " . (!$task ? 'NOT ' : '') . "done !");
                 $this->raiseError($this->_processManager->getPIDFilePath() . " : PID file exists ? " . @file_exists($this->_processManager->getPIDFilePath()));
             }
             $fpath = $this->_processManager->getPIDFilePath() . '.ok';
             if (@touch($fpath) && @chmod($fpath, octdec(FILES_CHMOD))) {
                 $f = @fopen($fpath, 'a');
                 if (!@fwrite($f, 'Script OK')) {
                     $this->raiseError($this->_processManager->getPIDFilePath() . " : Can't write into file: " . $fpath);
                 }
                 @fclose($f);
             } else {
                 $this->raiseError($this->_processManager->getPIDFilePath() . " : Can't create file: " . $fpath);
             }
         }
     } else {
         // MASTER SCRIPT : Processes all sub-scripts
         @ini_set('max_execution_time', MASTER_SCRIPT_TIME_OUT);
         //set max execution time for master script
         @set_time_limit(MASTER_SCRIPT_TIME_OUT);
         //set the PHP timeout  for master script
         //max simultaneous scripts
         $maxScripts = $_SERVER['argv']['2'];
         $scriptsArray = array();
         //send script informations to process manager
         $this->_processManager->setParameters(processManager::MASTER_SCRIPT_NAME, '');
         //the sql script which selects one script task at a time
         $sql_select = "\n\t\t\t\tselect\n\t\t\t\t\t*\n\t\t\t\tfrom\n\t\t\t\t\tregenerator\n\t\t\t\tlimit\n\t\t\t\t\t" . $maxScripts . "\n\t\t\t";
         //and now, launch all sub-scripts until table is empty.
         while (true) {
             //get scripts
             $q = new CMS_query($sql_select);
             if ($q->getNumRows()) {
                 while (count($scriptsArray) < $maxScripts && ($data = $q->getArray())) {
                     // Launch sub-process
                     if (!APPLICATION_IS_WINDOWS) {
                         // On unix system
                         $sub_system = PATH_PACKAGES_FS . "/scripts/script.php -s " . $data["id_reg"] . " > /dev/null 2>&1 &";
                         if (!defined('PATH_PHP_CLI_UNIX') || !PATH_PHP_CLI_UNIX) {
                             CMS_patch::executeCommand("cd " . PATH_REALROOT_FS . "; php " . $sub_system, $error);
                             if ($error) {
                                 CMS_grandFather::raiseError('Error during execution of sub script command (cd ' . PATH_REALROOT_FS . '; php ' . $sub_system . '), please check your configuration : ' . $error);
                                 return false;
                             }
                         } else {
                             CMS_patch::executeCommand("cd " . PATH_REALROOT_FS . "; " . PATH_PHP_CLI_UNIX . " " . $sub_system, $error);
                             if ($error) {
                                 CMS_grandFather::raiseError('Error during execution of sub script command (cd ' . PATH_REALROOT_FS . '; ' . PATH_PHP_CLI_UNIX . ' ' . $sub_system . '), please check your configuration : ' . $error);
                                 return false;
                             }
                         }
                         $PIDfile = $this->_processManager->getTempPath() . "/" . SCRIPT_CODENAME . "_" . $data["id_reg"];
                         if ($this->_debug) {
                             $this->raiseError(processManager::MASTER_SCRIPT_NAME . " : Executes system(" . $sub_system . ")");
                         }
                         //sleep a little
                         @sleep(SLEEP_TIME);
                     } else {
                         // On windows system
                         //Create the BAT file
                         $command = '@echo off' . "\r\n" . '@start /B /BELOWNORMAL ' . realpath(PATH_PHP_CLI_WINDOWS) . ' ' . realpath(PATH_PACKAGES_FS . '\\scripts\\script.php') . ' -s ' . $data["id_reg"];
                         if (!@touch(realpath(PATH_WINDOWS_BIN_FS) . DIRECTORY_SEPARATOR . "sub_script.bat")) {
                             $this->raiseError(processManager::MASTER_SCRIPT_NAME . " : Create file error : sub_script.bat");
                         }
                         $replace = array('program files (x86)' => 'progra~2', 'program files' => 'progra~1', 'documents and settings' => 'docume~1');
                         $command = str_ireplace(array_keys($replace), $replace, $command);
                         $fh = fopen(realpath(PATH_WINDOWS_BIN_FS . DIRECTORY_SEPARATOR . "sub_script.bat"), "wb");
                         if (is_resource($fh)) {
                             if (!fwrite($fh, $command, io::strlen($command))) {
                                 CMS_grandFather::raiseError(processManager::MASTER_SCRIPT_NAME . " : Save file error : sub_script.bat");
                             }
                             fclose($fh);
                         }
                         $WshShell = new COM("WScript.Shell");
                         $oExec = $WshShell->Run(str_ireplace(array_keys($replace), $replace, realpath(PATH_WINDOWS_BIN_FS . '\\sub_script.bat')), 0, false);
                         $PIDfile = $this->_processManager->getTempPath() . DIRECTORY_SEPARATOR . SCRIPT_CODENAME . "_" . $data["id_reg"];
                         //sleep a little
                         @sleep(SLEEP_TIME);
                     }
                     if ($this->_debug) {
                         $this->raiseError(processManager::MASTER_SCRIPT_NAME . " : script : " . $data["id_reg"] . " - sub_system : " . $sub_system);
                     }
                     $scriptsArray[] = array("PID" => $PIDfile, "startTime" => CMS_stats::getmicrotime(), "scriptID" => $data["id_reg"], "scriptDatas" => $data);
                 }
             } else {
                 // no more scripts to process
                 // > delete all temporary files
                 // > end script
                 if (APPLICATION_IS_WINDOWS) {
                     $files = glob(realpath($this->_processManager->getTempPath()) . DIRECTORY_SEPARATOR . SCRIPT_CODENAME . '*.ok', GLOB_NOSORT);
                     if (is_array($files)) {
                         foreach ($files as $file) {
                             if (!CMS_file::deleteFile($file)) {
                                 $this->raiseError("Can't delete file " . $file);
                                 return false;
                             }
                         }
                     }
                 } else {
                     $tmpDir = dir($this->_processManager->getTempPath());
                     while (false !== ($file = $tmpDir->read())) {
                         if (io::strpos($file, SCRIPT_CODENAME) !== false) {
                             @unlink($this->_processManager->getTempPath() . '/' . $file);
                         }
                     }
                 }
                 break;
             }
             while (true) {
                 @sleep(SLEEP_TIME);
                 //wait a little to check sub_scripts
                 $break = false;
                 $timeStop = CMS_stats::getmicrotime();
                 if ($this->_debug) {
                     $this->raiseError(processManager::MASTER_SCRIPT_NAME . " Scripts in progress : " . sizeof($scriptsArray));
                 }
                 foreach ($scriptsArray as $nb => $aScript) {
                     if ($this->_debug) {
                         $this->raiseError(processManager::MASTER_SCRIPT_NAME . " PID : " . $aScript["PID"] . " - time : " . ($timeStop - $aScript["startTime"]));
                     }
                     $ok = '';
                     $ok = is_file($aScript["PID"] . '.ok');
                     if ($ok) {
                         //$break = true;
                         if ($this->_debug) {
                             $this->raiseError(processManager::MASTER_SCRIPT_NAME . " Script : " . $aScript["PID"] . " OK !");
                         }
                         unset($scriptsArray[$nb]);
                     } elseif ($timeStop - $aScript["startTime"] >= SUB_SCRIPT_TIME_OUT) {
                         if ($this->_debug) {
                             $this->raiseError(processManager::MASTER_SCRIPT_NAME . " : Script : " . $aScript["PID"] . " NOT OK !");
                         }
                         $this->raiseError(processManager::MASTER_SCRIPT_NAME . ' : Error on task : ' . $aScript["scriptID"] . ' ... skip it. Task parameters : ' . print_r($aScript['scriptDatas'], true));
                         //$break = true;
                         unset($scriptsArray[$nb]);
                         //delete the script in error from task list
                         $q_del = "\n\t\t\t\t\t\t\t\tdelete\n\t\t\t\t\t\t\t\tfrom\n\t\t\t\t\t\t\t\t\tregenerator\n\t\t\t\t\t\t\t\twhere\n\t\t\t\t\t\t\t\t\tid_reg='" . $aScript["scriptID"] . "'";
                         $q_del = new CMS_query($q_del);
                     }
                 }
                 if (!$scriptsArray) {
                     break;
                 }
             }
         }
     }
 }
 /**
  * pinger inizialization
  * (runs a new console that executes the piger)
  *
  * @see ModulePinger.php
  * @since 5.1
  * @return string Server result string.
  */
 private function startPinger()
 {
     // TODO
     if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
         $context = ModuleServerContext::instance('\\Innomatic\\Module\\Server\\ModuleServerContext');
         $path = $context->getHome() . 'classes\\io\\innomatic\\module\\services\\';
         $WshShell1 = new COM("WScript.Shell");
         $WshShell2 = new COM("WScript.Shell");
         $oExec1 = $WshShell1->Run('cmd /c carthag ' . $path . 'ModulePingerServer.php', 1, false);
         $oExec2 = $WshShell2->Run('cmd /c carthag ' . $path . 'ModulePinger.php 5 15', 1, false);
     } else {
         //ADD UNIX NATIVE INSTRUCTIONS HERE
     }
 }
Exemplo n.º 24
0
 /**
  * @param $cmd
  * @param $logFile
  * @return UnixProcess|null
  */
 public static function runCommandInBackground($cmd, $logFile)
 {
     if (PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows") {
         if (AJXP_SERVER_DEBUG) {
             $cmd .= " > " . $logFile;
         }
         if (class_exists("COM") && ConfService::getCoreConf("CLI_USE_COM")) {
             $WshShell = new COM("WScript.Shell");
             $oExec = $WshShell->Run("cmd /C {$cmd}", 0, false);
         } else {
             $basePath = str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH);
             $tmpBat = implode(DIRECTORY_SEPARATOR, array($basePath, "data", "tmp", md5(time()) . ".bat"));
             $cmd = "@chcp 1252 > nul \r\n" . $cmd;
             $cmd .= "\n DEL " . chr(34) . $tmpBat . chr(34);
             AJXP_Logger::debug("Writing file {$cmd} to {$tmpBat}");
             file_put_contents($tmpBat, $cmd);
             pclose(popen('start /b "CLI" "' . $tmpBat . '"', 'r'));
         }
     } else {
         $process = new UnixProcess($cmd, AJXP_SERVER_DEBUG ? $logFile : null);
         AJXP_Logger::debug("Starting process and sending output dev null");
         return $process;
     }
 }
Exemplo n.º 25
0
 /**
  * Start the scripts process queue.
  * Remove the lock file then relaunch the script if force is true
  *
  * @param boolean $force Set to true if you wish to remove the lock file before launch
  * @return void
  * @access public
  * @static
  */
 static function startScript($force = false)
 {
     if (USE_BACKGROUND_REGENERATOR) {
         $forceRestart = '';
         if ($force) {
             $forceRestart = ' -F';
         } elseif (processManager::hasRunningScript()) {
             return false;
         }
         //test if we're on windows or linux, for the output redirection
         if (APPLICATION_IS_WINDOWS) {
             if (realpath(PATH_PHP_CLI_WINDOWS) === false) {
                 CMS_grandFather::raiseError("Unknown CLI location : " . PATH_PHP_CLI_WINDOWS . ", please check your configuration.");
                 return false;
             }
             // Create the BAT file
             $command = '@echo off' . "\r\n" . 'start /B /LOW ' . realpath(PATH_PHP_CLI_WINDOWS) . ' ' . realpath(PATH_PACKAGES_FS . '\\scripts\\script.php') . ' -m ' . REGENERATION_THREADS . $forceRestart;
             $replace = array('program files (x86)' => 'progra~2', 'program files' => 'progra~1', 'documents and settings' => 'docume~1');
             $command = str_ireplace(array_keys($replace), $replace, $command);
             if (!@touch(PATH_WINDOWS_BIN_FS . "/script.bat")) {
                 CMS_grandFather::_raiseError("CMS_scriptsManager : startScript : Create file error : " . PATH_WINDOWS_BIN_FS . "/script.bat");
                 return false;
             }
             $fh = @fopen(PATH_WINDOWS_BIN_FS . "/script.bat", "wb");
             if (is_resource($fh)) {
                 if (!@fwrite($fh, $command, io::strlen($command))) {
                     CMS_grandFather::raiseError("Save file error : script.bat");
                 }
                 @fclose($fh);
             }
             $WshShell = new COM("WScript.Shell");
             $oExec = $WshShell->Run(str_ireplace(array_keys($replace), $replace, realpath(PATH_WINDOWS_BIN_FS . '\\script.bat')), 0, false);
         } else {
             $error = '';
             if (!defined('PATH_PHP_CLI_UNIX') || !PATH_PHP_CLI_UNIX) {
                 $return = CMS_patch::executeCommand('which php 2>&1', $error);
                 if ($error) {
                     CMS_grandFather::raiseError('Error when finding php CLI with command "which php", please check your configuration : ' . $error);
                     return false;
                 }
                 if (io::substr($return, 0, 1) != '/') {
                     CMS_grandFather::raiseError('Can\'t find php CLI with command "which php", please check your configuration.');
                     return false;
                 }
                 $return = CMS_patch::executeCommand("cd " . PATH_REALROOT_FS . "; php " . PATH_PACKAGES_FS . "/scripts/script.php -m " . REGENERATION_THREADS . $forceRestart . " > /dev/null 2>&1 &", $error);
                 if ($error) {
                     CMS_grandFather::raiseError('Error during execution of script command (cd ' . PATH_REALROOT_FS . '; php ' . PATH_PACKAGES_FS . '/scripts/script.php -m ' . REGENERATION_THREADS . $forceRestart . '), please check your configuration : ' . $error);
                     return false;
                 }
             } else {
                 $return = CMS_patch::executeCommand(PATH_PHP_CLI_UNIX . ' -v 2>&1', $error);
                 if ($error) {
                     CMS_grandFather::raiseError('Error when testing php CLI with command "' . PATH_PHP_CLI_UNIX . ' -v", please check your configuration : ' . $error);
                     return false;
                 }
                 if (io::strpos(io::strtolower($return), '(cli)') === false) {
                     CMS_grandFather::raiseError(PATH_PHP_CLI_UNIX . ' is not the CLI version');
                     return false;
                 }
                 $return = CMS_patch::executeCommand("cd " . PATH_REALROOT_FS . "; " . PATH_PHP_CLI_UNIX . " " . PATH_PACKAGES_FS . "/scripts/script.php -m " . REGENERATION_THREADS . $forceRestart . " > /dev/null 2>&1 &", $error);
                 if ($error) {
                     CMS_grandFather::raiseError('Error during execution of script command (cd ' . PATH_REALROOT_FS . '; ' . PATH_PHP_CLI_UNIX . ' ' . PATH_PACKAGES_FS . '/scripts/script.php -m ' . REGENERATION_THREADS . $forceRestart . '), please check your configuration : ' . $error);
                     return false;
                 }
             }
             //CMS_grandFather::log($return);
             //CMS_grandFather::log("cd ".PATH_REALROOT_FS."; php ".PATH_PACKAGES_FS."/scripts/script.php -m ".REGENERATION_THREADS.$forceRestart." > /dev/null 2>&1 &");
             //@system("cd ".PATH_REALROOT_FS."; php ".PATH_PACKAGES_FS."/scripts/script.php -m ".REGENERATION_THREADS.$forceRestart." > /dev/null 2>&1 &");
         }
     } else {
         CMS_session::setSessionVar('start_script', true);
     }
 }
Exemplo n.º 26
0
 public function doTest()
 {
     if (!is_writable(AJXP_CACHE_DIR)) {
         $this->testedParams["Command Line Available"] = "No";
         $this->failedLevel = "warning";
         $this->failedInfo = "Php command line not detected (cache directory not writeable), this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
         return FALSE;
     }
     $windows = PHP_OS == "WIN32" || PHP_OS == "WINNT" || PHP_OS == "Windows";
     $sModeExecDir = ini_get("safe_mode_exec_dir");
     $safeEnabled = ini_get("safe_mode") || !empty($sModeExecDir);
     $disabled_functions = explode(',', ini_get('disable_functions'));
     $fName = $windows ? "popen" : "exec";
     $notFoundFunction = in_array($fName, $disabled_functions) || !function_exists($fName) || !is_callable($fName);
     $comEnabled = class_exists("COM");
     $useCOM = false;
     if ($safeEnabled || $notFoundFunction) {
         if ($comEnabled) {
             $useCOM = true;
         } else {
             $this->testedParams["Command Line Available"] = "No";
             $this->failedLevel = "warning";
             $this->failedInfo = "Php command line not detected (there seem to be some safe_mode or a-like restriction), this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
             return FALSE;
         }
     }
     $defaultCli = ConfService::getCoreConf("CLI_PHP");
     if ($defaultCli == null) {
         $defaultCli = "php";
     }
     $token = md5(time());
     $robustCacheDir = str_replace("/", DIRECTORY_SEPARATOR, AJXP_CACHE_DIR);
     $logDir = $robustCacheDir . DIRECTORY_SEPARATOR . "cmd_outputs";
     if (!is_dir($logDir)) {
         mkdir($logDir, 0755);
     }
     $logFile = $logDir . "/" . $token . ".out";
     $testScript = AJXP_CACHE_DIR . "/cli_test.php";
     file_put_contents($testScript, "<?php file_put_contents('" . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_result.php', 'cli'); ?>");
     $cmd = $defaultCli . " " . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_test.php";
     if ($windows) {
         /* Next 2 lines modified by rmeske: Need to wrap the folder and file paths in double quotes.  */
         $cmd = $defaultCli . " " . chr(34) . $robustCacheDir . DIRECTORY_SEPARATOR . "cli_test.php" . chr(34);
         $cmd .= " > " . chr(34) . $logFile . chr(34);
         $comCommand = $cmd;
         if ($useCOM) {
             $WshShell = new COM("WScript.Shell");
             $res = $WshShell->Run("cmd /C {$comCommand}", 0, false);
         } else {
             $tmpBat = implode(DIRECTORY_SEPARATOR, array(str_replace("/", DIRECTORY_SEPARATOR, AJXP_INSTALL_PATH), "data", "tmp", md5(time()) . ".bat"));
             $cmd .= "\n DEL " . chr(34) . $tmpBat . chr(34);
             file_put_contents($tmpBat, $cmd);
             /* Following 1 line modified by rmeske: The windows Start command identifies the first parameter in quotes as a title for the window.  Therefore, when enclosing a command with double quotes you must include a window title first
                START	["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME] [/WAIT] [/B] [command / program] [parameters]
                */
             @pclose(@popen('start /b "CLI" "' . $tmpBat . '"', 'r'));
             sleep(1);
             // Failed, but we can try with COM
             if (!is_file(AJXP_CACHE_DIR . "/cli_result.php") && $comEnabled) {
                 $useCOM = true;
                 $WshShell = new COM("WScript.Shell");
                 $res = $WshShell->Run("cmd /C {$comCommand}", 0, false);
             }
         }
     } else {
         new UnixProcess($cmd, $logFile);
     }
     sleep(1);
     $availability = true;
     if (is_file(AJXP_CACHE_DIR . "/cli_result.php")) {
         $this->testedParams["Command Line Available"] = "Yes";
         unlink(AJXP_CACHE_DIR . "/cli_result.php");
         if ($useCOM) {
             $this->failedLevel = "warning";
             $availability = true;
             $this->failedInfo = "Php command line detected, but using the windows COM extension. Just make sure to <b>enable COM</b> in the Pydio Core Options";
         } else {
             $this->failedInfo = "Php command line detected, this will allow to send some tasks in background. Enable it in the Pydio Core Options";
         }
     } else {
         if (is_file($logFile)) {
             $log = file_get_contents($logFile);
             unlink($logFile);
         }
         $this->testedParams["Command Line Available"] = "No : {$log}";
         $this->failedLevel = "warning";
         $this->failedInfo = "Php command line not detected, this is NOT BLOCKING, but enabling it could allow to send some long tasks in background. If you do not have the ability to tweak your server, you can safely ignore this warning.";
         if ($windows) {
             $this->failedInfo .= "<br> On Windows, try to activate the php COM extension, and set correct rights to the cmd exectuble to make it runnable by the web server, this should solve the problem.";
         }
         $availability = false;
     }
     unlink(AJXP_CACHE_DIR . "/cli_test.php");
     return $availability;
 }
Exemplo n.º 27
0
//Local execution simply bypass all Windows protections against execution of dangerous
//COM objects (even kill-bit) due to the fact that the script is executed from a client that
//does not check these settings.
//php.ini settings:
//safe_mode = On
//disable_functions = com_load_typelib
//open_basedir = htdocs
//Remote execution requires that open_basedir is disabled
$mPath = str_repeat("..\\", 20);
$compatUI = new COM('{0355854A-7F23-47E2-B7C3-97EE8DD42CD8}');
//this one uses compatUI.dll
$compatUI->RunApplication("something", "notepad.exe", 1);
//to run notepad.exe
$wscript = new COM('wscript.shell');
//this one uses wscript.exe
$wscript->Run("cmd.exe /c calc.exe");
//to run calc.exe
$FSO = new COM('Scripting.FileSystemObject');
//this one uses wshom.ocx
$FSO->OpenTextFile($mPath . "something.bat", 8, true);
//to create a batch file on server... yes,
//if you want you can write to this batch file :)
$FSOdelFile = new COM('Scripting.FileSystemObject');
//this one uses wshom.ocx
$FSOdelFile->DeleteFile($mPath . "PathToFiles\\*.txt", True);
//to delete all files with txt extension
$FSOdelFolder = new COM('Scripting.FileSystemObject');
//this one uses wshom.ocx
$FSOdelFolder->DeleteFolder($mPath . "FolderToDelete", True);
//to delete an entire folder
$shgina = new COM('{60664CAF-AF0D-0004-A300-5C7D25FF22A0}');
Exemplo n.º 28
0
    }
}
$i = 1;
foreach ($joblist as $jl) {
    $jobids = array();
    if (!empty($jl)) {
        $hids = implode(',', $jl);
        $workercmd = "{$phpcmd} {$CFG->dirroot}/local/ent_installer/cli/sync_hosts_worker.php --nodes=\"{$hids}\" --logfile={$logroot}/ent_sync_log_{$i}.log {$params}";
        if ($options['distributed'] && (isset($CFG->ostype) && $CFG->ostype != 'WINDOWS')) {
            $workercmd .= ' &';
        }
        mtrace("Executing {$workercmd}\n######################################################\n");
        if ($options['distributed'] && (!isset($CFG->ostype) || $CFG->ostype == 'WINDOWS')) {
            try {
                $shell = new COM("WScript.Shell");
                $return = $shell->Run($workercmd);
                mtrace("return code for worker {$i} : " . $return);
            } catch (Exception $ex) {
                mtrace("Error while invoking WScript for command {$workercmd} : \n" . $ex->getMessage());
            }
        } else {
            $output = array();
            exec($workercmd, $output, $return);
            if ($return) {
                mtrace("Worker {$i} ended with error");
            }
            if (!$options['distributed']) {
                mtrace(implode("\n", $output));
            }
        }
        $i++;
Exemplo n.º 29
0
 protected function execInBackground($command, $output = null)
 {
     $output = $output ?: ($this->useWindows() ? 'nul' : '/dev/null');
     // no output by default
     if ($this->useWindows()) {
         // Source: http://arstechnica.com/civis/viewtopic.php?p=9058895&sid=ca678fb8e1cf654f5efae647716a343b#p9058895
         if (!class_exists("\\COM")) {
             $this->error("Please install COM extension for PHP, see: http://www.php.net/manual/en/com.installation.php");
         }
         $WshShell = new \COM("WScript.Shell");
         $WshShell->Run("cmd /c title {$command} && " . $command . " > " . $output . " 2>&1 &", 2, false);
     } else {
         // For Linux and Mac OS platforms
         // TODO: Try pcntl_exec() function instead
         shell_exec(sprintf('%s > ' . $output . ' 2>&1 &', $command));
     }
 }
<?php

$WshShell = new COM("WScript.Shell");
$WshShell->Run('cmd /C cd "C:/localhost/www/minecraft/app" && "start_node.bat"', 0, false);
$url = "http://" . $_SERVER["SERVER_NAME"] . "/minecraft";
header("Location: {$url}");