xref: /plugin/siteexport/cron.php (revision 7d101cc131696cb3a0de345d8044a69fb2ef70e9)
1<?php
2if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../../');
3if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
4
5/**
6 * The Cron Class is just an initial wrapper which tries to create a blank cron.conf.php file
7 * It can also add/edit/delete Cron Jobs that are being configured at the GUI
8 *
9 * @author gamma
10 *
11 */
12class cron_plugin_siteexport {
13
14    private $configFile;
15    public $configuration;
16
17    /**
18     * Initial setup for this class
19     */
20    function __construct()
21    {
22        $this->configFile = DOKU_INC . 'conf/cron.config.php';
23        $this->readCronSettings();
24    }
25
26    /**
27     * Save a new entry, or overwrite an existing entry in the cron config
28     * @param $parameters parameters which define the cron job
29     * @param $canOverwrite information if an existing entry should be overwritten
30     */
31    public function saveCronDataWithParameters($parameters, $canOverwrite=false)
32    {
33        if ( !$canOverwrite && $this->hasCronJobForParameters($parameters) )
34        {
35            return "Cannot save. The Cron Job already exists - but no permission given to overwrite";
36        }
37
38        $this->configuration[$this->cronJobNameForParameters($parameters)] = $parameters;
39        if ( !$this->writeCronSettings() ) {
40            return "There was an error while saving the Cron configuration during a save action";
41        }
42    }
43
44    public function deleteCronDataWithParameters($parameters)
45    {
46        unset($this->configuration[$this->cronJobNameForParameters($parameters)]);
47        if ( !$this->writeCronSettings() ) {
48            return "There was an error while saving the Cron configuration during a deletion action";
49        }
50    }
51
52    /**
53     * Reads the Configuration if not loaded yet
54     */
55    public function readCronSettings()
56    {
57        if ( !$this->configFile )
58        {
59            return false;
60        }
61
62        $settings = array();
63        if ( file_exists($this->configFile) )
64        {
65            include($this->configFile);
66        }
67
68        $this->configuration = $settings;
69        return true;
70    }
71
72    /**
73     * Writes the Configuration if it is being set
74     */
75    public function writeCronSettings()
76    {
77        global $conf;
78
79        if ( !$this->configFile )
80        {
81            // Nothing has changed.
82            return true;
83        }
84
85        // backup current file (remove any existing backup)
86        if (@file_exists($this->configFile)) {
87            if (@file_exists($this->configFile.'.bak')) @unlink($this->configFile.'.bak');
88            if (!io_rename($this->configFile, $this->configFile.'.bak')) return false;
89        }
90
91        if (!$fh = @fopen($this->configFile, 'wb')) {
92            io_rename($this->configFile.'.bak', $this->configFile);     // problem opening, restore the backup
93            return false;
94        }
95
96        $out = $this->cronHeading();
97        $out .= $this->recurseSettingsToOut($this->configuration);
98        $out .= $this->cronFooter();
99
100        // Finally write it out.
101        @fwrite($fh, $out);
102        fclose($fh);
103        if($conf['fperm']) chmod($this->configFile, $conf['fperm']);
104        return true;
105    }
106
107    /**
108     * Header text for the cron config file
109     */
110    private function cronHeading()
111    {
112        $DOKU_URL = DOKU_URL;
113        return <<<OUTPUT
114<?php
115/*
116 * Siteexport Cron Job Configuration
117 * Auto-generated by siteexport
118 * Run for user: {$_SERVER['REMOTE_USER']}
119 */
120
121// Required to set the HTTP_HOST which is usually not set in CLI Environments
122\$_SERVER['HTTP_HOST'] = "{$_SERVER['HTTP_HOST']}";
123
124// This is not the nice way to inject another ROOT-URL, but we do not want to modify other stuff.
125if(!defined('DOKU_URL')) define('DOKU_URL', "{$DOKU_URL}");
126
127
128OUTPUT;
129    }
130
131    /**
132     * Footer Text for the cron config file
133     */
134    private function cronFooter()
135    {
136        return <<<OUTPUT
137
138// end of auto-generated content
139OUTPUT;
140    }
141
142    /**
143     * Checks if the settings file is writeable
144     */
145    public function canWriteSettings()
146    {
147        if ( !file_exists($this->configFile) && !$this->writeCronSettings() )
148        {
149            return false;
150        }
151
152        return is_writable($this->configFile);
153    }
154
155    /**
156     * Recursively walk through the settings and generate a nice looking string
157     * @param $settings Array of named settings
158     * @param $levelPrefix Prefix that will be build during recursion. It will contain a string for the named array depth
159     */
160    private function recurseSettingsToOut($settings, $levelPrefix = null)
161    {
162        if ( !is_array($settings) )
163        {
164            // If this is a value and the levelPrefix is not empty, print it out
165            if ( $levelPrefix == null || empty($settings) )
166            {
167                return '';
168            }
169
170            return '$settings' . $levelPrefix . ' = "' . trim($settings) . "\";\n";
171        }
172
173        $out = '';
174
175        // walk recursively through the content and giv it all back
176        foreach ($settings as $name => $value )
177        {
178            $out .= $this->recurseSettingsToOut($value, $levelPrefix . '["' . trim($name) . '"]');
179        }
180        return $out;
181    }
182
183    /**
184     * Checks if there is already a Cron Job for the given parameters
185     * @param $parameters
186     */
187    public function hasCronJobForParameters($parameters)
188    {
189        return array_key_exists($this->cronJobNameForParameters($parameters), $this->configuration);
190    }
191
192    /**
193     * returns a name for the parameters
194     * @param $parameters
195     */
196    public function cronJobNameForParameters($parameters)
197    {
198        return md5($parameters);
199    }
200}
201
202// ensure that the request comes from the cli
203if ( !$_SERVER['REMOTE_ADDR'] && 'cli' == php_sapi_name()) {
204    ini_set('memory_limit','512M');
205    error_reporting(E_ALL);
206
207    /**
208     * Cli Cron is responsible for doing the actual fetching of documentation
209     * @author gamma
210     *
211     */
212    class plugin_siteexport_cli_cron {
213
214        private $cronPlugin;
215        private $siteexportAjax;
216        public $error;
217
218        /**
219         * Instantiate and load plugin
220         */
221        public function plugin_siteexport_cli_cron()
222        {
223            // Needs to go first, to initialize the config which holds some special treatment
224            $this->cronPlugin = new cron_plugin_siteexport();
225
226            // Load later to have the config up and running.
227            // the config needs to adjust some variables of the server
228            require_once(DOKU_INC . 'inc/init.php');
229            require_once(DOKU_INC . 'inc/common.php');
230            require_once(DOKU_INC . 'inc/indexer.php');
231            require_once(DOKU_INC . 'inc/io.php');
232            require_once(DOKU_INC . 'inc/confutils.php');
233
234            if ( !$this->siteexportAjax =& plugin_load('action', 'siteexport_ajax' ) ) {
235                $this->error = "Faild! Ajax Plugin not loaded\n";
236            }
237        }
238
239        /**
240         * let the plugin run!
241         */
242        public function run() {
243            global $ID;
244            global $INFO;
245
246            $originalREquest = $_REQUEST;
247
248            foreach ( $this->cronPlugin->configuration as $name => $config )
249            {
250                // retrieve parameters
251                list($id,$parameters) = explode('?', $config, 2);
252
253                $function = new siteexport_functions(false);
254                $_REQUEST = $function->parseStringToRequestArray($parameters, true);
255                unset($function);
256
257                $ID = $_REQUEST['id'] = cleanID($id); // re-set the ID
258                // $ID = getID();
259
260                // Lets start over!
261                $this->siteexportAjax->__init_functions();
262                $this->siteexportAjax->functions->settings->isCLI = true;
263                $this->siteexportAjax->functions->settings->isAuthed = true;
264                $INFO['perm'] = AUTH_DELETE; // Fake authentication
265
266                // Fake security Token if none given
267                if ( empty( $_REQUEST['sectok'] ) ) {
268                    $_REQUEST['sectok'] = getSecurityToken();
269                }
270
271                $data = $this->siteexportAjax->__get_siteexport_list_and_init_tocs($ID);
272
273                // If there is nothing in there - ignore. This may mean we have a valid cache
274                if ( count($data) == 0 ) {
275                    continue;
276                }
277
278                foreach ( $data as $site ) {
279
280                    // We want to create a specific file! - have to reset it every time in here
281                    // $_REQUEST['pattern'] = $name;
282                    $status = $this->siteexportAjax->__siteexport_add_site($site['id']);
283                }
284
285                $this->siteexportAjax->functions->checkIfCacheFileExistsForFileWithPattern($this->siteexportAjax->functions->getCacheFileNameForPattern(), $name);
286
287                // Wat zum geier?
288                $this->siteexportAjax->cleanCacheFiles();
289            }
290        }
291    }
292
293    $cron = new plugin_siteexport_cli_cron();
294    if ( empty($cron->error) )
295    {
296        $cron->run();
297    } else
298    {
299        echo <<<OUTPUT
300************************************************************************
301* ERROR                                                                *
302************************************************************************
303
304        {$cron->error}
305************************************************************************
306
307
308OUTPUT;
309    }
310}
311
312?>