Alternc  latest
Alternc logiel libre pour l'h├ębergement
 All Classes Namespaces Files Functions Variables Pages
m_cron Class Reference

This class manage web-cron tasks. More...

Public Member Functions

 schedule ()
 
 lst_cron ()
 List the crontab for the current user. More...
 
 hook_menu ()
 Hook called by menu class to add menu to the left panel. More...
 
 update ($arr)
 update the crontab More...
 
 delete_one ($id)
 delete a crontab More...
 
 valid_schedule ($s)
 validate a crontab schedule More...
 
 hook_quota_get ()
 hook for quota computation More...
 
 execute_cron ()
 Execute the required crontab of AlternC users this function EXIT at the end. More...
 
 cron_callback ($url, $content, $curl)
 Callback function called by rolling_curl when a cron resulr has been received schedule it for next run and send the mail if needed. More...
 
 rolling_curl ($urls, $callback, $custom_options=null)
 Launch parallel (using MAX_SOCKETS sockets maximum) retrieval of URL using CURL. More...
 

Public Attributes

const MAX_SOCKETS = 8
 
const DEFAULT_CAFILE = "/etc/ssl/certs/ca-certificates.crt"
 

Private Member Functions

 _update_one ($url, $user, $password, $email, $schedule, $id=null)
 update a crontab, More...
 

Detailed Description

This class manage web-cron tasks.

Definition at line 26 of file m_cron.php.

Member Function Documentation

m_cron::_update_one (   $url,
  $user,
  $password,
  $email,
  $schedule,
  $id = null 
)
private

update a crontab,

Returns
boolean TRUE if the crontab has been edited

Definition at line 120 of file m_cron.php.

References $cuid, $db, $id, $msg, $password, $q, $user, checkmail(), delete_one(), and valid_schedule().

Referenced by update().

120  {
121  global $db, $msg, $quota, $cuid;
122  $msg->log("cron", "update_one");
123 
124  if (empty($url) && !is_null($id)) {
125  return $this->delete_one($id);
126  }
127 
128 
129  if (filter_var($url, FILTER_VALIDATE_URL) === false) {
130  $msg->raise("ERROR", "cron", _("URL not valid"));
131  return false;
132  }
133  $url = urlencode($url);
134  $user = urlencode($user);
135  if (empty($user)) {
136  $password = '';
137  }
138  $password = urlencode($password);
139 
140  //@todo remove checkmail cf functions.php
141  if (!empty($email) && !checkmail($email) == 0) {
142  $msg->raise("ERROR", "cron", _("Email address is not valid"));
143  return false;
144  }
145  $email = urlencode($email);
146  if (!$this->valid_schedule($schedule)) {
147  return false;
148  }
149 
150  if (is_null($id)) { // if a new insert, quotacheck
151  $q = $quota->getquota("cron");
152  if ($q["u"] >= $q["t"]) {
153  $msg->raise("ERROR", "cron", _("You quota of cron entries is over. You cannot create more cron entries"));
154  return false;
155  }
156  } else { // if not a new insert, check the $cuid
157  $db->query("SELECT uid FROM cron WHERE id = ? ;", array($id));
158  if (!$db->next_record()) {
159  return "false";
160  } // return false if pb
161  if ($db->f('uid') != $cuid) {
162  $msg->raise("ERROR", "cron", _("Identity problem"));
163  return false;
164  }
165  }
166  return $db->query("REPLACE INTO cron (id, uid, url, user, password, schedule, email) VALUES (?, ?, ?, ?, ?, ?, ?) ;" , array($id, $cuid, $url, $user, $password, $schedule, $email));
167  }
$user
Definition: bootstrap.php:84
global $db
Definition: bootstrap.php:22
$msg
Definition: config.php:155
$cuid
Definition: bootstrap.php:43
$password
Definition: bootstrap.php:85
checkmail($mail)
Check an email address, use filter_var with emails, which works great ;)
Definition: functions.php:244
if(!isset($is_include)) if(!$key &&!$crt) $id
valid_schedule($s)
validate a crontab schedule
Definition: m_cron.php:175
delete_one($id)
delete a crontab
Definition: m_cron.php:109
m_cron::cron_callback (   $url,
  $content,
  $curl 
)

Callback function called by rolling_curl when a cron resulr has been received schedule it for next run and send the mail if needed.

Definition at line 254 of file m_cron.php.

References $content, $db, $id, and $ok.

254  {
255  global $db, $L_FQDN;
256  if (empty($url["id"])) {
257  return; // not normal...
258  }
259  $id = intval($url["id"]);
260 
261  if ($curl["http_code"] == 200) {
262  $ok = true;
263  } else {
264  $ok = false;
265  }
266  if (isset($url["email"]) && $url["email"] && $content) {
267  if (!mail($url["email"], "AlternC Cron #$id - Report " . date("r"), "Please find below the stdout content produced by your cron task.\n------------------------------------------------------------\n\n" . $content, "From: postmaster@$L_FQDN")) {
268  echo "Error sending mail for cron #$id to address '" . $url["email"] . "'\n";
269  }
270  }
271  // now schedule it for next run:
272  $db->query("UPDATE cron SET next_execution=FROM_UNIXTIME( UNIX_TIMESTAMP(NOW()) + schedule * 60) WHERE id= ?", array($id));
273  }
$content
Definition: bro_editor.php:89
global $db
Definition: bootstrap.php:22
if(!isset($delete)) $ok
Definition: ssl_delete.php:41
if(!isset($is_include)) if(!$key &&!$crt) $id
m_cron::delete_one (   $id)

delete a crontab

Parameters
$idthe id of the crontab to delete
Returns
boolean TRUE if the crontab has been deleted

Definition at line 109 of file m_cron.php.

References $cuid, $db, $id, and $msg.

Referenced by _update_one().

109  {
110  global $db, $msg, $cuid;
111  $msg->log("cron", "delete_one");
112  return $db->query("DELETE FROM cron WHERE id= ? AND uid= ? LIMIT 1;", array(intval($id), $cuid));
113  }
global $db
Definition: bootstrap.php:22
$msg
Definition: config.php:155
$cuid
Definition: bootstrap.php:43
if(!isset($is_include)) if(!$key &&!$crt) $id
m_cron::execute_cron ( )

Execute the required crontab of AlternC users this function EXIT at the end.

Definition at line 209 of file m_cron.php.

References $db, exit, and rolling_curl().

209  {
210  global $db;
211 
212  if (!isset($GLOBALS["DEBUG"])) {
213  $GLOBALS["DEBUG"] = false;
214  }
215  $db->query("SELECT id, url, email, schedule, user, password FROM cron WHERE next_execution <= NOW();");
216  $urllist = array();
217 
218  while ($db->next_record()) {
219  $db->Record["url"] = urldecode($db->Record["url"]);
220  $db->Record["user"] = urldecode($db->Record["user"]);
221  $db->Record["email"] = urldecode($db->Record["email"]);
222  $db->Record["password"] = urldecode($db->Record["password"]);
223 
224  // we support only http or https schemes:
225  if (substr($db->Record["url"], 0, 7) == "http://" || substr($db->Record["url"], 0, 8) == "https://") {
226  $u = array(
227  "url" => $db->Record["url"],
228  "id" => $db->Record["id"], "email" => $db->Record["email"],
229  );
230 
231  if ($db->Record["user"] && $db->Record["password"]) {
232  $u["login"] = $db->Record["user"];
233  $u["password"] = $db->Record["password"];
234  }
235  if ($GLOBALS["DEBUG"])
236  echo "Will run cron :\n" . print_r($u, true) . "\n";
237  $urllist[] = $u;
238  }
239 
240  if (empty($urllist)) { // nothing to do :
241  exit(0);
242  }
243 
244  // cron_callback($url, $content, $curlobj) will be called at the end of each http call.
245  $this->rolling_curl($urllist, array("m_cron", "cron_callback"));
246  }
247  }
global $db
Definition: bootstrap.php:22
rolling_curl($urls, $callback, $custom_options=null)
Launch parallel (using MAX_SOCKETS sockets maximum) retrieval of URL using CURL.
Definition: m_cron.php:288
exit
Definition: adm_doadd.php:70
m_cron::hook_menu ( )

Hook called by menu class to add menu to the left panel.

Definition at line 70 of file m_cron.php.

70  {
71  $obj = array(
72  'title' => _("Scheduled tasks"),
73  'ico' => 'images/schedule.png',
74  'link' => 'cron.php',
75  'pos' => 120,
76  );
77 
78  return $obj;
79  }
m_cron::hook_quota_get ( )

hook for quota computation

Definition at line 193 of file m_cron.php.

References $cuid, $db, $msg, and $q.

193  {
194  global $cuid, $db, $msg;
195  $msg->log("cron", "alternc_get_quota");
196  $q = Array("name" => "cron", "description" => _("Scheduled tasks"), "used" => 0);
197  $db->query("select count(*) as cnt from cron where uid = ? ;", array($cuid));
198  if ($db->next_record()) {
199  $q['used'] = $db->f('cnt');
200  }
201  return $q;
202  }
global $db
Definition: bootstrap.php:22
$msg
Definition: config.php:155
$cuid
Definition: bootstrap.php:43
m_cron::lst_cron ( )

List the crontab for the current user.

Returns
array an hash for each crontab.

Definition at line 48 of file m_cron.php.

References $cuid, $db, $msg, and $r.

48  {
49  global $cuid, $db, $msg;
50  $msg->log("cron", "lst_cron");
51  $db->query("SELECT * FROM cron WHERE uid = ? ORDER BY url;", array($cuid));
52  $r = Array();
53  while ($db->next_record()) {
54  $tmp = Array();
55  $tmp['id'] = $db->f('id');
56  $tmp['url'] = urldecode($db->f('url'));
57  $tmp['user'] = urldecode($db->f('user'));
58  $tmp['password'] = urldecode($db->f('password'));
59  $tmp['schedule'] = $db->f('schedule');
60  $tmp['email'] = urldecode($db->f('email'));
61  $tmp['next_execution'] = $db->f('next_execution');
62  $r[] = $tmp;
63  }
64  return $r;
65  }
global $db
Definition: bootstrap.php:22
$r
Definition: aws_add.php:75
$msg
Definition: config.php:155
$cuid
Definition: bootstrap.php:43
m_cron::rolling_curl (   $urls,
  $callback,
  $custom_options = null 
)

Launch parallel (using MAX_SOCKETS sockets maximum) retrieval of URL using CURL.

Parameters
$urlsarray of associative array, each having the following keys : url = url to get (of the form http[s]://login:password/path/file?querystring ) login & password = if set, tell the login and password to use as simple HTTP AUTH.
  • any other key will be sent as it is to the callback function
$callbackfunction called for each request when completing. First argument is the $url object, second is the content (output) third is the info structure from curl for the returned page. 200 for OK, 403 for AUTH FAILED, 0 for timeout, dump it to know it ;) this function should return as soon as possible to allow other curl calls to complete properly.
$cursom_optionsarray of custom CURL options for all transfers

Definition at line 288 of file m_cron.php.

References $i, $info, DEFAULT_CAFILE, and MAX_SOCKETS.

Referenced by execute_cron().

288  {
289  // make sure the rolling window isn't greater than the # of urls
290  if (!isset($GLOBALS["DEBUG"]))
291  $GLOBALS["DEBUG"] = false;
292  $rolling_window = m_cron::MAX_SOCKETS;
293  $rolling_window = (count($urls) < $rolling_window) ? count($urls) : $rolling_window;
294 
295  $master = curl_multi_init();
296 
297  // add additional curl options here
298  $std_options = array(CURLOPT_RETURNTRANSFER => true,
299  CURLOPT_FOLLOWLOCATION => false,
300  CURLOPT_CONNECTTIMEOUT => 5,
301  CURLOPT_TIMEOUT => 240, // 4 minutes timeout for a page
302  CURLOPT_USERAGENT => "AlternC (Cron Daemon)",
303  CURLOPT_MAXREDIRS => 0);
304 
305  if ($GLOBALS["DEBUG"]) {
306  $std_options[CURLOPT_VERBOSE] = true;
307  }
308  $options = ($custom_options) ? ($std_options + $custom_options) : $std_options;
309 
310  // start the first batch of requests
311  for ($i = 0; $i < $rolling_window; $i++) {
312  $ch = curl_init();
313  $options[CURLOPT_URL] = $urls[$i]["url"];
314  if ($GLOBALS["DEBUG"]) {
315  echo "URL: " . $urls[$i]["url"] . "\n";
316  }
317  curl_setopt_array($ch, $options);
318  // Handle custom cafile for some https url
319  if (strtolower(substr($options[CURLOPT_URL], 0, 5)) == "https") {
320  curl_setopt($ch, CURLOPT_CAINFO, m_cron::DEFAULT_CAFILE);
321  if ($GLOBALS["DEBUG"]) {
322  echo "cainfo set to DEFAULT\n";
323  }
324  }
325  if (isset($urls[$i]["login"]) && isset($urls[$i]["password"])) { // set basic http authentication
326  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
327  curl_setopt($ch, CURLOPT_USERPWD, $urls[$i]["login"] . ":" . $urls[$i]["password"]);
328  if ($GLOBALS["DEBUG"]) {
329  echo "set basic auth\n";
330  }
331  }
332  curl_multi_add_handle($master, $ch);
333  }
334 
335  do {
336  while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
337  if ($execrun != CURLM_OK) {
338  break;
339  }
340  // a request was just completed -- find out which one
341  while ($done = curl_multi_info_read($master)) {
342  $info = curl_getinfo($done['handle']);
343  // TODO : since ssl_verify_result is buggy, if we have [header_size] => 0 && [request_size] => 0 && [http_code] => 0, AND https, we can pretend the SSL certificate is buggy.
344  if ($GLOBALS["DEBUG"]) {
345  echo "Info for " . $done['handle'] . " \n";
346  print_r($info);
347  }
348  if ($info['http_code'] == 200) {
349  $output = curl_multi_getcontent($done['handle']);
350  } else {
351  // request failed. add error handling.
352  $output = "";
353  }
354  // request terminated. process output using the callback function.
355  // Pass the url array to the callback, so we need to search it
356  foreach ($urls as $url) {
357  if ($url["url"] == $info["url"]) {
358  call_user_func($callback, $url, $output, $info);
359  break;
360  }
361  }
362 
363  // If there is more: start a new request
364  // (it's important to do this before removing the old one)
365  if ($i < count($urls)) {
366  $ch = curl_init();
367  $options[CURLOPT_URL] = $urls[$i++]; // increment i
368  curl_setopt_array($ch, $options);
369  if (strtolower(substr($options[CURLOPT_URL], 0, 5)) == "https") {
370  curl_setopt($ch, CURLOPT_CAINFO, m_cron::DEFAULT_CAFILE);
371  if ($GLOBALS["DEBUG"]) {
372  echo "cainfo set to DEFAULT\n";
373  }
374  }
375  if (isset($urls[$i]["login"]) && isset($urls[$i]["password"])) { // set basic http authentication
376  curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
377  curl_setopt($ch, CURLOPT_USERPWD, urlencode($urls[$i]["login"]) . ":" . urlencode($urls[$i]["password"]));
378  if ($GLOBALS["DEBUG"]) {
379  echo "set basic auth\n";
380  }
381  }
382  curl_multi_add_handle($master, $ch);
383  }
384  // remove the curl handle that just completed
385  curl_multi_remove_handle($master, $done['handle']);
386  }
387  } while ($running);
388 
389  curl_multi_close($master);
390  return true;
391  }
$i
const MAX_SOCKETS
Definition: m_cron.php:28
const DEFAULT_CAFILE
Definition: m_cron.php:29
m_cron::schedule ( )

Definition at line 35 of file m_cron.php.

Referenced by valid_schedule().

35  {
36  return Array(
37  Array('unit' => 1440, 'name' => _("Daily")),
38  Array('unit' => 60, 'name' => _("Hour")),
39  Array('unit' => 30, 'name' => _("Half Hour")),
40  );
41  }
m_cron::update (   $arr)

update the crontab

Parameters
$arrarray the crontab information, including its ID
Returns
boolean TRUE if the crontab has been edited

Definition at line 87 of file m_cron.php.

References $ok, _update_one(), and null.

87  {
88  $ok = true;
89  foreach ($arr as $a) {
90  if (!isset($a['id'])) {
91  $a['id'] = null;
92  }
93  if (empty($a['url']) && is_null($a['id'])) {
94  continue;
95  }
96  if (!$this->_update_one($a['url'], $a['user'], $a['password'], $a['email'], $a['schedule'], $a['id'])) {
97  $ok = false;
98  }
99  }
100  return $ok;
101  }
PR null
Definition: lang-css.js:1
if(!isset($delete)) $ok
Definition: ssl_delete.php:41
_update_one($url, $user, $password, $email, $schedule, $id=null)
update a crontab,
Definition: m_cron.php:120
m_cron::valid_schedule (   $s)

validate a crontab schedule

Parameters
$sarray schedule paramters
Returns
boolean TRUE if the schedule is valid

Definition at line 175 of file m_cron.php.

References $r, and schedule().

Referenced by _update_one().

175  {
176  $s2 = intval($s);
177  if ($s2 != $s) {
178  return false;
179  }
180  $r = false;
181  foreach ($this->schedule() as $cs) {
182  if ($cs['unit'] == $s) {
183  return true;
184  }
185  }
186  return $r;
187  }
$r
Definition: aws_add.php:75
schedule()
Definition: m_cron.php:35

Member Data Documentation

const m_cron::DEFAULT_CAFILE = "/etc/ssl/certs/ca-certificates.crt"

Definition at line 29 of file m_cron.php.

Referenced by rolling_curl().

const m_cron::MAX_SOCKETS = 8

Definition at line 28 of file m_cron.php.

Referenced by rolling_curl().


The documentation for this class was generated from the following file: