tengo un problema con un trabajo cron.
Resulta que tengo un script que funciona como uptobox, sin embargo el cron está configurado para que cada determinado tiempo haga unas tareas, borrar archivos y cosas así, pero cuando se ejecuta el cron tengo la siguiente salida. Ya revise y los datos de la base de datos con correctos, el script en sí mismo (el sitio web) funciona sin problemas, pero al ejecutarse el cron me dice que los datos no pudieron acceder. Solo existe un archivo de configuración con los datos de conexión a la base, y el sitio web se conecta y trabaja pero el cron no.
No entiendo mucho de PHP y de MySQL pero espero me puedan ayudar.
Failed connecting to the database with the supplied connection details. Please check the details are correct and your MySQL user has permissions to access this database.
Failed connecting to the database with the supplied connection details. Please check the details are correct and your MySQL user has permissions to access this database.
PHP Fatal error: Uncaught Error: Call to a member function prepare() on bool in /home/mrva/web/misitio.xyz/public_html/app/core/Database.class.php:121
Stack trace:
#0 /home/mrva/web/misitio.xyz/public_html/app/core/Database.class.php(319): App\Core\Database->query()
#1 /home/mrva/web/misitio.xyz/public_html/app/core/Database.class.php(242): App\Core\Database->resulter()
#2 /home/mrva/web/misitio.xyz/public_html/app/core/Framework.class.php(183): App\Core\Database->getRows()
#3 /home/mrva/web/misitio.xyz/public_html/app/core/Framework.class.php(50): App\Core\Framework::initConfigIntoMemory()
#4 /home/mrva/web/misitio.xyz/public_html/app/core/Framework.class.php(24): App\Core\Framework::init()
#5 /home/mrva/web/misitio.xyz/public_html/app/tasks/process_file_queue.cron.php(29): App\Core\Framework::runLight()
#6 {main}
thrown in /home/mrva/web/misitio.xyz/public_html/app/core/Database.class.php on line 121
Les adjunto los archivos que interactuan y llevan a este error
Framework.class.php
<?php
namespace App\Core;
use App\Core\Database;
use App\Helpers\BannedIpHelper;
use App\Helpers\CoreHelper;
use App\Helpers\PluginHelper;
use App\Helpers\LogHelper;
use App\Helpers\RouteHelper;
use App\Helpers\SessionHelper;
class Framework
{
const VERSION_NUMBER = '5.2.0';
public static function run()
{
self::init();
self::autoload();
LogHelper::initErrorHandler();
self::registerSession();
self::postInit();
self::dispatch();
}
public static function runLight()
{
self::init();
self::autoload();
}
private static function init()
{
define('DS', DIRECTORY_SEPARATOR);
define('DOC_ROOT', realpath(dirname(__FILE__) . '/../../'));
define('APP_ROOT', DOC_ROOT . '/app');
define('CORE_FRAMEWORK_ROOT', APP_ROOT . '/core');
define('CORE_FRAMEWORK_HELPERS_ROOT', APP_ROOT . '/helpers');
define('CORE_FRAMEWORK_LIBRARIES_ROOT', APP_ROOT . '/libraries');
define('CORE_APPLICATION_CONTROLLERS_ROOT', APP_ROOT . '/controllers');
define('CORE_APPLICATION_TEMPLATES_PATH', APP_ROOT . '/views');
define('CORE_FRAMEWORK_SERVICES_ROOT', APP_ROOT . '/services');
define('LOCAL_SITE_CONFIG_BASE_LOG_PATH', DOC_ROOT . '/logs/');
require DOC_ROOT . '/_config.inc.php';
if (!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
self::iniSets();
define('WEB_ROOT', _CONFIG_SITE_PROTOCOL . '://' . _CONFIG_SITE_FULL_URL);
define('CORE_WEB_ROOT', _CONFIG_SITE_PROTOCOL . '://' . _CONFIG_CORE_SITE_FULL_URL);
include_once CORE_FRAMEWORK_ROOT . '/Database.class.php';
include_once CORE_FRAMEWORK_ROOT . '/BaseController.class.php';
include_once CORE_FRAMEWORK_ROOT . '/Auth.class.php';
self::initConfigIntoMemory();
define('PLUGIN_DIRECTORY_NAME', 'plugins');
define('PLUGIN_DIRECTORY_ROOT', DOC_ROOT . '/' . PLUGIN_DIRECTORY_NAME . '/');
define('PLUGIN_WEB_ROOT', WEB_ROOT . '/' . PLUGIN_DIRECTORY_NAME);
define('CORE_APPLICATION_WEB_ROOT', WEB_ROOT . '');
define('DOWNLOAD_TRACKER_UPDATE_FREQUENCY', 15);
define('DOWNLOAD_TRACKER_PURGE_PERIOD', 7);
define('ADMIN_FOLDER_NAME', 'admin');
define('ADMIN_WEB_ROOT', WEB_ROOT . '/' . ADMIN_FOLDER_NAME);
define('ACCOUNT_WEB_ROOT', WEB_ROOT . '/account');
define('CACHE_DIRECTORY_NAME', 'cache');
define('CACHE_DIRECTORY_ROOT', DOC_ROOT . '/' . CACHE_DIRECTORY_NAME);
define('CACHE_WEB_ROOT', WEB_ROOT . '/' . CACHE_DIRECTORY_NAME);
define('SITE_THEME_DIRECTORY_NAME', 'themes');
define('SITE_THEME_DIRECTORY_ROOT', DOC_ROOT . '/' . SITE_THEME_DIRECTORY_NAME . '/');
define('SITE_THEME_WEB_ROOT', WEB_ROOT . '/' . SITE_THEME_DIRECTORY_NAME . '/');
define('CORE_ASSETS_WEB_ROOT', CORE_APPLICATION_WEB_ROOT . '/app/assets');
define('CORE_ASSETS_ADMIN_WEB_ROOT', CORE_ASSETS_WEB_ROOT . '/admin');
define('CORE_ASSETS_ADMIN_DIRECTORY_ROOT', APP_ROOT . '/assets/admin');
}
private static function postInit()
{
CoreHelper::checkMaintenanceMode(_INT_PAGE_URL);
$db = Database::getDatabase();
$currentLanguage = isset($_SESSION['_t']) ? $_SESSION['_t'] : SITE_CONFIG_SITE_LANGUAGE;
$languageImagePath = '';
$languageDirection = 'LTR';
$languageDetails = $db->getRow("SELECT id, flag, direction " . "FROM language " . "WHERE isActive = 1 " . "AND languageName = :languageName " . "LIMIT 1", array(
'languageName' => $currentLanguage,
));
if ($languageDetails)
{
$languageDirection = $languageDetails['direction'];
if (SITE_CONFIG_LANGUAGE_SEPARATE_LANGUAGE_IMAGES == 'yes')
{
$languageImagePath = $languageDetails['flag'] . '/';
}
define('SITE_CURRENT_LANGUAGE_ID', (int)$languageDetails['id']);
$_SESSION['_tFlag'] = $languageDetails['flag'];
}
define('SITE_LANGUAGE_DIRECTION', $languageDirection);
$siteTheme = SITE_CONFIG_SITE_THEME;
if ((isset($_SESSION['_current_theme'])) && (strlen($_SESSION['_current_theme'])))
{
$siteTheme = $_SESSION['_current_theme'];
}
define('SITE_CURRENT_THEME_DIRECTORY_ROOT', SITE_THEME_DIRECTORY_ROOT . $siteTheme);
define('SITE_IMAGE_DIRECTORY_ROOT', SITE_CURRENT_THEME_DIRECTORY_ROOT . '/assets/' . $languageImagePath . 'images');
define('SITE_CSS_DIRECTORY_ROOT', SITE_CURRENT_THEME_DIRECTORY_ROOT . '/assets/' . $languageImagePath . 'styles');
define('SITE_JS_DIRECTORY_ROOT', SITE_CURRENT_THEME_DIRECTORY_ROOT . '/assets/' . $languageImagePath . 'js');
define('SITE_TEMPLATES_PATH', SITE_CURRENT_THEME_DIRECTORY_ROOT . '/views');
define('SITE_THEME_PATH', SITE_THEME_WEB_ROOT . $siteTheme);
define('SITE_IMAGE_PATH', SITE_THEME_PATH . '/assets/' . $languageImagePath . 'images');
define('SITE_CSS_PATH', SITE_THEME_PATH . '/assets/' . $languageImagePath . 'styles');
define('SITE_JS_PATH', SITE_THEME_PATH . '/assets/' . $languageImagePath . 'js');
$bannedIP = BannedIpHelper::getBannedType();
if (strtolower($bannedIP) === "whole site")
{
header('HTTP/1.1 404 Not Found');
die();
}
CoreHelper::setupOldPaymentConstants();
if (_CONFIG_DEMO_MODE == true)
{
if (isset($_REQUEST['_p']))
{
$_SESSION['_plugins'] = false;
if ((int)$_REQUEST['_p'] == 1)
{
$_SESSION['_plugins'] = true;
}
PluginHelper::loadPluginConfigurationFiles(true);
}
if (!isset($_SESSION['_plugins']))
{
$_SESSION['_plugins'] = false;
PluginHelper::loadPluginConfigurationFiles(true);
}
}
PluginHelper::loadPluginConfigurationFiles();
PluginHelper::callHook('postFrameworkInit');
}
private static function iniSets()
{
@ini_set('memory_limit', '512M');
}
private static function registerSession()
{
if (SITE_CONFIG_USER_SESSION_TYPE === 'Database Sessions')
{
SessionHelper::register();
}
session_name('filehosting');
session_set_cookie_params((int)SITE_CONFIG_SESSION_EXPIRY);
session_start();
}
private static function autoload()
{
spl_autoload_register(array(
__CLASS__,
'load'
));
require_once (APP_ROOT . '/libraries/vendor/autoload.php');
}
private static function load($className)
{
if (!strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
$className = basename($className);
}
$className = str_replace('\\', DS, $className);
$filename = basename($className) . '.class.php';
$className = strtolower(dirname($className)) . DS . $filename;
if (file_exists(DOC_ROOT . DS . $className))
{
require_once (DOC_ROOT . DS . $className);
return;
}
else
{
$error = 'Error: Could not auto load class: ' . $className . '<br/><br/>Ensure you\'ve set a "use" statement at the top of your code.<br/><br/>';
$e = new \Exception();
$error .= nl2br($e->getTraceAsString());
}
}
private static function dispatch()
{
RouteHelper::processRoutes();
}
private static function initConfigIntoMemory()
{
$db = Database::getDatabase();
$rows = $db->getRows('SELECT config_key, config_value ' . 'FROM site_config ' . 'ORDER BY config_group, config_key');
if (COUNT($rows))
{
foreach ($rows AS $row)
{
$constantName = 'SITE_CONFIG_' . strtoupper($row['config_key']);
if (!defined($constantName))
{
define($constantName, $row['config_value']);
}
}
}
}
}
Database.class.php
<?php
namespace App\Core;
use \PDO;
class Database
{
// singleton object. Leave $me alone.
private static $me;
public static $queries = array();
public $db = false;
public $host;
public $name;
public $username;
public $password;
public $dieOnError;
public $result = null;
public $redirect = false;
private $reconnectCount = 0;
// Singleton constructor
private function __construct($connect = false) {
$this->host = _CONFIG_DB_HOST;
$this->name = _CONFIG_DB_NAME;
$this->username = _CONFIG_DB_USER;
$this->password = _CONFIG_DB_PASS;
$this->dieOnError = _CONFIG_DEBUG;
if ($connect === true) {
$this->connect();
}
}
// Get Singleton object
public static function getDatabase($connect = true, $forceReconnect = false) {
if (is_null(self::$me) || $forceReconnect === true) {
self::$me = new Database($connect);
}
return self::$me;
}
// Do we have a valid database connection?
public function isConnected() {
return is_object($this->db);
}
// Do we have a valid database connection and have we selected a database?
public function databaseSelected() {
if (!$this->isConnected()) {
return false;
}
$result = $this->db->query("SHOW TABLES");
return is_object($result);
}
public function connect() {
// check if we already have a connection
if ($this->db !== false && $this->isConnected()) {
return true;
}
// check for the MySQL PDO driver
if ($this->havePDODriver() == false) {
$this->notify('PDO driver unavailable. Please contact your host to request '
. 'the MySQL PDO driver to be enabled within PHP.');
}
try {
$this->db = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->name . ";charset=utf8", $this->username, $this->password);
// catch errors if debug is enabled
if (_CONFIG_DEBUG === true) {
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
catch (\Exception $e) {
$this->notify('Failed connecting to the database with the supplied connection '
. 'details. Please check the details are correct and your MySQL user '
. 'has permissions to access this database.');
}
if ($this->isConnected()) {
// disable strict mode in MySQL
$this->db->exec("SET sql_mode = ''");
// set utf8
$this->db->exec("SET NAMES utf8");
}
return $this->isConnected();
}
public function reconnect() {
$this->db = false;
$this->reconnectCount++;
return $this->connect();
}
public function close() {
$this->result = null;
self::closeDB();
}
public static function closeDB() {
if (!is_null(self::$me)) {
self::$me->db = null;
self::$me = null;
}
}
public function query($sQL, $args = null) {
if (!$this->isConnected()) {
$this->connect();
}
// allow for prepared arguments. Example:
$sth = $this->db->prepare($sQL);
$debugSql = $sQL;
$params = array();
if (is_array($args)) {
foreach ($args AS $name => $val) {
$params[':' . $name] = $val;
$replacement = "'" . $val . "'";
if (is_int($val)) {
$replacement = $val;
}
elseif ($val === null) {
$replacement = 'null';
}
$debugSql = preg_replace('/:\b' . $name . '\b/u', $replacement, $debugSql);
}
}
$start = microtime();
$startEx = explode(' ', $start);
$start = $startEx[1] + $startEx[0];
// track query
$nextIndex = $this->numQueries();
self::$queries[$nextIndex] = array(
'sql' => $debugSql,
'start' => $start,
);
try {
$sth->execute($params);
}
catch (\PDOException $e) {
if ($e->getCode() != 'HY000' || !stristr($e->getMessage(), 'server has gone away') || $this->reconnectCount >= 3) {
$this->notify($e);
}
// if we have "PDOException: SQLSTATE[HY000]: General error: 2006 MySQL
// server has gone away", try to reconnect and re-run query
$this->reconnect();
return $this->query($sQL, $args);
}
$end = microtime();
$endEx = explode(' ', $end);
$end = $endEx[1] + $endEx[0];
$total = number_format($end - $start, 6);
self::$queries[$nextIndex]['end'] = $end;
self::$queries[$nextIndex]['total'] = $total;
$this->result = $sth;
return $this->result;
}
// Returns the number of rows.
// You can pass in nothing, a string, or a db result
public function numRows($arg = null) {
$result = $this->resulter($arg);
return ($result !== false) ? $result->rowCount() : false;
}
// Returns true / false if the result has one or more rows
public function hasRows($arg = null) {
$result = $this->resulter($arg);
return is_object($result) && ($result->rowCount() > 0);
}
// Returns the number of rows affected by the previous operation
public function affectedRows() {
if (!$this->isConnected()) {
return false;
}
return $this->result->rowCount();
}
// Returns the auto increment ID generated by the previous insert statement
public function insertId() {
if (!$this->isConnected()) {
return false;
}
$id = $this->db->lastInsertId();
if ($id === 0 || $id === false) {
return false;
}
return $id;
}
// Returns a single value.
// You can pass in nothing, a string, or a db result
public function getValue($arg = null, $args_to_prepare = array()) {
$result = $this->resulter($arg, $args_to_prepare);
$data = false;
if ($result) {
$row = $result->fetch(PDO::FETCH_NUM);
if (is_array($row) && array_key_exists(0, $row)) {
$data = $row[0];
}
}
return $data;
}
// Returns the first row.
// You can pass in nothing, a string, or a db result
public function getRow($arg = null, $args_to_prepare = array(), $fetchType = PDO::FETCH_ASSOC) {
$result = $this->resulter($arg, $args_to_prepare);
$data = $result->fetch($fetchType);
return $result->rowCount() ? $data : false;
}
// Returns an array of all the rows.
// You can pass in nothing, a string, or a db result
public function getRows($arg = null, $args_to_prepare = array(), $fetchType = PDO::FETCH_ASSOC) {
$result = $this->resulter($arg, $args_to_prepare);
$data = $result->fetchAll($fetchType);
return $result->rowCount() ? $data : array();
}
// Escapes a value and wraps it in single quotes.
public function quote($var) {
if (!$this->isConnected()) {
$this->connect();
}
return $this->db->quote($var);
}
// Escapes a value.
public function escape($var) {
if (!$this->isConnected()) {
$this->connect();
}
$str = $this->db->quote($var);
if (strlen($str) > 2) {
$str = substr($str, 1, strlen($str) - 2);
}
return $str;
}
public function numQueries() {
return count(self::$queries);
}
public function lastQuery() {
if ($this->numQueries() > 0) {
return self::$queries[$this->numQueries() - 1];
}
return false;
}
private function notify($errMsg = null) {
if ($errMsg === null) {
$errors = $this->db->errorInfo();
$errMsg = implode(".", $errors);
}
error_log($errMsg);
if ($this->dieOnError === true) {
echo "<p style='border:5px solid red;background-color:#fff;padding:12px;font-family: verdana, sans-serif;'><strong>Database Error:</strong><br/>$errMsg</p>";
$lastQuery = $this->lastQuery();
if ($lastQuery !== false) {
echo "<p style='border:5px solid red;background-color:#fff;padding:12px;font-family: verdana, sans-serif;'><strong>Last Rendered Query:</strong><br/>" . $lastQuery['sql'] . "</p>";
}
echo "<pre>";
debug_print_backtrace();
echo "</pre>";
exit;
}
if (is_string($this->redirect)) {
header("Location: {$this->redirect}");
exit;
}
}
// Takes nothing, a MySQL result, or a query string and returns
// the correspsonding MySQL result resource or false if none available.
private function resulter($arg = null, $args_to_prepare = array()) {
if (is_null($arg) && is_object($this->result)) {
return $this->result;
}
elseif (is_object($arg)) {
return $arg;
}
elseif (is_string($arg)) {
$this->query($arg, $args_to_prepare);
if (is_object($this->result)) {
return $this->result;
}
return false;
}
return false;
}
private function havePDODriver() {
// check for pdo driver
if (!class_exists('PDO')) {
return false;
}
return true;
}
/**
* To fetch Only the next row from the result data in form of [key][value] array.
*
* @access public
* @return array|bool false on if no data returned
*/
public function fetchAssociative() {
return $this->statement->fetch(PDO::FETCH_ASSOC);
}
/**
* Counts the number of rows in a specific table
*
* @access public
* @param string $table
* @return integer
*
*/
public function countAll($table) {
return (int) $this->getValue('SELECT COUNT(*) AS count '
. 'FROM ' . $table);
}
}
process_file_queue.cron.php
<?php
namespace App\Tasks;
// include framework
use App\Core\Framework;
use App\Helpers\BackgroundTaskHelper;
use App\Helpers\FileActionHelper;
use App\Helpers\FileHelper;
require_once(realpath(dirname(__FILE__).'/../core/Framework.class.php'));
// setup light environment
Framework::runLight();
// background task logging
BackgroundTaskHelper::start();
// process delete queue
FileActionHelper::processQueue('delete');
// process move queue
FileActionHelper::processQueue('move', 1);
// process restoration queue
FileActionHelper::processQueue('restore', 50);
// update storage stats
FileHelper::updateFileServerStorageStats();
// background task logging
BackgroundTaskHelper::end();
Salida cambiando notify
object(PDOException)#3 (8) {
["message":protected]=>
string(21) "could not find driver"
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(70) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php"
["line":protected]=>
int(72)
["trace":"Exception":private]=>
array(7) {
[0]=>
array(5) {
["file"]=>
string(70) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php"
["line"]=>
int(72)
["function"]=>
string(11) "__construct"
["class"]=>
string(3) "PDO"
["type"]=>
string(2) "->"
}
[1]=>
array(5) {
["file"]=>
string(70) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php"
["line"]=>
int(30)
["function"]=>
string(7) "connect"
["class"]=>
string(17) "App\Core\Database"
["type"]=>
string(2) "->"
}
[2]=>
array(5) {
["file"]=>
string(70) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php"
["line"]=>
int(37)
["function"]=>
string(11) "__construct"
["class"]=>
string(17) "App\Core\Database"
["type"]=>
string(2) "->"
}
[3]=>
array(5) {
["file"]=>
string(71) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php"
["line"]=>
int(182)
["function"]=>
string(11) "getDatabase"
["class"]=>
string(17) "App\Core\Database"
["type"]=>
string(2) "::"
}
[4]=>
array(5) {
["file"]=>
string(71) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php"
["line"]=>
int(50)
["function"]=>
string(20) "initConfigIntoMemory"
["class"]=>
string(18) "App\Core\Framework"
["type"]=>
string(2) "::"
}
[5]=>
array(5) {
["file"]=>
string(71) "/home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php"
["line"]=>
int(24)
["function"]=>
string(4) "init"
["class"]=>
string(18) "App\Core\Framework"
["type"]=>
string(2) "::"
}
[6]=>
array(5) {
["file"]=>
string(80) "/home/mrva/web/uptomycloud.xyz/public_html/app/tasks/process_file_queue.cron.php"
["line"]=>
int(29)
["function"]=>
string(8) "runLight"
["class"]=>
string(18) "App\Core\Framework"
["type"]=>
string(2) "::"
}
}
["previous":"Exception":private]=>
NULL
["errorInfo"]=>
NULL
}
PHP Fatal error: Uncaught Error: Call to a member function errorInfo() on bool in /home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php:286
Stack trace:
#0 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php(80): App\Core\Database->notify()
#1 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php(30): App\Core\Database->connect()
#2 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php(37): App\Core\Database->__construct()
#3 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php(182): App\Core\Database::getDatabase()
#4 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php(50): App\Core\Framework::initConfigIntoMemory()
#5 /home/mrva/web/uptomycloud.xyz/public_html/app/core/Framework.class.php(24): App\Core\Framework::init()
#6 /home/mrva/web/uptomycloud.xyz/public_html/app/tasks/process_file_queue.cron.php(29): App\Core\Framework::runLight()
#7 {main}
thrown in /home/mrva/web/uptomycloud.xyz/public_html/app/core/Database.class.php on line 286