| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('ABSPATH')) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
trait ABJ_404_Solution_DataAccess_ConnectionTrait { |
| 8 |
|
| 9 |
/** |
| 10 |
* Probe wpdb's check_connection method defensively for custom wpdb |
| 11 |
* drop-ins (HyperDB, LudicrousDB, mu-cluster proxies) that may not |
| 12 |
* implement it. WordPress core has shipped this method since 4.1, |
| 13 |
* but a `wp-content/db.php` drop-in can replace `$wpdb` with a |
| 14 |
* subclass that omits it. Calling an undefined method on such a |
| 15 |
* subclass throws a fatal Error before we'd hit a try/catch. |
| 16 |
* |
| 17 |
* Returns true (assume connected) when the method is missing -- the |
| 18 |
* absence of a probe is not a connection failure, and the standard |
| 19 |
* wpdb default is also "no probe == connected". |
| 20 |
* |
| 21 |
* @param object $wpdb The current $wpdb instance (or subclass). |
| 22 |
* @param bool $allowReconnect Passed through to check_connection(). |
| 23 |
* @return bool True if connected (or unable to probe); false if probed and disconnected. |
| 24 |
*/ |
| 25 |
private function safeCheckConnection($wpdb, $allowReconnect = false) { |
| 26 |
if (!is_object($wpdb)) { |
| 27 |
return true; |
| 28 |
} |
| 29 |
if (!method_exists($wpdb, 'check_connection') && !is_callable(array($wpdb, 'check_connection'))) { |
| 30 |
return true; |
| 31 |
} |
| 32 |
return (bool) $wpdb->check_connection($allowReconnect); |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Ensure database connection is active and reconnect if necessary. |
| 37 |
* |
| 38 |
* @return bool True if connection is active, false otherwise |
| 39 |
*/ |
| 40 |
private function ensureConnection() { |
| 41 |
global $wpdb; |
| 42 |
|
| 43 |
if (!isset($wpdb)) { |
| 44 |
return true; |
| 45 |
} |
| 46 |
|
| 47 |
try { |
| 48 |
$isConnected = $this->safeCheckConnection($wpdb, false); |
| 49 |
|
| 50 |
if (!$isConnected) { |
| 51 |
$this->logger->debugMessage("Database connection lost, attempting to reconnect..."); |
| 52 |
|
| 53 |
if (is_object($wpdb) && method_exists($wpdb, 'db_connect')) { |
| 54 |
$wpdb->db_connect(); |
| 55 |
} |
| 56 |
|
| 57 |
if ($this->safeCheckConnection($wpdb, false)) { |
| 58 |
$this->logger->debugMessage("Database reconnection successful"); |
| 59 |
return true; |
| 60 |
} |
| 61 |
|
| 62 |
$this->logger->errorMessage("Failed to reconnect to database"); |
| 63 |
return false; |
| 64 |
} |
| 65 |
} catch (Exception $e) { |
| 66 |
$this->logger->debugMessage("Connection check failed: " . $e->getMessage()); |
| 67 |
return true; |
| 68 |
} catch (Error $e) { |
| 69 |
$this->logger->debugMessage("Connection check not available: " . $e->getMessage()); |
| 70 |
return true; |
| 71 |
} |
| 72 |
|
| 73 |
return true; |
| 74 |
} |
| 75 |
} |
| 76 |
|