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

 m_cron ()
 Constructor. More...
 
 schedule ()
 
 lst_cron ()
 List the crontab for the current user. More...
 
 hook_menu ()
 
 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 30 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 125 of file m_cron.php.

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

Referenced by update().

125  {
126  global $db, $err, $quota, $cuid;
127  $err->log("cron", "update_one");
128 
129  if (empty($url) && !is_null($id)) {
130  return $this->delete_one($id);
131  }
132 
133 
134  if (filter_var($url, FILTER_VALIDATE_URL) === false) {
135  $err->raise("cron", _("URL not valid"));
136  return false;
137  }
138  $url = urlencode($url);
139  $user = urlencode($user);
140  if (empty($user)) {
141  $password = '';
142  }
143  $password = urlencode($password);
144 
145  //@todo remove checkmail cf functions.php
146  if (!empty($email) && !checkmail($email) == 0) {
147  $err->raise("cron", _("Email address is not valid"));
148  return false;
149  }
150  $email = urlencode($email);
151  if (!$this->valid_schedule($schedule)) {
152  return false;
153  }
154 
155  if (is_null($id)) { // if a new insert, quotacheck
156  $q = $quota->getquota("cron");
157  if ($q["u"] >= $q["t"]) {
158  $err->raise("cron", _("You quota of cron entries is over. You cannot create more cron entries"));
159  return false;
160  }
161  } else { // if not a new insert, check the $cuid
162  $db->query("SELECT uid FROM cron WHERE id = ? ;", array($id));
163  if (!$db->next_record()) {
164  return "false";
165  } // return false if pb
166  if ($db->f('uid') != $cuid) {
167  $err->raise("cron", _("Identity problem"));
168  return false;
169  }
170  }
171  return $db->query("REPLACE INTO cron (id, uid, url, user, password, schedule, email) VALUES (?, ?, ?, ?, ?, ?, ?) ;" , array($id, $cuid, $url, $user, $password, $schedule, $email));
172  }
$user
Definition: bootstrap.php:84
global $db
Definition: bootstrap.php:22
$err
Definition: bootstrap.php:72
$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:236
if(!isset($is_include)) if(!$key &&!$crt) $id
valid_schedule($s)
validate a crontab schedule
Definition: m_cron.php:180
delete_one($id)
delete a crontab
Definition: m_cron.php:114
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 261 of file m_cron.php.

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

261  {
262  global $db, $L_FQDN;
263  if (empty($url["id"])) {
264  return; // not normal...
265  }
266  $id = intval($url["id"]);
267 
268  if ($curl["http_code"] == 200) {
269  $ok = true;
270  } else {
271  $ok = false;
272  }
273  if (isset($url["email"]) && $url["email"] && $content) {
274  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")) {
275  echo "Error sending mail for cron #$id to address '" . $url["email"] . "'\n";
276  }
277  }
278  // now schedule it for next run:
279  $db->query("UPDATE cron SET next_execution=FROM_UNIXTIME( UNIX_TIMESTAMP(NOW()) + schedule * 60) WHERE id= ?", array($id));
280  }
$content
Definition: bro_editor.php:94
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 114 of file m_cron.php.

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

Referenced by _update_one().

114  {
115  global $db, $err, $cuid;
116  $err->log("cron", "delete_one");
117  return $db->query("DELETE FROM cron WHERE id= ? AND uid= ? LIMIT 1;", array(intval($id), $cuid));
118  }
global $db
Definition: bootstrap.php:22
$err
Definition: bootstrap.php:72
$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 215 of file m_cron.php.

References $db, exit, and rolling_curl().

215  {
216  global $db;
217 
218  if (!isset($GLOBALS["DEBUG"])) {
219  $GLOBALS["DEBUG"] = false;
220  }
221  $db->query("SELECT id, url, email, schedule, user, password FROM cron WHERE next_execution <= NOW();");
222  $urllist = array();
223 
224  while ($db->next_record()) {
225  $db->Record["url"] = urldecode($db->Record["url"]);
226  $db->Record["user"] = urldecode($db->Record["user"]);
227  $db->Record["email"] = urldecode($db->Record["email"]);
228  $db->Record["password"] = urldecode($db->Record["password"]);
229 
230  // we support only http or https schemes:
231  if (substr($db->Record["url"], 0, 7) == "http://" || substr($db->Record["url"], 0, 8) == "https://") {
232  $u = array(
233  "url" => $db->Record["url"],
234  "id" => $db->Record["id"], "email" => $db->Record["email"],
235  );
236 
237  if ($db->Record["user"] && $db->Record["password"]) {
238  $u["login"] = $db->Record["user"];
239  $u["password"] = $db->Record["password"];
240  }
241  if ($GLOBALS["DEBUG"])
242  echo "Will run cron :\n" . print_r($u, true) . "\n";
243  $urllist[] = $u;
244  }
245 
246  if (empty($urllist)) { // nothing to do :
247  exit(0);
248  }
249 
250  // cron_callback($url, $content, $curlobj) will be called at the end of each http call.
251  $this->rolling_curl($urllist, array("m_cron", "cron_callback"));
252  }
253  }
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:296
exit
Definition: adm_doadd.php:71
m_cron::hook_menu ( )

Definition at line 75 of file m_cron.php.

75  {
76  $obj = array(
77  'title' => _("Scheduled tasks"),
78  'ico' => 'images/schedule.png',
79  'link' => 'cron.php',
80  'pos' => 90,
81  );
82 
83  return $obj;
84  }
m_cron::hook_quota_get ( )

hook for quota computation

Definition at line 198 of file m_cron.php.

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

198  {
199  global $cuid, $db, $err;
200  $err->log("cron", "alternc_get_quota");
201  $q = Array("name" => "cron", "description" => _("Scheduled tasks"), "used" => 0);
202  $db->query("select count(*) as cnt from cron where uid = ? ;", array($cuid));
203  if ($db->next_record()) {
204  $q['used'] = $db->f('cnt');
205  }
206  return $q;
207  }
global $db
Definition: bootstrap.php:22
$err
Definition: bootstrap.php:72
$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 56 of file m_cron.php.

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

56  {
57  global $cuid, $db, $err;
58  $err->log("cron", "lst_cron");
59  $db->query("SELECT * FROM cron WHERE uid = ? ORDER BY url;", array($cuid));
60  $r = Array();
61  while ($db->next_record()) {
62  $tmp = Array();
63  $tmp['id'] = $db->f('id');
64  $tmp['url'] = urldecode($db->f('url'));
65  $tmp['user'] = urldecode($db->f('user'));
66  $tmp['password'] = urldecode($db->f('password'));
67  $tmp['schedule'] = $db->f('schedule');
68  $tmp['email'] = urldecode($db->f('email'));
69  $tmp['next_execution'] = $db->f('next_execution');
70  $r[] = $tmp;
71  }
72  return $r;
73  }
global $db
Definition: bootstrap.php:22
$r
Definition: aws_add.php:77
$err
Definition: bootstrap.php:72
$cuid
Definition: bootstrap.php:43
m_cron::m_cron ( )

Constructor.

Definition at line 39 of file m_cron.php.

39  {
40 
41  }
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 296 of file m_cron.php.

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

Referenced by execute_cron().

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

Definition at line 43 of file m_cron.php.

Referenced by valid_schedule().

43  {
44  return Array(
45  Array('unit' => 1440, 'name' => _("Daily")),
46  Array('unit' => 60, 'name' => _("Hour")),
47  Array('unit' => 30, 'name' => _("Half Hour")),
48  );
49  }
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 92 of file m_cron.php.

References $ok, _update_one(), and null.

92  {
93  $ok = true;
94  foreach ($arr as $a) {
95  if (!isset($a['id'])) {
96  $a['id'] = null;
97  }
98  if (empty($a['url']) && is_null($a['id'])) {
99  continue;
100  }
101  if (!$this->_update_one($a['url'], $a['user'], $a['password'], $a['email'], $a['schedule'], $a['id'])) {
102  $ok = false;
103  }
104  }
105  return $ok;
106  }
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:125
m_cron::valid_schedule (   $s)

validate a crontab schedule

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

Definition at line 180 of file m_cron.php.

References $r, and schedule().

Referenced by _update_one().

180  {
181  $s2 = intval($s);
182  if ($s2 != $s) {
183  return false;
184  }
185  $r = false;
186  foreach ($this->schedule() as $cs) {
187  if ($cs['unit'] == $s) {
188  return true;
189  }
190  }
191  return $r;
192  }
$r
Definition: aws_add.php:77
schedule()
Definition: m_cron.php:43

Member Data Documentation

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

Definition at line 33 of file m_cron.php.

Referenced by rolling_curl().

const m_cron::MAX_SOCKETS = 8

Definition at line 32 of file m_cron.php.

Referenced by rolling_curl().


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