Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * CronJob Class
- *
- * @see \ssh2_connect()
- */
- class CronJobController extends CI_Controller
- {
- /**
- * Represents our connection/resource
- *
- * @var resource $conn
- */
- private $conn;
- /**
- * Represents the path for the file.
- *
- * @var string $path
- */
- private $path;
- /**
- * Represents the name of our temporary cron file
- *
- * @var string $handle
- */
- private $handle;
- /**
- * Represents the full path and name of the temporary
- * cron file.
- *
- * @var string $cronFile
- */
- private $cronFile;
- // ------------------------------------------------------------------------
- /**
- * The class constructor will primarily be responsible for establishing and
- * authenticating the SSH2 connection. It will take four arguments, each of
- * which will have a default value of NULL.
- *
- * @param null $host The ip address of the remote server we want to
- * connect to.
- * @param null $port The port to be used for the SSH2 connection.
- * @param null $username Represents the user's log in name for the server.
- * @param null $password Represents the user's password for the server.
- */
- public function __construct($host = null, $port = null, $username = null, $password = null)
- {
- parent::__construct();
- $path_length = strrpos(__FILE__, "/");
- $this->path = substr(__FILE__, 0, $path_length) . '/';
- $this->handle = 'crontab.txt';
- $this->cronFile = "{$this->path}{$this->handle}";
- try {
- if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) {
- throw new Exception("Please specify the host, port, username and password!");
- }
- $this->conn = @ssh2_connect($host, $port);
- if (!$this->conn) {
- throw new Exception("The SSH2 connection could not be established.");
- }
- $authentication = @ssh2_auth_password($this->conn, $username, $password);
- if (!$authentication) {
- throw new Exception("Could not authenticate '{$username}' using password: '{$password}'.");
- }
- } catch (Exception $e) {
- $this->errorMessage($e->getMessage());
- }
- }
- // ------------------------------------------------------------------------
- /**
- * This method will be responsible for executing commands on the remote server.
- * It's comparable to manually entering commands into a shell like, say, PuTTY.
- * To allow for greater flexibility, we'll make this method public so that users
- * can actually execute any other commands they may need to run. We'll also
- * allow for any number of arguments so long as at least one is specified. These
- * arguments will represent the commands we want to run using the ssh2_exec()
- * function.
- *
- * @return $this
- */
- public function exec()
- {
- $argumentCount = func_num_args();
- try {
- if (!$argumentCount) {
- throw new Exception("There is nothing to execute, no arguments specified.");
- }
- $arguments = func_get_args();
- $commandString = ($argumentCount > 1) ? implode(" && ", $arguments): $arguments[0];
- $stream = @ssh2_exec($this->conn, $commandString);
- if (!$stream) {
- throw new Exception("Unable to execute the specified commands: <br />{$commandString}");
- }
- } catch (Exception $e) {
- $this->errorMessage($e->getMessage());
- }
- return $this;
- }
- // ------------------------------------------------------------------------
- /**
- * The next method, writeToFile(), will be responsible for writing the
- * existing cronTab to a temporary file or creating a blank temp. file
- * should no cron jobs exist.
- *
- * @param null $path The path for the temporary file we'll be creating
- * @param null $handle The name we should use when creating it.
- *
- * @return $this
- */
- public function writeToFile($path = null, $handle = null)
- {
- if (!$this->crontabFileExists()) {
- $this->handle = is_null($handle)
- ? $this->handle
- : $handle;
- $this->path = is_null($path)
- ? $this->path
- : $path;
- $this->cronFile = "{$this->path}{$this->handle}";
- $init_cron = "crontab -l > {$this->cronFile} && [ -f {$this->cronFile} ] || > {$this->cronFile}";
- $this->exec($init_cron);
- }
- return $this;
- }
- // ------------------------------------------------------------------------
- /**
- * This method, removeFile() is as easy as easy could be! We'll use our helper
- * method, crontabFileExists(), to check for the existence of the temporary cron
- * file and then execute the Linux command `rm` to delete it if it does. As usual,
- * we'll also return $this in order to maintain chainability.
- *
- * @return $this
- */
- public function removeFile()
- {
- if ($this->crontabFileExists()) {
- $this->exec("rm {$this->cronFile}");
- }
- return $this;
- }
- // ------------------------------------------------------------------------
- /**
- * This method will create new cron jobs by way of adding new jobs / lines to
- * the temporary cron file and then executing the crontab command on that file
- * which will install all of those jobs as a new cronTab. As such, appendCronjob()
- * will take one argument, $cronJobs, which will either be a string or an array of
- * strings representing the cron jobs to append.
- *
- * @param null $cronJobs
- *
- * @return $this
- */
- public function appendCronjob($cronJobs = null)
- {
- if (is_null($cronJobs)) {
- $this->errorMessage("Nothing to append! Please specify a cron job or an array of cron jobs.");
- }
- $appendCronfile = "echo '";
- $appendCronfile .= is_array($cronJobs) ? implode("\n", $cronJobs): $cronJobs;
- $appendCronfile .= "' >> {$this->cronFile}";
- $installCron = "crontab {$this->cronFile}";
- $this->writeToFile()->exec($appendCronfile, $installCron)->removeFile();
- return $this;
- }
- // ------------------------------------------------------------------------
- /**
- * Now that we can create new cron jobs, it's only logical that we have the
- * ability to remove them as well! The removeCronjob() method will take one
- * argument which will be a (simple) regular expression. This regEx will be
- * used to find matching jobs within the cronTab and remove them accordingly.
- * As with the appendCronjob() method, the first thing we'll do is check to
- * see if the $cron_jobs argument is NULL and halt execution if it is. If not,
- * we'll call the createFile() method in order write the cron tab to a file.
- *
- * @param mixed $cronJobs
- *
- * @return CronJobController
- */
- public function removeCronjob($cronJobs = null)
- {
- if (is_null($cronJobs)) {
- $this->errorMessage("Nothing to remove! Please specify a cron job or an array of cron jobs.");
- }
- $this->writeToFile();
- $cronArray = file($this->cronFile, FILE_IGNORE_NEW_LINES);
- if (empty($cronArray)) {
- $this->errorMessage("Nothing to remove! The cronTab is already empty.");
- }
- $originalCount = count($cronArray);
- if (is_array($cronJobs)) {
- foreach ($cronJobs as $cronRegex) {
- $cronArray = preg_grep($cronRegex, $cronArray, PREG_GREP_INVERT);
- }
- } else {
- $cronArray = preg_grep($cronJobs, $cronArray, PREG_GREP_INVERT);
- }
- return ($originalCount === count($cronArray))
- ? $this->removeFile()
- : $this->removeCrontab()
- ->appendCronjob($cronArray);
- }
- // ------------------------------------------------------------------------
- /**
- * Removing the entire cronTab is relatively simple to do. Essentially, we'll
- * just execute the crontab command with the -r flag set which removes the entire
- * cronTab for a given user. Since the crontab has been removed we might as well
- * remove the temporary cron file as well, should it exist. Then we'll return $this
- * in order to preserve chainability.
- *
- * @return $this
- */
- public function removeCrontab()
- {
- $this->exec("crontab -r")->removeFile();
- return $this;
- }
- // ------------------------------------------------------------------------
- /**
- * With the brunt of our cron management class written, we'll now take a look
- * at the two small but useful methods we've used throughout our class,
- * crontabFileExists() and errorMessage().
- *
- * @see \CronJobController::crontabFileExists()
- * @see \CronJobController::errorMessage()
- *
- * @return bool
- */
- private function crontabFileExists()
- {
- return file_exists($this->cronFile);
- }
- // ------------------------------------------------------------------------
- /**
- * This method will take one argument, a string, representing the error message
- * we want to display. We'll then call PHP's die() method in order to halt
- * execution and display this message. The string it self, will be concatenated
- * into a <pre> element with some simple style applied to it.
- *
- * @param $error
- */
- private function errorMessage($error)
- {
- die("<pre style='color:#EE2711'>ERROR: {$error}</pre>");
- }
- // ------------------------------------------------------------------------
- }
Add Comment
Please, Sign In to add comment