Alternc  latest
Alternc logiel libre pour l'h├ębergement
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

◆ _update_one()

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

◆ cron_callback()

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 253 of file m_cron.php.

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

253  {
254  global $db, $L_FQDN;
255  if (empty($url["id"])) {
256  return; // not normal...
257  }
258  $id = intval($url["id"]);
259 
260  if ($curl["http_code"] == 200) {
261  $ok = true;
262  } else {
263  $ok = false;
264  }
265  if (isset($url["email"]) && $url["email"] && $content) {
266  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")) {
267  echo "Error sending mail for cron #$id to address '" . $url["email"] . "'\n";
268  }
269  }
270  // now schedule it for next run:
271  $db->query("UPDATE cron SET next_execution=FROM_UNIXTIME( UNIX_TIMESTAMP(NOW()) + schedule * 60) WHERE id= ?", array($id));
272  }
$content
Definition: bro_editor.php:89
global $db
Definition: bootstrap.php:22
if(!isset($is_include)) if(! $key &&! $crt) $id
if(!isset($delete)) $ok
Definition: ssl_delete.php:41

◆ delete_one()

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

◆ execute_cron()

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  }
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:287
exit
Definition: adm_doadd.php:70

◆ hook_menu()

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  }

◆ hook_quota_get()

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

◆ lst_cron()

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

◆ rolling_curl()

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 287 of file m_cron.php.

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

Referenced by execute_cron().

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

◆ schedule()

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  }

◆ update()

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, and _update_one().

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  }
_update_one($url, $user, $password, $email, $schedule, $id=null)
update a crontab,
Definition: m_cron.php:120
if(!isset($delete)) $ok
Definition: ssl_delete.php:41

◆ valid_schedule()

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

◆ DEFAULT_CAFILE

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

Definition at line 29 of file m_cron.php.

Referenced by rolling_curl().

◆ MAX_SOCKETS

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: