Guest User

Untitled

a guest
Jan 7th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.74 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * CronJob Class
  5. *
  6. * @see \ssh2_connect()
  7. */
  8. class CronJobController extends CI_Controller
  9. {
  10. /**
  11. * Represents our connection/resource
  12. *
  13. * @var resource $conn
  14. */
  15. private $conn;
  16.  
  17. /**
  18. * Represents the path for the file.
  19. *
  20. * @var string $path
  21. */
  22. private $path;
  23.  
  24. /**
  25. * Represents the name of our temporary cron file
  26. *
  27. * @var string $handle
  28. */
  29. private $handle;
  30.  
  31. /**
  32. * Represents the full path and name of the temporary
  33. * cron file.
  34. *
  35. * @var string $cronFile
  36. */
  37. private $cronFile;
  38.  
  39. // ------------------------------------------------------------------------
  40.  
  41. /**
  42. * The class constructor will primarily be responsible for establishing and
  43. * authenticating the SSH2 connection. It will take four arguments, each of
  44. * which will have a default value of NULL.
  45. *
  46. * @param null $host The ip address of the remote server we want to
  47. * connect to.
  48. * @param null $port The port to be used for the SSH2 connection.
  49. * @param null $username Represents the user's log in name for the server.
  50. * @param null $password Represents the user's password for the server.
  51. */
  52. public function __construct($host = null, $port = null, $username = null, $password = null)
  53. {
  54. parent::__construct();
  55. $path_length = strrpos(__FILE__, "/");
  56. $this->path = substr(__FILE__, 0, $path_length) . '/';
  57. $this->handle = 'crontab.txt';
  58. $this->cronFile = "{$this->path}{$this->handle}";
  59.  
  60. try {
  61. if (is_null($host) || is_null($port) || is_null($username) || is_null($password)) {
  62. throw new Exception("Please specify the host, port, username and password!");
  63.  
  64. }
  65.  
  66. $this->conn = @ssh2_connect($host, $port);
  67. if (!$this->conn) {
  68. throw new Exception("The SSH2 connection could not be established.");
  69.  
  70. }
  71.  
  72. $authentication = @ssh2_auth_password($this->conn, $username, $password);
  73. if (!$authentication) {
  74. throw new Exception("Could not authenticate '{$username}' using password: '{$password}'.");
  75.  
  76. }
  77.  
  78. } catch (Exception $e) {
  79. $this->errorMessage($e->getMessage());
  80. }
  81. }
  82.  
  83. // ------------------------------------------------------------------------
  84.  
  85. /**
  86. * This method will be responsible for executing commands on the remote server.
  87. * It's comparable to manually entering commands into a shell like, say, PuTTY.
  88. * To allow for greater flexibility, we'll make this method public so that users
  89. * can actually execute any other commands they may need to run. We'll also
  90. * allow for any number of arguments so long as at least one is specified. These
  91. * arguments will represent the commands we want to run using the ssh2_exec()
  92. * function.
  93. *
  94. * @return $this
  95. */
  96. public function exec()
  97. {
  98. $argumentCount = func_num_args();
  99.  
  100. try {
  101. if (!$argumentCount) {
  102. throw new Exception("There is nothing to execute, no arguments specified.");
  103.  
  104. }
  105.  
  106. $arguments = func_get_args();
  107.  
  108. $commandString = ($argumentCount > 1) ? implode(" && ", $arguments): $arguments[0];
  109.  
  110. $stream = @ssh2_exec($this->conn, $commandString);
  111. if (!$stream) {
  112. throw new Exception("Unable to execute the specified commands: <br />{$commandString}");
  113.  
  114. }
  115.  
  116. } catch (Exception $e) {
  117. $this->errorMessage($e->getMessage());
  118. }
  119.  
  120. return $this;
  121. }
  122.  
  123. // ------------------------------------------------------------------------
  124.  
  125. /**
  126. * The next method, writeToFile(), will be responsible for writing the
  127. * existing cronTab to a temporary file or creating a blank temp. file
  128. * should no cron jobs exist.
  129. *
  130. * @param null $path The path for the temporary file we'll be creating
  131. * @param null $handle The name we should use when creating it.
  132. *
  133. * @return $this
  134. */
  135. public function writeToFile($path = null, $handle = null)
  136. {
  137. if (!$this->crontabFileExists()) {
  138.  
  139. $this->handle = is_null($handle)
  140. ? $this->handle
  141. : $handle;
  142.  
  143. $this->path = is_null($path)
  144. ? $this->path
  145. : $path;
  146.  
  147. $this->cronFile = "{$this->path}{$this->handle}";
  148.  
  149. $init_cron = "crontab -l > {$this->cronFile} && [ -f {$this->cronFile} ] || > {$this->cronFile}";
  150.  
  151. $this->exec($init_cron);
  152.  
  153. }
  154.  
  155. return $this;
  156. }
  157.  
  158. // ------------------------------------------------------------------------
  159.  
  160. /**
  161. * This method, removeFile() is as easy as easy could be! We'll use our helper
  162. * method, crontabFileExists(), to check for the existence of the temporary cron
  163. * file and then execute the Linux command `rm` to delete it if it does. As usual,
  164. * we'll also return $this in order to maintain chainability.
  165. *
  166. * @return $this
  167. */
  168. public function removeFile()
  169. {
  170. if ($this->crontabFileExists()) {
  171. $this->exec("rm {$this->cronFile}");
  172.  
  173. }
  174.  
  175. return $this;
  176. }
  177.  
  178. // ------------------------------------------------------------------------
  179.  
  180. /**
  181. * This method will create new cron jobs by way of adding new jobs / lines to
  182. * the temporary cron file and then executing the crontab command on that file
  183. * which will install all of those jobs as a new cronTab. As such, appendCronjob()
  184. * will take one argument, $cronJobs, which will either be a string or an array of
  185. * strings representing the cron jobs to append.
  186. *
  187. * @param null $cronJobs
  188. *
  189. * @return $this
  190. */
  191. public function appendCronjob($cronJobs = null)
  192. {
  193. if (is_null($cronJobs)) {
  194. $this->errorMessage("Nothing to append! Please specify a cron job or an array of cron jobs.");
  195.  
  196. }
  197.  
  198. $appendCronfile = "echo '";
  199.  
  200. $appendCronfile .= is_array($cronJobs) ? implode("\n", $cronJobs): $cronJobs;
  201.  
  202. $appendCronfile .= "' >> {$this->cronFile}";
  203.  
  204. $installCron = "crontab {$this->cronFile}";
  205.  
  206. $this->writeToFile()->exec($appendCronfile, $installCron)->removeFile();
  207.  
  208. return $this;
  209. }
  210.  
  211. // ------------------------------------------------------------------------
  212.  
  213. /**
  214. * Now that we can create new cron jobs, it's only logical that we have the
  215. * ability to remove them as well! The removeCronjob() method will take one
  216. * argument which will be a (simple) regular expression. This regEx will be
  217. * used to find matching jobs within the cronTab and remove them accordingly.
  218. * As with the appendCronjob() method, the first thing we'll do is check to
  219. * see if the $cron_jobs argument is NULL and halt execution if it is. If not,
  220. * we'll call the createFile() method in order write the cron tab to a file.
  221. *
  222. * @param mixed $cronJobs
  223. *
  224. * @return CronJobController
  225. */
  226. public function removeCronjob($cronJobs = null)
  227. {
  228. if (is_null($cronJobs)) {
  229. $this->errorMessage("Nothing to remove! Please specify a cron job or an array of cron jobs.");
  230.  
  231. }
  232.  
  233. $this->writeToFile();
  234.  
  235. $cronArray = file($this->cronFile, FILE_IGNORE_NEW_LINES);
  236.  
  237. if (empty($cronArray)) {
  238. $this->errorMessage("Nothing to remove! The cronTab is already empty.");
  239.  
  240. }
  241.  
  242. $originalCount = count($cronArray);
  243.  
  244. if (is_array($cronJobs)) {
  245. foreach ($cronJobs as $cronRegex) {
  246. $cronArray = preg_grep($cronRegex, $cronArray, PREG_GREP_INVERT);
  247. }
  248.  
  249. } else {
  250. $cronArray = preg_grep($cronJobs, $cronArray, PREG_GREP_INVERT);
  251.  
  252. }
  253.  
  254. return ($originalCount === count($cronArray))
  255. ? $this->removeFile()
  256.  
  257. : $this->removeCrontab()
  258. ->appendCronjob($cronArray);
  259. }
  260.  
  261. // ------------------------------------------------------------------------
  262.  
  263. /**
  264. * Removing the entire cronTab is relatively simple to do. Essentially, we'll
  265. * just execute the crontab command with the -r flag set which removes the entire
  266. * cronTab for a given user. Since the crontab has been removed we might as well
  267. * remove the temporary cron file as well, should it exist. Then we'll return $this
  268. * in order to preserve chainability.
  269. *
  270. * @return $this
  271. */
  272. public function removeCrontab()
  273. {
  274. $this->exec("crontab -r")->removeFile();
  275.  
  276. return $this;
  277. }
  278.  
  279. // ------------------------------------------------------------------------
  280.  
  281. /**
  282. * With the brunt of our cron management class written, we'll now take a look
  283. * at the two small but useful methods we've used throughout our class,
  284. * crontabFileExists() and errorMessage().
  285. *
  286. * @see \CronJobController::crontabFileExists()
  287. * @see \CronJobController::errorMessage()
  288. *
  289. * @return bool
  290. */
  291. private function crontabFileExists()
  292. {
  293. return file_exists($this->cronFile);
  294. }
  295.  
  296. // ------------------------------------------------------------------------
  297.  
  298. /**
  299. * This method will take one argument, a string, representing the error message
  300. * we want to display. We'll then call PHP's die() method in order to halt
  301. * execution and display this message. The string it self, will be concatenated
  302. * into a <pre> element with some simple style applied to it.
  303. *
  304. * @param $error
  305. */
  306. private function errorMessage($error)
  307. {
  308. die("<pre style='color:#EE2711'>ERROR: {$error}</pre>");
  309. }
  310.  
  311. // ------------------------------------------------------------------------
  312. }
Add Comment
Please, Sign In to add comment