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

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

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

Referenced by update().

◆ 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.

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:91
if(!isset($delete)) $ok
Definition: ssl_delete.php:41

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

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

108  {
109  global $db, $msg, $cuid;
110  $msg->log("cron", "delete_one");
111  return $db->query("DELETE FROM cron WHERE id= ? AND uid= ? LIMIT 1;", array(intval($id), $cuid));
112  }

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

Referenced by _update_one().

◆ execute_cron()

m_cron::execute_cron ( )

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

Definition at line 208 of file m_cron.php.

208  {
209  global $db,$msg;
210 
211  $msg->debug("cron", "execute_cron");
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  }
exit
Definition: adm_doadd.php:70
rolling_curl($urls, $callback, $custom_options=null)
Launch parallel (using MAX_SOCKETS sockets maximum) retrieval of URL using CURL.
Definition: m_cron.php:287

References $db, $msg, exit, and rolling_curl().

◆ 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  'link' => 'cron.php',
74  'pos' => 120,
75  );
76 
77  return $obj;
78  }

◆ hook_quota_get()

m_cron::hook_quota_get ( )

hook for quota computation

Definition at line 192 of file m_cron.php.

192  {
193  global $cuid, $db, $msg;
194  $msg->debug("cron", "alternc_get_quota");
195  $q = Array("name" => "cron", "description" => _("Scheduled tasks"), "used" => 0);
196  $db->query("select count(*) as cnt from cron where uid = ? ;", array($cuid));
197  if ($db->next_record()) {
198  $q['used'] = $db->f('cnt');
199  }
200  return $q;
201  }

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

◆ 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.

48  {
49  global $cuid, $db, $msg;
50  $msg->debug("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  }
$r
Definition: aws_add.php:75

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

◆ 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@host/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.

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  }
const DEFAULT_CAFILE
Definition: m_cron.php:29
const MAX_SOCKETS
Definition: m_cron.php:28
$i
if($error) $info

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

Referenced by execute_cron().

◆ schedule()

m_cron::schedule ( )

Definition at line 35 of file m_cron.php.

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  }

Referenced by valid_schedule().

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

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

References $ok, and _update_one().

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

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

References $r, and schedule().

Referenced by _update_one().

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: