1: <?php
2:
3: App::uses('FileSystem', 'Base.Lib');
4: App::uses('SchedulingInstaller', 'Scheduling.Lib');
5:
6: class CronSchedulingInstaller implements SchedulingInstaller {
7:
8: public function install() {
9: $this->_setCrontabUserContents($this->_cronFileContent(false));
10: }
11:
12: public function uninstall() {
13: $this->_setCrontabUserContents($this->_cronFileContent(true));
14: }
15:
16: public function isInstalled() {
17: foreach (explode("\n", $this->_getCrontabUserContents()) as $line) {
18: if ($this->_isAppCronLine($line)) {
19: return true;
20: }
21: }
22: return false;
23: }
24:
25: private function _getCrontabUserContents() {
26: @exec('crontab -l', $lines, $result);
27: if ($result == 0) {
28: return implode("\n", $lines);
29: } else {
30: return '';
31: }
32: }
33:
34: private function _setCrontabUserContents($contents) {
35: $tmpFile = FileSystem::createTemporaryFile();
36: file_put_contents($tmpFile, $contents);
37: $command = 'crontab ' . escapeshellarg($tmpFile);
38: @exec($command, $lines, $result);
39: if ($result !== 0) {
40: throw new Exception("\"$command\" returned \"$result\"");
41: }
42: }
43:
44: 45: 46: 47:
48: private function _cronFileContent($uninstall) {
49: $lines = array();
50: foreach (explode("\n", $this->_getCrontabUserContents()) as $line) {
51: if (trim($line) != '' && !$this->_isAppCronLine($line)) {
52: $lines[] = $line;
53: }
54: }
55: if (!$uninstall) {
56: $lines[] = $this->_buildAppCronLine();
57: }
58: return implode("\n", $lines) . "\n";
59: }
60:
61: private function _isAppCronLine($line) {
62: return preg_match('/\#\s*APP_ID\:\s*' . preg_quote(APP_ID) . '\s*$/', $line);
63: }
64:
65: private function _buildAppCronLine() {
66: return '*/1 * * * * ' . $this->_quoteCommand(array(
67: APP . DS . 'Console' . DS . 'cake',
68: 'Scheduling.check_and_run',
69: )) . '# APP_ID: ' . APP_ID . "\n";
70: }
71:
72: 73: 74: 75: 76:
77: private function _quoteCommand($args) {
78: $b = '';
79: foreach ($args as $arg) {
80: $b .= escapeshellarg($arg) . ' ';
81: }
82: return $b;
83: }
84:
85: }
86: