class-wpdb.php 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874
  1. <?php
  2. /**
  3. * WordPress database access abstraction class.
  4. *
  5. * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
  6. *
  7. * @package WordPress
  8. * @subpackage Database
  9. * @since 0.71
  10. */
  11. /**
  12. * @since 0.71
  13. */
  14. define( 'EZSQL_VERSION', 'WP1.25' );
  15. /**
  16. * @since 0.71
  17. */
  18. define( 'OBJECT', 'OBJECT' );
  19. // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ConstantNotUpperCase
  20. define( 'object', 'OBJECT' ); // Back compat.
  21. /**
  22. * @since 2.5.0
  23. */
  24. define( 'OBJECT_K', 'OBJECT_K' );
  25. /**
  26. * @since 0.71
  27. */
  28. define( 'ARRAY_A', 'ARRAY_A' );
  29. /**
  30. * @since 0.71
  31. */
  32. define( 'ARRAY_N', 'ARRAY_N' );
  33. /**
  34. * WordPress database access abstraction class.
  35. *
  36. * This class is used to interact with a database without needing to use raw SQL statements.
  37. * By default, WordPress uses this class to instantiate the global $wpdb object, providing
  38. * access to the WordPress database.
  39. *
  40. * It is possible to replace this class with your own by setting the $wpdb global variable
  41. * in wp-content/db.php file to your class. The wpdb class will still be included, so you can
  42. * extend it or simply use your own.
  43. *
  44. * @link https://developer.wordpress.org/reference/classes/wpdb/
  45. *
  46. * @since 0.71
  47. */
  48. #[AllowDynamicProperties]
  49. class wpdb {
  50. /**
  51. * Whether to show SQL/DB errors.
  52. *
  53. * Default is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY evaluate to true.
  54. *
  55. * @since 0.71
  56. *
  57. * @var bool
  58. */
  59. public $show_errors = false;
  60. /**
  61. * Whether to suppress errors during the DB bootstrapping. Default false.
  62. *
  63. * @since 2.5.0
  64. *
  65. * @var bool
  66. */
  67. public $suppress_errors = false;
  68. /**
  69. * The error encountered during the last query.
  70. *
  71. * @since 2.5.0
  72. *
  73. * @var string
  74. */
  75. public $last_error = '';
  76. /**
  77. * The number of queries made.
  78. *
  79. * @since 1.2.0
  80. *
  81. * @var int
  82. */
  83. public $num_queries = 0;
  84. /**
  85. * Count of rows returned by the last query.
  86. *
  87. * @since 0.71
  88. *
  89. * @var int
  90. */
  91. public $num_rows = 0;
  92. /**
  93. * Count of rows affected by the last query.
  94. *
  95. * @since 0.71
  96. *
  97. * @var int
  98. */
  99. public $rows_affected = 0;
  100. /**
  101. * The ID generated for an AUTO_INCREMENT column by the last query (usually INSERT).
  102. *
  103. * @since 0.71
  104. *
  105. * @var int
  106. */
  107. public $insert_id = 0;
  108. /**
  109. * The last query made.
  110. *
  111. * @since 0.71
  112. *
  113. * @var string
  114. */
  115. public $last_query;
  116. /**
  117. * Results of the last query.
  118. *
  119. * @since 0.71
  120. *
  121. * @var stdClass[]|null
  122. */
  123. public $last_result;
  124. /**
  125. * Database query result.
  126. *
  127. * Possible values:
  128. *
  129. * - For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries:
  130. * - `mysqli_result` instance when the `mysqli` driver is in use
  131. * - `resource` when the older `mysql` driver is in use
  132. * - `true` for other query types that were successful
  133. * - `null` if a query is yet to be made or if the result has since been flushed
  134. * - `false` if the query returned an error
  135. *
  136. * @since 0.71
  137. *
  138. * @var mysqli_result|resource|bool|null
  139. */
  140. protected $result;
  141. /**
  142. * Cached column info, for sanity checking data before inserting.
  143. *
  144. * @since 4.2.0
  145. *
  146. * @var array
  147. */
  148. protected $col_meta = array();
  149. /**
  150. * Calculated character sets keyed by table name.
  151. *
  152. * @since 4.2.0
  153. *
  154. * @var string[]
  155. */
  156. protected $table_charset = array();
  157. /**
  158. * Whether text fields in the current query need to be sanity checked.
  159. *
  160. * @since 4.2.0
  161. *
  162. * @var bool
  163. */
  164. protected $check_current_query = true;
  165. /**
  166. * Flag to ensure we don't run into recursion problems when checking the collation.
  167. *
  168. * @since 4.2.0
  169. *
  170. * @see wpdb::check_safe_collation()
  171. * @var bool
  172. */
  173. private $checking_collation = false;
  174. /**
  175. * Saved info on the table column.
  176. *
  177. * @since 0.71
  178. *
  179. * @var array
  180. */
  181. protected $col_info;
  182. /**
  183. * Log of queries that were executed, for debugging purposes.
  184. *
  185. * @since 1.5.0
  186. * @since 2.5.0 The third element in each query log was added to record the calling functions.
  187. * @since 5.1.0 The fourth element in each query log was added to record the start time.
  188. * @since 5.3.0 The fifth element in each query log was added to record custom data.
  189. *
  190. * @var array[] {
  191. * Array of arrays containing information about queries that were executed.
  192. *
  193. * @type array ...$0 {
  194. * Data for each query.
  195. *
  196. * @type string $0 The query's SQL.
  197. * @type float $1 Total time spent on the query, in seconds.
  198. * @type string $2 Comma-separated list of the calling functions.
  199. * @type float $3 Unix timestamp of the time at the start of the query.
  200. * @type array $4 Custom query data.
  201. * }
  202. * }
  203. */
  204. public $queries;
  205. /**
  206. * The number of times to retry reconnecting before dying. Default 5.
  207. *
  208. * @since 3.9.0
  209. *
  210. * @see wpdb::check_connection()
  211. * @var int
  212. */
  213. protected $reconnect_retries = 5;
  214. /**
  215. * WordPress table prefix.
  216. *
  217. * You can set this to have multiple WordPress installations in a single database.
  218. * The second reason is for possible security precautions.
  219. *
  220. * @since 2.5.0
  221. *
  222. * @var string
  223. */
  224. public $prefix = '';
  225. /**
  226. * WordPress base table prefix.
  227. *
  228. * @since 3.0.0
  229. *
  230. * @var string
  231. */
  232. public $base_prefix;
  233. /**
  234. * Whether the database queries are ready to start executing.
  235. *
  236. * @since 2.3.2
  237. *
  238. * @var bool
  239. */
  240. public $ready = false;
  241. /**
  242. * Blog ID.
  243. *
  244. * @since 3.0.0
  245. *
  246. * @var int
  247. */
  248. public $blogid = 0;
  249. /**
  250. * Site ID.
  251. *
  252. * @since 3.0.0
  253. *
  254. * @var int
  255. */
  256. public $siteid = 0;
  257. /**
  258. * List of WordPress per-site tables.
  259. *
  260. * @since 2.5.0
  261. *
  262. * @see wpdb::tables()
  263. * @var string[]
  264. */
  265. public $tables = array(
  266. 'posts',
  267. 'comments',
  268. 'links',
  269. 'options',
  270. 'postmeta',
  271. 'terms',
  272. 'term_taxonomy',
  273. 'term_relationships',
  274. 'termmeta',
  275. 'commentmeta',
  276. );
  277. /**
  278. * List of deprecated WordPress tables.
  279. *
  280. * 'categories', 'post2cat', and 'link2cat' were deprecated in 2.3.0, db version 5539.
  281. *
  282. * @since 2.9.0
  283. *
  284. * @see wpdb::tables()
  285. * @var string[]
  286. */
  287. public $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  288. /**
  289. * List of WordPress global tables.
  290. *
  291. * @since 3.0.0
  292. *
  293. * @see wpdb::tables()
  294. * @var string[]
  295. */
  296. public $global_tables = array( 'users', 'usermeta' );
  297. /**
  298. * List of Multisite global tables.
  299. *
  300. * @since 3.0.0
  301. *
  302. * @see wpdb::tables()
  303. * @var string[]
  304. */
  305. public $ms_global_tables = array(
  306. 'blogs',
  307. 'blogmeta',
  308. 'signups',
  309. 'site',
  310. 'sitemeta',
  311. 'registration_log',
  312. );
  313. /**
  314. * List of deprecated WordPress Multisite global tables.
  315. *
  316. * @since 6.1.0
  317. *
  318. * @see wpdb::tables()
  319. * @var string[]
  320. */
  321. public $old_ms_global_tables = array( 'sitecategories' );
  322. /**
  323. * WordPress Comments table.
  324. *
  325. * @since 1.5.0
  326. *
  327. * @var string
  328. */
  329. public $comments;
  330. /**
  331. * WordPress Comment Metadata table.
  332. *
  333. * @since 2.9.0
  334. *
  335. * @var string
  336. */
  337. public $commentmeta;
  338. /**
  339. * WordPress Links table.
  340. *
  341. * @since 1.5.0
  342. *
  343. * @var string
  344. */
  345. public $links;
  346. /**
  347. * WordPress Options table.
  348. *
  349. * @since 1.5.0
  350. *
  351. * @var string
  352. */
  353. public $options;
  354. /**
  355. * WordPress Post Metadata table.
  356. *
  357. * @since 1.5.0
  358. *
  359. * @var string
  360. */
  361. public $postmeta;
  362. /**
  363. * WordPress Posts table.
  364. *
  365. * @since 1.5.0
  366. *
  367. * @var string
  368. */
  369. public $posts;
  370. /**
  371. * WordPress Terms table.
  372. *
  373. * @since 2.3.0
  374. *
  375. * @var string
  376. */
  377. public $terms;
  378. /**
  379. * WordPress Term Relationships table.
  380. *
  381. * @since 2.3.0
  382. *
  383. * @var string
  384. */
  385. public $term_relationships;
  386. /**
  387. * WordPress Term Taxonomy table.
  388. *
  389. * @since 2.3.0
  390. *
  391. * @var string
  392. */
  393. public $term_taxonomy;
  394. /**
  395. * WordPress Term Meta table.
  396. *
  397. * @since 4.4.0
  398. *
  399. * @var string
  400. */
  401. public $termmeta;
  402. //
  403. // Global and Multisite tables
  404. //
  405. /**
  406. * WordPress User Metadata table.
  407. *
  408. * @since 2.3.0
  409. *
  410. * @var string
  411. */
  412. public $usermeta;
  413. /**
  414. * WordPress Users table.
  415. *
  416. * @since 1.5.0
  417. *
  418. * @var string
  419. */
  420. public $users;
  421. /**
  422. * Multisite Blogs table.
  423. *
  424. * @since 3.0.0
  425. *
  426. * @var string
  427. */
  428. public $blogs;
  429. /**
  430. * Multisite Blog Metadata table.
  431. *
  432. * @since 5.1.0
  433. *
  434. * @var string
  435. */
  436. public $blogmeta;
  437. /**
  438. * Multisite Registration Log table.
  439. *
  440. * @since 3.0.0
  441. *
  442. * @var string
  443. */
  444. public $registration_log;
  445. /**
  446. * Multisite Signups table.
  447. *
  448. * @since 3.0.0
  449. *
  450. * @var string
  451. */
  452. public $signups;
  453. /**
  454. * Multisite Sites table.
  455. *
  456. * @since 3.0.0
  457. *
  458. * @var string
  459. */
  460. public $site;
  461. /**
  462. * Multisite Sitewide Terms table.
  463. *
  464. * @since 3.0.0
  465. *
  466. * @var string
  467. */
  468. public $sitecategories;
  469. /**
  470. * Multisite Site Metadata table.
  471. *
  472. * @since 3.0.0
  473. *
  474. * @var string
  475. */
  476. public $sitemeta;
  477. /**
  478. * Format specifiers for DB columns.
  479. *
  480. * Columns not listed here default to %s. Initialized during WP load.
  481. * Keys are column names, values are format types: 'ID' => '%d'.
  482. *
  483. * @since 2.8.0
  484. *
  485. * @see wpdb::prepare()
  486. * @see wpdb::insert()
  487. * @see wpdb::update()
  488. * @see wpdb::delete()
  489. * @see wp_set_wpdb_vars()
  490. * @var array
  491. */
  492. public $field_types = array();
  493. /**
  494. * Database table columns charset.
  495. *
  496. * @since 2.2.0
  497. *
  498. * @var string
  499. */
  500. public $charset;
  501. /**
  502. * Database table columns collate.
  503. *
  504. * @since 2.2.0
  505. *
  506. * @var string
  507. */
  508. public $collate;
  509. /**
  510. * Database Username.
  511. *
  512. * @since 2.9.0
  513. *
  514. * @var string
  515. */
  516. protected $dbuser;
  517. /**
  518. * Database Password.
  519. *
  520. * @since 3.1.0
  521. *
  522. * @var string
  523. */
  524. protected $dbpassword;
  525. /**
  526. * Database Name.
  527. *
  528. * @since 3.1.0
  529. *
  530. * @var string
  531. */
  532. protected $dbname;
  533. /**
  534. * Database Host.
  535. *
  536. * @since 3.1.0
  537. *
  538. * @var string
  539. */
  540. protected $dbhost;
  541. /**
  542. * Database handle.
  543. *
  544. * Possible values:
  545. *
  546. * - `mysqli` instance when the `mysqli` driver is in use
  547. * - `resource` when the older `mysql` driver is in use
  548. * - `null` if the connection is yet to be made or has been closed
  549. * - `false` if the connection has failed
  550. *
  551. * @since 0.71
  552. *
  553. * @var mysqli|resource|false|null
  554. */
  555. protected $dbh;
  556. /**
  557. * A textual description of the last query/get_row/get_var call.
  558. *
  559. * @since 3.0.0
  560. *
  561. * @var string
  562. */
  563. public $func_call;
  564. /**
  565. * Whether MySQL is used as the database engine.
  566. *
  567. * Set in wpdb::db_connect() to true, by default. This is used when checking
  568. * against the required MySQL version for WordPress. Normally, a replacement
  569. * database drop-in (db.php) will skip these checks, but setting this to true
  570. * will force the checks to occur.
  571. *
  572. * @since 3.3.0
  573. *
  574. * @var bool
  575. */
  576. public $is_mysql = null;
  577. /**
  578. * A list of incompatible SQL modes.
  579. *
  580. * @since 3.9.0
  581. *
  582. * @var string[]
  583. */
  584. protected $incompatible_modes = array(
  585. 'NO_ZERO_DATE',
  586. 'ONLY_FULL_GROUP_BY',
  587. 'STRICT_TRANS_TABLES',
  588. 'STRICT_ALL_TABLES',
  589. 'TRADITIONAL',
  590. 'ANSI',
  591. );
  592. /**
  593. * Whether to use mysqli over mysql. Default false.
  594. *
  595. * @since 3.9.0
  596. *
  597. * @var bool
  598. */
  599. private $use_mysqli = false;
  600. /**
  601. * Whether we've managed to successfully connect at some point.
  602. *
  603. * @since 3.9.0
  604. *
  605. * @var bool
  606. */
  607. private $has_connected = false;
  608. /**
  609. * Time when the last query was performed.
  610. *
  611. * Only set when `SAVEQUERIES` is defined and truthy.
  612. *
  613. * @since 1.5.0
  614. *
  615. * @var float
  616. */
  617. public $time_start = null;
  618. /**
  619. * The last SQL error that was encountered.
  620. *
  621. * @since 2.5.0
  622. *
  623. * @var WP_Error|string
  624. */
  625. public $error = null;
  626. /**
  627. * Connects to the database server and selects a database.
  628. *
  629. * Does the actual setting up
  630. * of the class properties and connection to the database.
  631. *
  632. * @since 2.0.8
  633. *
  634. * @link https://core.trac.wordpress.org/ticket/3354
  635. *
  636. * @param string $dbuser Database user.
  637. * @param string $dbpassword Database password.
  638. * @param string $dbname Database name.
  639. * @param string $dbhost Database host.
  640. */
  641. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  642. if ( WP_DEBUG && WP_DEBUG_DISPLAY ) {
  643. $this->show_errors();
  644. }
  645. // Use the `mysqli` extension if it exists unless `WP_USE_EXT_MYSQL` is defined as true.
  646. if ( function_exists( 'mysqli_connect' ) ) {
  647. $this->use_mysqli = true;
  648. if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
  649. $this->use_mysqli = ! WP_USE_EXT_MYSQL;
  650. }
  651. }
  652. $this->dbuser = $dbuser;
  653. $this->dbpassword = $dbpassword;
  654. $this->dbname = $dbname;
  655. $this->dbhost = $dbhost;
  656. // wp-config.php creation will manually connect when ready.
  657. if ( defined( 'WP_SETUP_CONFIG' ) ) {
  658. return;
  659. }
  660. $this->db_connect();
  661. }
  662. /**
  663. * Makes private properties readable for backward compatibility.
  664. *
  665. * @since 3.5.0
  666. *
  667. * @param string $name The private member to get, and optionally process.
  668. * @return mixed The private member.
  669. */
  670. public function __get( $name ) {
  671. if ( 'col_info' === $name ) {
  672. $this->load_col_info();
  673. }
  674. return $this->$name;
  675. }
  676. /**
  677. * Makes private properties settable for backward compatibility.
  678. *
  679. * @since 3.5.0
  680. *
  681. * @param string $name The private member to set.
  682. * @param mixed $value The value to set.
  683. */
  684. public function __set( $name, $value ) {
  685. $protected_members = array(
  686. 'col_meta',
  687. 'table_charset',
  688. 'check_current_query',
  689. );
  690. if ( in_array( $name, $protected_members, true ) ) {
  691. return;
  692. }
  693. $this->$name = $value;
  694. }
  695. /**
  696. * Makes private properties check-able for backward compatibility.
  697. *
  698. * @since 3.5.0
  699. *
  700. * @param string $name The private member to check.
  701. * @return bool If the member is set or not.
  702. */
  703. public function __isset( $name ) {
  704. return isset( $this->$name );
  705. }
  706. /**
  707. * Makes private properties un-settable for backward compatibility.
  708. *
  709. * @since 3.5.0
  710. *
  711. * @param string $name The private member to unset
  712. */
  713. public function __unset( $name ) {
  714. unset( $this->$name );
  715. }
  716. /**
  717. * Sets $this->charset and $this->collate.
  718. *
  719. * @since 3.1.0
  720. */
  721. public function init_charset() {
  722. $charset = '';
  723. $collate = '';
  724. if ( function_exists( 'is_multisite' ) && is_multisite() ) {
  725. $charset = 'utf8';
  726. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  727. $collate = DB_COLLATE;
  728. } else {
  729. $collate = 'utf8_general_ci';
  730. }
  731. } elseif ( defined( 'DB_COLLATE' ) ) {
  732. $collate = DB_COLLATE;
  733. }
  734. if ( defined( 'DB_CHARSET' ) ) {
  735. $charset = DB_CHARSET;
  736. }
  737. $charset_collate = $this->determine_charset( $charset, $collate );
  738. $this->charset = $charset_collate['charset'];
  739. $this->collate = $charset_collate['collate'];
  740. }
  741. /**
  742. * Determines the best charset and collation to use given a charset and collation.
  743. *
  744. * For example, when able, utf8mb4 should be used instead of utf8.
  745. *
  746. * @since 4.6.0
  747. *
  748. * @param string $charset The character set to check.
  749. * @param string $collate The collation to check.
  750. * @return array {
  751. * The most appropriate character set and collation to use.
  752. *
  753. * @type string $charset Character set.
  754. * @type string $collate Collation.
  755. * }
  756. */
  757. public function determine_charset( $charset, $collate ) {
  758. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
  759. return compact( 'charset', 'collate' );
  760. }
  761. if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
  762. $charset = 'utf8mb4';
  763. }
  764. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  765. $charset = 'utf8';
  766. $collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
  767. }
  768. if ( 'utf8mb4' === $charset ) {
  769. // _general_ is outdated, so we can upgrade it to _unicode_, instead.
  770. if ( ! $collate || 'utf8_general_ci' === $collate ) {
  771. $collate = 'utf8mb4_unicode_ci';
  772. } else {
  773. $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
  774. }
  775. }
  776. // _unicode_520_ is a better collation, we should use that when it's available.
  777. if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
  778. $collate = 'utf8mb4_unicode_520_ci';
  779. }
  780. return compact( 'charset', 'collate' );
  781. }
  782. /**
  783. * Sets the connection's character set.
  784. *
  785. * @since 3.1.0
  786. *
  787. * @param mysqli|resource $dbh The connection returned by `mysqli_connect()` or `mysql_connect()`.
  788. * @param string $charset Optional. The character set. Default null.
  789. * @param string $collate Optional. The collation. Default null.
  790. */
  791. public function set_charset( $dbh, $charset = null, $collate = null ) {
  792. if ( ! isset( $charset ) ) {
  793. $charset = $this->charset;
  794. }
  795. if ( ! isset( $collate ) ) {
  796. $collate = $this->collate;
  797. }
  798. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  799. $set_charset_succeeded = true;
  800. if ( $this->use_mysqli ) {
  801. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  802. $set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
  803. }
  804. if ( $set_charset_succeeded ) {
  805. $query = $this->prepare( 'SET NAMES %s', $charset );
  806. if ( ! empty( $collate ) ) {
  807. $query .= $this->prepare( ' COLLATE %s', $collate );
  808. }
  809. mysqli_query( $dbh, $query );
  810. }
  811. } else {
  812. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  813. $set_charset_succeeded = mysql_set_charset( $charset, $dbh );
  814. }
  815. if ( $set_charset_succeeded ) {
  816. $query = $this->prepare( 'SET NAMES %s', $charset );
  817. if ( ! empty( $collate ) ) {
  818. $query .= $this->prepare( ' COLLATE %s', $collate );
  819. }
  820. mysql_query( $query, $dbh );
  821. }
  822. }
  823. }
  824. }
  825. /**
  826. * Changes the current SQL mode, and ensures its WordPress compatibility.
  827. *
  828. * If no modes are passed, it will ensure the current MySQL server modes are compatible.
  829. *
  830. * @since 3.9.0
  831. *
  832. * @param array $modes Optional. A list of SQL modes to set. Default empty array.
  833. */
  834. public function set_sql_mode( $modes = array() ) {
  835. if ( empty( $modes ) ) {
  836. if ( $this->use_mysqli ) {
  837. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  838. } else {
  839. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  840. }
  841. if ( empty( $res ) ) {
  842. return;
  843. }
  844. if ( $this->use_mysqli ) {
  845. $modes_array = mysqli_fetch_array( $res );
  846. if ( empty( $modes_array[0] ) ) {
  847. return;
  848. }
  849. $modes_str = $modes_array[0];
  850. } else {
  851. $modes_str = mysql_result( $res, 0 );
  852. }
  853. if ( empty( $modes_str ) ) {
  854. return;
  855. }
  856. $modes = explode( ',', $modes_str );
  857. }
  858. $modes = array_change_key_case( $modes, CASE_UPPER );
  859. /**
  860. * Filters the list of incompatible SQL modes to exclude.
  861. *
  862. * @since 3.9.0
  863. *
  864. * @param array $incompatible_modes An array of incompatible modes.
  865. */
  866. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  867. foreach ( $modes as $i => $mode ) {
  868. if ( in_array( $mode, $incompatible_modes, true ) ) {
  869. unset( $modes[ $i ] );
  870. }
  871. }
  872. $modes_str = implode( ',', $modes );
  873. if ( $this->use_mysqli ) {
  874. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  875. } else {
  876. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  877. }
  878. }
  879. /**
  880. * Sets the table prefix for the WordPress tables.
  881. *
  882. * @since 2.5.0
  883. *
  884. * @param string $prefix Alphanumeric name for the new prefix.
  885. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts,
  886. * should be updated or not. Default true.
  887. * @return string|WP_Error Old prefix or WP_Error on error.
  888. */
  889. public function set_prefix( $prefix, $set_table_names = true ) {
  890. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) {
  891. return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' );
  892. }
  893. $old_prefix = is_multisite() ? '' : $prefix;
  894. if ( isset( $this->base_prefix ) ) {
  895. $old_prefix = $this->base_prefix;
  896. }
  897. $this->base_prefix = $prefix;
  898. if ( $set_table_names ) {
  899. foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) {
  900. $this->$table = $prefixed_table;
  901. }
  902. if ( is_multisite() && empty( $this->blogid ) ) {
  903. return $old_prefix;
  904. }
  905. $this->prefix = $this->get_blog_prefix();
  906. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  907. $this->$table = $prefixed_table;
  908. }
  909. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  910. $this->$table = $prefixed_table;
  911. }
  912. }
  913. return $old_prefix;
  914. }
  915. /**
  916. * Sets blog ID.
  917. *
  918. * @since 3.0.0
  919. *
  920. * @param int $blog_id
  921. * @param int $network_id Optional.
  922. * @return int Previous blog ID.
  923. */
  924. public function set_blog_id( $blog_id, $network_id = 0 ) {
  925. if ( ! empty( $network_id ) ) {
  926. $this->siteid = $network_id;
  927. }
  928. $old_blog_id = $this->blogid;
  929. $this->blogid = $blog_id;
  930. $this->prefix = $this->get_blog_prefix();
  931. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  932. $this->$table = $prefixed_table;
  933. }
  934. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  935. $this->$table = $prefixed_table;
  936. }
  937. return $old_blog_id;
  938. }
  939. /**
  940. * Gets blog prefix.
  941. *
  942. * @since 3.0.0
  943. *
  944. * @param int $blog_id Optional.
  945. * @return string Blog prefix.
  946. */
  947. public function get_blog_prefix( $blog_id = null ) {
  948. if ( is_multisite() ) {
  949. if ( null === $blog_id ) {
  950. $blog_id = $this->blogid;
  951. }
  952. $blog_id = (int) $blog_id;
  953. if ( defined( 'MULTISITE' ) && ( 0 === $blog_id || 1 === $blog_id ) ) {
  954. return $this->base_prefix;
  955. } else {
  956. return $this->base_prefix . $blog_id . '_';
  957. }
  958. } else {
  959. return $this->base_prefix;
  960. }
  961. }
  962. /**
  963. * Returns an array of WordPress tables.
  964. *
  965. * Also allows for the `CUSTOM_USER_TABLE` and `CUSTOM_USER_META_TABLE` to override the WordPress users
  966. * and usermeta tables that would otherwise be determined by the prefix.
  967. *
  968. * The `$scope` argument can take one of the following:
  969. *
  970. * - 'all' - returns 'all' and 'global' tables. No old tables are returned.
  971. * - 'blog' - returns the blog-level tables for the queried blog.
  972. * - 'global' - returns the global tables for the installation, returning multisite tables only on multisite.
  973. * - 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  974. * - 'old' - returns tables which are deprecated.
  975. *
  976. * @since 3.0.0
  977. * @since 6.1.0 `old` now includes deprecated multisite global tables only on multisite.
  978. *
  979. * @uses wpdb::$tables
  980. * @uses wpdb::$old_tables
  981. * @uses wpdb::$global_tables
  982. * @uses wpdb::$ms_global_tables
  983. * @uses wpdb::$old_ms_global_tables
  984. *
  985. * @param string $scope Optional. Possible values include 'all', 'global', 'ms_global', 'blog',
  986. * or 'old' tables. Default 'all'.
  987. * @param bool $prefix Optional. Whether to include table prefixes. If blog prefix is requested,
  988. * then the custom users and usermeta tables will be mapped. Default true.
  989. * @param int $blog_id Optional. The blog_id to prefix. Used only when prefix is requested.
  990. * Defaults to `wpdb::$blogid`.
  991. * @return string[] Table names. When a prefix is requested, the key is the unprefixed table name.
  992. */
  993. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  994. switch ( $scope ) {
  995. case 'all':
  996. $tables = array_merge( $this->global_tables, $this->tables );
  997. if ( is_multisite() ) {
  998. $tables = array_merge( $tables, $this->ms_global_tables );
  999. }
  1000. break;
  1001. case 'blog':
  1002. $tables = $this->tables;
  1003. break;
  1004. case 'global':
  1005. $tables = $this->global_tables;
  1006. if ( is_multisite() ) {
  1007. $tables = array_merge( $tables, $this->ms_global_tables );
  1008. }
  1009. break;
  1010. case 'ms_global':
  1011. $tables = $this->ms_global_tables;
  1012. break;
  1013. case 'old':
  1014. $tables = $this->old_tables;
  1015. if ( is_multisite() ) {
  1016. $tables = array_merge( $tables, $this->old_ms_global_tables );
  1017. }
  1018. break;
  1019. default:
  1020. return array();
  1021. }
  1022. if ( $prefix ) {
  1023. if ( ! $blog_id ) {
  1024. $blog_id = $this->blogid;
  1025. }
  1026. $blog_prefix = $this->get_blog_prefix( $blog_id );
  1027. $base_prefix = $this->base_prefix;
  1028. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  1029. foreach ( $tables as $k => $table ) {
  1030. if ( in_array( $table, $global_tables, true ) ) {
  1031. $tables[ $table ] = $base_prefix . $table;
  1032. } else {
  1033. $tables[ $table ] = $blog_prefix . $table;
  1034. }
  1035. unset( $tables[ $k ] );
  1036. }
  1037. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) ) {
  1038. $tables['users'] = CUSTOM_USER_TABLE;
  1039. }
  1040. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) ) {
  1041. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  1042. }
  1043. }
  1044. return $tables;
  1045. }
  1046. /**
  1047. * Selects a database using the current or provided database connection.
  1048. *
  1049. * The database name will be changed based on the current database connection.
  1050. * On failure, the execution will bail and display a DB error.
  1051. *
  1052. * @since 0.71
  1053. *
  1054. * @param string $db Database name.
  1055. * @param mysqli|resource $dbh Optional database connection.
  1056. */
  1057. public function select( $db, $dbh = null ) {
  1058. if ( is_null( $dbh ) ) {
  1059. $dbh = $this->dbh;
  1060. }
  1061. if ( $this->use_mysqli ) {
  1062. $success = mysqli_select_db( $dbh, $db );
  1063. } else {
  1064. $success = mysql_select_db( $db, $dbh );
  1065. }
  1066. if ( ! $success ) {
  1067. $this->ready = false;
  1068. if ( ! did_action( 'template_redirect' ) ) {
  1069. wp_load_translations_early();
  1070. $message = '<h1>' . __( 'Cannot select database' ) . "</h1>\n";
  1071. $message .= '<p>' . sprintf(
  1072. /* translators: %s: Database name. */
  1073. __( 'The database server could be connected to (which means your username and password is okay) but the %s database could not be selected.' ),
  1074. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  1075. ) . "</p>\n";
  1076. $message .= "<ul>\n";
  1077. $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
  1078. $message .= '<li>' . sprintf(
  1079. /* translators: 1: Database user, 2: Database name. */
  1080. __( 'Does the user %1$s have permission to use the %2$s database?' ),
  1081. '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
  1082. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  1083. ) . "</li>\n";
  1084. $message .= '<li>' . sprintf(
  1085. /* translators: %s: Database name. */
  1086. __( 'On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?' ),
  1087. htmlspecialchars( $db, ENT_QUOTES )
  1088. ) . "</li>\n";
  1089. $message .= "</ul>\n";
  1090. $message .= '<p>' . sprintf(
  1091. /* translators: %s: Support forums URL. */
  1092. __( 'If you do not know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="%s">WordPress Support Forums</a>.' ),
  1093. __( 'https://wordpress.org/support/forums/' )
  1094. ) . "</p>\n";
  1095. $this->bail( $message, 'db_select_fail' );
  1096. }
  1097. }
  1098. }
  1099. /**
  1100. * Do not use, deprecated.
  1101. *
  1102. * Use esc_sql() or wpdb::prepare() instead.
  1103. *
  1104. * @since 2.8.0
  1105. * @deprecated 3.6.0 Use wpdb::prepare()
  1106. * @see wpdb::prepare()
  1107. * @see esc_sql()
  1108. *
  1109. * @param string $string
  1110. * @return string
  1111. */
  1112. public function _weak_escape( $string ) {
  1113. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1114. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1115. }
  1116. return addslashes( $string );
  1117. }
  1118. /**
  1119. * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string().
  1120. *
  1121. * @since 2.8.0
  1122. *
  1123. * @see mysqli_real_escape_string()
  1124. * @see mysql_real_escape_string()
  1125. *
  1126. * @param string $string String to escape.
  1127. * @return string Escaped string.
  1128. */
  1129. public function _real_escape( $string ) {
  1130. if ( ! is_scalar( $string ) ) {
  1131. return '';
  1132. }
  1133. if ( $this->dbh ) {
  1134. if ( $this->use_mysqli ) {
  1135. $escaped = mysqli_real_escape_string( $this->dbh, $string );
  1136. } else {
  1137. $escaped = mysql_real_escape_string( $string, $this->dbh );
  1138. }
  1139. } else {
  1140. $class = get_class( $this );
  1141. wp_load_translations_early();
  1142. /* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */
  1143. _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
  1144. $escaped = addslashes( $string );
  1145. }
  1146. return $this->add_placeholder_escape( $escaped );
  1147. }
  1148. /**
  1149. * Escapes data. Works on arrays.
  1150. *
  1151. * @since 2.8.0
  1152. *
  1153. * @uses wpdb::_real_escape()
  1154. *
  1155. * @param string|array $data Data to escape.
  1156. * @return string|array Escaped data, in the same type as supplied.
  1157. */
  1158. public function _escape( $data ) {
  1159. if ( is_array( $data ) ) {
  1160. foreach ( $data as $k => $v ) {
  1161. if ( is_array( $v ) ) {
  1162. $data[ $k ] = $this->_escape( $v );
  1163. } else {
  1164. $data[ $k ] = $this->_real_escape( $v );
  1165. }
  1166. }
  1167. } else {
  1168. $data = $this->_real_escape( $data );
  1169. }
  1170. return $data;
  1171. }
  1172. /**
  1173. * Do not use, deprecated.
  1174. *
  1175. * Use esc_sql() or wpdb::prepare() instead.
  1176. *
  1177. * @since 0.71
  1178. * @deprecated 3.6.0 Use wpdb::prepare()
  1179. * @see wpdb::prepare()
  1180. * @see esc_sql()
  1181. *
  1182. * @param string|array $data Data to escape.
  1183. * @return string|array Escaped data, in the same type as supplied.
  1184. */
  1185. public function escape( $data ) {
  1186. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1187. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1188. }
  1189. if ( is_array( $data ) ) {
  1190. foreach ( $data as $k => $v ) {
  1191. if ( is_array( $v ) ) {
  1192. $data[ $k ] = $this->escape( $v, 'recursive' );
  1193. } else {
  1194. $data[ $k ] = $this->_weak_escape( $v, 'internal' );
  1195. }
  1196. }
  1197. } else {
  1198. $data = $this->_weak_escape( $data, 'internal' );
  1199. }
  1200. return $data;
  1201. }
  1202. /**
  1203. * Escapes content by reference for insertion into the database, for security.
  1204. *
  1205. * @uses wpdb::_real_escape()
  1206. *
  1207. * @since 2.3.0
  1208. *
  1209. * @param string $string String to escape.
  1210. */
  1211. public function escape_by_ref( &$string ) {
  1212. if ( ! is_float( $string ) ) {
  1213. $string = $this->_real_escape( $string );
  1214. }
  1215. }
  1216. /**
  1217. * Prepares a SQL query for safe execution.
  1218. *
  1219. * Uses sprintf()-like syntax. The following placeholders can be used in the query string:
  1220. *
  1221. * - %d (integer)
  1222. * - %f (float)
  1223. * - %s (string)
  1224. *
  1225. * All placeholders MUST be left unquoted in the query string. A corresponding argument
  1226. * MUST be passed for each placeholder.
  1227. *
  1228. * Note: There is one exception to the above: for compatibility with old behavior,
  1229. * numbered or formatted string placeholders (eg, `%1$s`, `%5s`) will not have quotes
  1230. * added by this function, so should be passed with appropriate quotes around them.
  1231. *
  1232. * Literal percentage signs (`%`) in the query string must be written as `%%`. Percentage wildcards
  1233. * (for example, to use in LIKE syntax) must be passed via a substitution argument containing
  1234. * the complete LIKE string, these cannot be inserted directly in the query string.
  1235. * Also see wpdb::esc_like().
  1236. *
  1237. * Arguments may be passed as individual arguments to the method, or as a single array
  1238. * containing all arguments. A combination of the two is not supported.
  1239. *
  1240. * Examples:
  1241. *
  1242. * $wpdb->prepare(
  1243. * "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
  1244. * array( 'foo', 1337, '%bar' )
  1245. * );
  1246. *
  1247. * $wpdb->prepare(
  1248. * "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s",
  1249. * 'foo'
  1250. * );
  1251. *
  1252. * @since 2.3.0
  1253. * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
  1254. * by updating the function signature. The second parameter was changed
  1255. * from `$args` to `...$args`.
  1256. *
  1257. * @link https://www.php.net/sprintf Description of syntax.
  1258. *
  1259. * @param string $query Query statement with sprintf()-like placeholders.
  1260. * @param array|mixed $args The array of variables to substitute into the query's placeholders
  1261. * if being called with an array of arguments, or the first variable
  1262. * to substitute into the query's placeholders if being called with
  1263. * individual arguments.
  1264. * @param mixed ...$args Further variables to substitute into the query's placeholders
  1265. * if being called with individual arguments.
  1266. * @return string|void Sanitized query string, if there is a query to prepare.
  1267. */
  1268. public function prepare( $query, ...$args ) {
  1269. if ( is_null( $query ) ) {
  1270. return;
  1271. }
  1272. // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
  1273. if ( strpos( $query, '%' ) === false ) {
  1274. wp_load_translations_early();
  1275. _doing_it_wrong(
  1276. 'wpdb::prepare',
  1277. sprintf(
  1278. /* translators: %s: wpdb::prepare() */
  1279. __( 'The query argument of %s must have a placeholder.' ),
  1280. 'wpdb::prepare()'
  1281. ),
  1282. '3.9.0'
  1283. );
  1284. }
  1285. // If args were passed as an array (as in vsprintf), move them up.
  1286. $passed_as_array = false;
  1287. if ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) ) {
  1288. $passed_as_array = true;
  1289. $args = $args[0];
  1290. }
  1291. foreach ( $args as $arg ) {
  1292. if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
  1293. wp_load_translations_early();
  1294. _doing_it_wrong(
  1295. 'wpdb::prepare',
  1296. sprintf(
  1297. /* translators: %s: Value type. */
  1298. __( 'Unsupported value type (%s).' ),
  1299. gettype( $arg )
  1300. ),
  1301. '4.8.2'
  1302. );
  1303. }
  1304. }
  1305. /*
  1306. * Specify the formatting allowed in a placeholder. The following are allowed:
  1307. *
  1308. * - Sign specifier, e.g. $+d
  1309. * - Numbered placeholders, e.g. %1$s
  1310. * - Padding specifier, including custom padding characters, e.g. %05s, %'#5s
  1311. * - Alignment specifier, e.g. %05-s
  1312. * - Precision specifier, e.g. %.2f
  1313. */
  1314. $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
  1315. /*
  1316. * If a %s placeholder already has quotes around it, removing the existing quotes
  1317. * and re-inserting them ensures the quotes are consistent.
  1318. *
  1319. * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s,
  1320. * which are frequently used in the middle of longer strings, or as table name placeholders.
  1321. */
  1322. $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
  1323. $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
  1324. $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
  1325. $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/", '%\\2F', $query ); // Force floats to be locale-unaware.
  1326. $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
  1327. // Count the number of valid placeholders in the query.
  1328. $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
  1329. $args_count = count( $args );
  1330. if ( $args_count !== $placeholders ) {
  1331. if ( 1 === $placeholders && $passed_as_array ) {
  1332. // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
  1333. wp_load_translations_early();
  1334. _doing_it_wrong(
  1335. 'wpdb::prepare',
  1336. __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ),
  1337. '4.9.0'
  1338. );
  1339. return;
  1340. } else {
  1341. /*
  1342. * If we don't have the right number of placeholders,
  1343. * but they were passed as individual arguments,
  1344. * or we were expecting multiple arguments in an array, throw a warning.
  1345. */
  1346. wp_load_translations_early();
  1347. _doing_it_wrong(
  1348. 'wpdb::prepare',
  1349. sprintf(
  1350. /* translators: 1: Number of placeholders, 2: Number of arguments passed. */
  1351. __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
  1352. $placeholders,
  1353. $args_count
  1354. ),
  1355. '4.8.3'
  1356. );
  1357. /*
  1358. * If we don't have enough arguments to match the placeholders,
  1359. * return an empty string to avoid a fatal error on PHP 8.
  1360. */
  1361. if ( $args_count < $placeholders ) {
  1362. $max_numbered_placeholder = ! empty( $matches[3] ) ? max( array_map( 'intval', $matches[3] ) ) : 0;
  1363. if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
  1364. return '';
  1365. }
  1366. }
  1367. }
  1368. }
  1369. array_walk( $args, array( $this, 'escape_by_ref' ) );
  1370. $query = vsprintf( $query, $args );
  1371. return $this->add_placeholder_escape( $query );
  1372. }
  1373. /**
  1374. * First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL.
  1375. *
  1376. * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
  1377. *
  1378. * Example Prepared Statement:
  1379. *
  1380. * $wild = '%';
  1381. * $find = 'only 43% of planets';
  1382. * $like = $wild . $wpdb->esc_like( $find ) . $wild;
  1383. * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
  1384. *
  1385. * Example Escape Chain:
  1386. *
  1387. * $sql = esc_sql( $wpdb->esc_like( $input ) );
  1388. *
  1389. * @since 4.0.0
  1390. *
  1391. * @param string $text The raw text to be escaped. The input typed by the user
  1392. * should have no extra or deleted slashes.
  1393. * @return string Text in the form of a LIKE phrase. The output is not SQL safe.
  1394. * Call wpdb::prepare() or wpdb::_real_escape() next.
  1395. */
  1396. public function esc_like( $text ) {
  1397. return addcslashes( $text, '_%\\' );
  1398. }
  1399. /**
  1400. * Prints SQL/DB error.
  1401. *
  1402. * @since 0.71
  1403. *
  1404. * @global array $EZSQL_ERROR Stores error information of query and error string.
  1405. *
  1406. * @param string $str The error to display.
  1407. * @return void|false Void if the showing of errors is enabled, false if disabled.
  1408. */
  1409. public function print_error( $str = '' ) {
  1410. global $EZSQL_ERROR;
  1411. if ( ! $str ) {
  1412. if ( $this->use_mysqli ) {
  1413. $str = mysqli_error( $this->dbh );
  1414. } else {
  1415. $str = mysql_error( $this->dbh );
  1416. }
  1417. }
  1418. $EZSQL_ERROR[] = array(
  1419. 'query' => $this->last_query,
  1420. 'error_str' => $str,
  1421. );
  1422. if ( $this->suppress_errors ) {
  1423. return false;
  1424. }
  1425. $caller = $this->get_caller();
  1426. if ( $caller ) {
  1427. // Not translated, as this will only appear in the error log.
  1428. $error_str = sprintf( 'WordPress database error %1$s for query %2$s made by %3$s', $str, $this->last_query, $caller );
  1429. } else {
  1430. $error_str = sprintf( 'WordPress database error %1$s for query %2$s', $str, $this->last_query );
  1431. }
  1432. error_log( $error_str );
  1433. // Are we showing errors?
  1434. if ( ! $this->show_errors ) {
  1435. return false;
  1436. }
  1437. wp_load_translations_early();
  1438. // If there is an error then take note of it.
  1439. if ( is_multisite() ) {
  1440. $msg = sprintf(
  1441. "%s [%s]\n%s\n",
  1442. __( 'WordPress database error:' ),
  1443. $str,
  1444. $this->last_query
  1445. );
  1446. if ( defined( 'ERRORLOGFILE' ) ) {
  1447. error_log( $msg, 3, ERRORLOGFILE );
  1448. }
  1449. if ( defined( 'DIEONDBERROR' ) ) {
  1450. wp_die( $msg );
  1451. }
  1452. } else {
  1453. $str = htmlspecialchars( $str, ENT_QUOTES );
  1454. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1455. printf(
  1456. '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
  1457. __( 'WordPress database error:' ),
  1458. $str,
  1459. $query
  1460. );
  1461. }
  1462. }
  1463. /**
  1464. * Enables showing of database errors.
  1465. *
  1466. * This function should be used only to enable showing of errors.
  1467. * wpdb::hide_errors() should be used instead for hiding errors.
  1468. *
  1469. * @since 0.71
  1470. *
  1471. * @see wpdb::hide_errors()
  1472. *
  1473. * @param bool $show Optional. Whether to show errors. Default true.
  1474. * @return bool Whether showing of errors was previously active.
  1475. */
  1476. public function show_errors( $show = true ) {
  1477. $errors = $this->show_errors;
  1478. $this->show_errors = $show;
  1479. return $errors;
  1480. }
  1481. /**
  1482. * Disables showing of database errors.
  1483. *
  1484. * By default database errors are not shown.
  1485. *
  1486. * @since 0.71
  1487. *
  1488. * @see wpdb::show_errors()
  1489. *
  1490. * @return bool Whether showing of errors was previously active.
  1491. */
  1492. public function hide_errors() {
  1493. $show = $this->show_errors;
  1494. $this->show_errors = false;
  1495. return $show;
  1496. }
  1497. /**
  1498. * Enables or disables suppressing of database errors.
  1499. *
  1500. * By default database errors are suppressed.
  1501. *
  1502. * @since 2.5.0
  1503. *
  1504. * @see wpdb::hide_errors()
  1505. *
  1506. * @param bool $suppress Optional. Whether to suppress errors. Default true.
  1507. * @return bool Whether suppressing of errors was previously active.
  1508. */
  1509. public function suppress_errors( $suppress = true ) {
  1510. $errors = $this->suppress_errors;
  1511. $this->suppress_errors = (bool) $suppress;
  1512. return $errors;
  1513. }
  1514. /**
  1515. * Kills cached query results.
  1516. *
  1517. * @since 0.71
  1518. */
  1519. public function flush() {
  1520. $this->last_result = array();
  1521. $this->col_info = null;
  1522. $this->last_query = null;
  1523. $this->rows_affected = 0;
  1524. $this->num_rows = 0;
  1525. $this->last_error = '';
  1526. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1527. mysqli_free_result( $this->result );
  1528. $this->result = null;
  1529. // Sanity check before using the handle.
  1530. if ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) {
  1531. return;
  1532. }
  1533. // Clear out any results from a multi-query.
  1534. while ( mysqli_more_results( $this->dbh ) ) {
  1535. mysqli_next_result( $this->dbh );
  1536. }
  1537. } elseif ( is_resource( $this->result ) ) {
  1538. mysql_free_result( $this->result );
  1539. }
  1540. }
  1541. /**
  1542. * Connects to and selects database.
  1543. *
  1544. * If `$allow_bail` is false, the lack of database connection will need to be handled manually.
  1545. *
  1546. * @since 3.0.0
  1547. * @since 3.9.0 $allow_bail parameter added.
  1548. *
  1549. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1550. * @return bool True with a successful connection, false on failure.
  1551. */
  1552. public function db_connect( $allow_bail = true ) {
  1553. $this->is_mysql = true;
  1554. /*
  1555. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1556. * $new_link parameter exists for mysqli_* functions.
  1557. */
  1558. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1559. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1560. if ( $this->use_mysqli ) {
  1561. /*
  1562. * Set the MySQLi error reporting off because WordPress handles its own.
  1563. * This is due to the default value change from `MYSQLI_REPORT_OFF`
  1564. * to `MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT` in PHP 8.1.
  1565. */
  1566. mysqli_report( MYSQLI_REPORT_OFF );
  1567. $this->dbh = mysqli_init();
  1568. $host = $this->dbhost;
  1569. $port = null;
  1570. $socket = null;
  1571. $is_ipv6 = false;
  1572. $host_data = $this->parse_db_host( $this->dbhost );
  1573. if ( $host_data ) {
  1574. list( $host, $port, $socket, $is_ipv6 ) = $host_data;
  1575. }
  1576. /*
  1577. * If using the `mysqlnd` library, the IPv6 address needs to be enclosed
  1578. * in square brackets, whereas it doesn't while using the `libmysqlclient` library.
  1579. * @see https://bugs.php.net/bug.php?id=67563
  1580. */
  1581. if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
  1582. $host = "[$host]";
  1583. }
  1584. if ( WP_DEBUG ) {
  1585. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1586. } else {
  1587. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1588. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1589. }
  1590. if ( $this->dbh->connect_errno ) {
  1591. $this->dbh = null;
  1592. /*
  1593. * It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1594. * - We haven't previously connected, and
  1595. * - WP_USE_EXT_MYSQL isn't set to false, and
  1596. * - ext/mysql is loaded.
  1597. */
  1598. $attempt_fallback = true;
  1599. if ( $this->has_connected ) {
  1600. $attempt_fallback = false;
  1601. } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
  1602. $attempt_fallback = false;
  1603. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1604. $attempt_fallback = false;
  1605. }
  1606. if ( $attempt_fallback ) {
  1607. $this->use_mysqli = false;
  1608. return $this->db_connect( $allow_bail );
  1609. }
  1610. }
  1611. } else {
  1612. if ( WP_DEBUG ) {
  1613. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1614. } else {
  1615. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1616. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1617. }
  1618. }
  1619. if ( ! $this->dbh && $allow_bail ) {
  1620. wp_load_translations_early();
  1621. // Load custom DB error template, if present.
  1622. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  1623. require_once WP_CONTENT_DIR . '/db-error.php';
  1624. die();
  1625. }
  1626. $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
  1627. $message .= '<p>' . sprintf(
  1628. /* translators: 1: wp-config.php, 2: Database host. */
  1629. __( 'This either means that the username and password information in your %1$s file is incorrect or that contact with the database server at %2$s could not be established. This could mean your host&#8217;s database server is down.' ),
  1630. '<code>wp-config.php</code>',
  1631. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1632. ) . "</p>\n";
  1633. $message .= "<ul>\n";
  1634. $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
  1635. $message .= '<li>' . __( 'Are you sure you have typed the correct hostname?' ) . "</li>\n";
  1636. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1637. $message .= "</ul>\n";
  1638. $message .= '<p>' . sprintf(
  1639. /* translators: %s: Support forums URL. */
  1640. __( 'If you are unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
  1641. __( 'https://wordpress.org/support/forums/' )
  1642. ) . "</p>\n";
  1643. $this->bail( $message, 'db_connect_fail' );
  1644. return false;
  1645. } elseif ( $this->dbh ) {
  1646. if ( ! $this->has_connected ) {
  1647. $this->init_charset();
  1648. }
  1649. $this->has_connected = true;
  1650. $this->set_charset( $this->dbh );
  1651. $this->ready = true;
  1652. $this->set_sql_mode();
  1653. $this->select( $this->dbname, $this->dbh );
  1654. return true;
  1655. }
  1656. return false;
  1657. }
  1658. /**
  1659. * Parses the DB_HOST setting to interpret it for mysqli_real_connect().
  1660. *
  1661. * mysqli_real_connect() doesn't support the host param including a port or socket
  1662. * like mysql_connect() does. This duplicates how mysql_connect() detects a port
  1663. * and/or socket file.
  1664. *
  1665. * @since 4.9.0
  1666. *
  1667. * @param string $host The DB_HOST setting to parse.
  1668. * @return array|false {
  1669. * Array containing the host, the port, the socket and
  1670. * whether it is an IPv6 address, in that order.
  1671. * False if the host couldn't be parsed.
  1672. *
  1673. * @type string $0 Host name.
  1674. * @type string|null $1 Port.
  1675. * @type string|null $2 Socket.
  1676. * @type bool $3 Whether it is an IPv6 address.
  1677. * }
  1678. */
  1679. public function parse_db_host( $host ) {
  1680. $socket = null;
  1681. $is_ipv6 = false;
  1682. // First peel off the socket parameter from the right, if it exists.
  1683. $socket_pos = strpos( $host, ':/' );
  1684. if ( false !== $socket_pos ) {
  1685. $socket = substr( $host, $socket_pos + 1 );
  1686. $host = substr( $host, 0, $socket_pos );
  1687. }
  1688. // We need to check for an IPv6 address first.
  1689. // An IPv6 address will always contain at least two colons.
  1690. if ( substr_count( $host, ':' ) > 1 ) {
  1691. $pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
  1692. $is_ipv6 = true;
  1693. } else {
  1694. // We seem to be dealing with an IPv4 address.
  1695. $pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
  1696. }
  1697. $matches = array();
  1698. $result = preg_match( $pattern, $host, $matches );
  1699. if ( 1 !== $result ) {
  1700. // Couldn't parse the address, bail.
  1701. return false;
  1702. }
  1703. $host = ! empty( $matches['host'] ) ? $matches['host'] : '';
  1704. // MySQLi port cannot be a string; must be null or an integer.
  1705. $port = ! empty( $matches['port'] ) ? absint( $matches['port'] ) : null;
  1706. return array( $host, $port, $socket, $is_ipv6 );
  1707. }
  1708. /**
  1709. * Checks that the connection to the database is still up. If not, try to reconnect.
  1710. *
  1711. * If this function is unable to reconnect, it will forcibly die, or if called
  1712. * after the {@see 'template_redirect'} hook has been fired, return false instead.
  1713. *
  1714. * If `$allow_bail` is false, the lack of database connection will need to be handled manually.
  1715. *
  1716. * @since 3.9.0
  1717. *
  1718. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1719. * @return bool|void True if the connection is up.
  1720. */
  1721. public function check_connection( $allow_bail = true ) {
  1722. if ( $this->use_mysqli ) {
  1723. if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
  1724. return true;
  1725. }
  1726. } else {
  1727. if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
  1728. return true;
  1729. }
  1730. }
  1731. $error_reporting = false;
  1732. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages.
  1733. if ( WP_DEBUG ) {
  1734. $error_reporting = error_reporting();
  1735. error_reporting( $error_reporting & ~E_WARNING );
  1736. }
  1737. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1738. // On the last try, re-enable warnings. We want to see a single instance
  1739. // of the "unable to connect" message on the bail() screen, if it appears.
  1740. if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
  1741. error_reporting( $error_reporting );
  1742. }
  1743. if ( $this->db_connect( false ) ) {
  1744. if ( $error_reporting ) {
  1745. error_reporting( $error_reporting );
  1746. }
  1747. return true;
  1748. }
  1749. sleep( 1 );
  1750. }
  1751. // If template_redirect has already happened, it's too late for wp_die()/dead_db().
  1752. // Let's just return and hope for the best.
  1753. if ( did_action( 'template_redirect' ) ) {
  1754. return false;
  1755. }
  1756. if ( ! $allow_bail ) {
  1757. return false;
  1758. }
  1759. wp_load_translations_early();
  1760. $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
  1761. $message .= '<p>' . sprintf(
  1762. /* translators: %s: Database host. */
  1763. __( 'This means that the contact with the database server at %s was lost. This could mean your host&#8217;s database server is down.' ),
  1764. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1765. ) . "</p>\n";
  1766. $message .= "<ul>\n";
  1767. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1768. $message .= '<li>' . __( 'Are you sure the database server is not under particularly heavy load?' ) . "</li>\n";
  1769. $message .= "</ul>\n";
  1770. $message .= '<p>' . sprintf(
  1771. /* translators: %s: Support forums URL. */
  1772. __( 'If you are unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
  1773. __( 'https://wordpress.org/support/forums/' )
  1774. ) . "</p>\n";
  1775. // We weren't able to reconnect, so we better bail.
  1776. $this->bail( $message, 'db_connect_fail' );
  1777. // Call dead_db() if bail didn't die, because this database is no more.
  1778. // It has ceased to be (at least temporarily).
  1779. dead_db();
  1780. }
  1781. /**
  1782. * Performs a database query, using current database connection.
  1783. *
  1784. * More information can be found on the documentation page.
  1785. *
  1786. * @since 0.71
  1787. *
  1788. * @link https://developer.wordpress.org/reference/classes/wpdb/
  1789. *
  1790. * @param string $query Database query.
  1791. * @return int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows
  1792. * affected/selected for all other queries. Boolean false on error.
  1793. */
  1794. public function query( $query ) {
  1795. if ( ! $this->ready ) {
  1796. $this->check_current_query = true;
  1797. return false;
  1798. }
  1799. /**
  1800. * Filters the database query.
  1801. *
  1802. * Some queries are made before the plugins have been loaded,
  1803. * and thus cannot be filtered with this method.
  1804. *
  1805. * @since 2.1.0
  1806. *
  1807. * @param string $query Database query.
  1808. */
  1809. $query = apply_filters( 'query', $query );
  1810. if ( ! $query ) {
  1811. $this->insert_id = 0;
  1812. return false;
  1813. }
  1814. $this->flush();
  1815. // Log how the function was called.
  1816. $this->func_call = "\$db->query(\"$query\")";
  1817. // If we're writing to the database, make sure the query will write safely.
  1818. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1819. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1820. // strip_invalid_text_from_query() can perform queries, so we need
  1821. // to flush again, just to make sure everything is clear.
  1822. $this->flush();
  1823. if ( $stripped_query !== $query ) {
  1824. $this->insert_id = 0;
  1825. $this->last_query = $query;
  1826. wp_load_translations_early();
  1827. $this->last_error = __( 'WordPress database error: Could not perform query because it contains invalid data.' );
  1828. return false;
  1829. }
  1830. }
  1831. $this->check_current_query = true;
  1832. // Keep track of the last query for debug.
  1833. $this->last_query = $query;
  1834. $this->_do_query( $query );
  1835. // Database server has gone away, try to reconnect.
  1836. $mysql_errno = 0;
  1837. if ( ! empty( $this->dbh ) ) {
  1838. if ( $this->use_mysqli ) {
  1839. if ( $this->dbh instanceof mysqli ) {
  1840. $mysql_errno = mysqli_errno( $this->dbh );
  1841. } else {
  1842. // $dbh is defined, but isn't a real connection.
  1843. // Something has gone horribly wrong, let's try a reconnect.
  1844. $mysql_errno = 2006;
  1845. }
  1846. } else {
  1847. if ( is_resource( $this->dbh ) ) {
  1848. $mysql_errno = mysql_errno( $this->dbh );
  1849. } else {
  1850. $mysql_errno = 2006;
  1851. }
  1852. }
  1853. }
  1854. if ( empty( $this->dbh ) || 2006 === $mysql_errno ) {
  1855. if ( $this->check_connection() ) {
  1856. $this->_do_query( $query );
  1857. } else {
  1858. $this->insert_id = 0;
  1859. return false;
  1860. }
  1861. }
  1862. // If there is an error then take note of it.
  1863. if ( $this->use_mysqli ) {
  1864. if ( $this->dbh instanceof mysqli ) {
  1865. $this->last_error = mysqli_error( $this->dbh );
  1866. } else {
  1867. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1868. }
  1869. } else {
  1870. if ( is_resource( $this->dbh ) ) {
  1871. $this->last_error = mysql_error( $this->dbh );
  1872. } else {
  1873. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1874. }
  1875. }
  1876. if ( $this->last_error ) {
  1877. // Clear insert_id on a subsequent failed insert.
  1878. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1879. $this->insert_id = 0;
  1880. }
  1881. $this->print_error();
  1882. return false;
  1883. }
  1884. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1885. $return_val = $this->result;
  1886. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1887. if ( $this->use_mysqli ) {
  1888. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1889. } else {
  1890. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1891. }
  1892. // Take note of the insert_id.
  1893. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1894. if ( $this->use_mysqli ) {
  1895. $this->insert_id = mysqli_insert_id( $this->dbh );
  1896. } else {
  1897. $this->insert_id = mysql_insert_id( $this->dbh );
  1898. }
  1899. }
  1900. // Return number of rows affected.
  1901. $return_val = $this->rows_affected;
  1902. } else {
  1903. $num_rows = 0;
  1904. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1905. while ( $row = mysqli_fetch_object( $this->result ) ) {
  1906. $this->last_result[ $num_rows ] = $row;
  1907. $num_rows++;
  1908. }
  1909. } elseif ( is_resource( $this->result ) ) {
  1910. while ( $row = mysql_fetch_object( $this->result ) ) {
  1911. $this->last_result[ $num_rows ] = $row;
  1912. $num_rows++;
  1913. }
  1914. }
  1915. // Log and return the number of rows selected.
  1916. $this->num_rows = $num_rows;
  1917. $return_val = $num_rows;
  1918. }
  1919. return $return_val;
  1920. }
  1921. /**
  1922. * Internal function to perform the mysql_query() call.
  1923. *
  1924. * @since 3.9.0
  1925. *
  1926. * @see wpdb::query()
  1927. *
  1928. * @param string $query The query to run.
  1929. */
  1930. private function _do_query( $query ) {
  1931. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1932. $this->timer_start();
  1933. }
  1934. if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
  1935. $this->result = mysqli_query( $this->dbh, $query );
  1936. } elseif ( ! empty( $this->dbh ) ) {
  1937. $this->result = mysql_query( $query, $this->dbh );
  1938. }
  1939. $this->num_queries++;
  1940. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1941. $this->log_query(
  1942. $query,
  1943. $this->timer_stop(),
  1944. $this->get_caller(),
  1945. $this->time_start,
  1946. array()
  1947. );
  1948. }
  1949. }
  1950. /**
  1951. * Logs query data.
  1952. *
  1953. * @since 5.3.0
  1954. *
  1955. * @param string $query The query's SQL.
  1956. * @param float $query_time Total time spent on the query, in seconds.
  1957. * @param string $query_callstack Comma-separated list of the calling functions.
  1958. * @param float $query_start Unix timestamp of the time at the start of the query.
  1959. * @param array $query_data Custom query data.
  1960. */
  1961. public function log_query( $query, $query_time, $query_callstack, $query_start, $query_data ) {
  1962. /**
  1963. * Filters the custom data to log alongside a query.
  1964. *
  1965. * Caution should be used when modifying any of this data, it is recommended that any additional
  1966. * information you need to store about a query be added as a new associative array element.
  1967. *
  1968. * @since 5.3.0
  1969. *
  1970. * @param array $query_data Custom query data.
  1971. * @param string $query The query's SQL.
  1972. * @param float $query_time Total time spent on the query, in seconds.
  1973. * @param string $query_callstack Comma-separated list of the calling functions.
  1974. * @param float $query_start Unix timestamp of the time at the start of the query.
  1975. */
  1976. $query_data = apply_filters( 'log_query_custom_data', $query_data, $query, $query_time, $query_callstack, $query_start );
  1977. $this->queries[] = array(
  1978. $query,
  1979. $query_time,
  1980. $query_callstack,
  1981. $query_start,
  1982. $query_data,
  1983. );
  1984. }
  1985. /**
  1986. * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
  1987. *
  1988. * @since 4.8.3
  1989. *
  1990. * @return string String to escape placeholders.
  1991. */
  1992. public function placeholder_escape() {
  1993. static $placeholder;
  1994. if ( ! $placeholder ) {
  1995. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  1996. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  1997. // Old WP installs may not have AUTH_SALT defined.
  1998. $salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();
  1999. $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
  2000. }
  2001. /*
  2002. * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
  2003. * else attached to this filter will receive the query with the placeholder string removed.
  2004. */
  2005. if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
  2006. add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
  2007. }
  2008. return $placeholder;
  2009. }
  2010. /**
  2011. * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
  2012. *
  2013. * @since 4.8.3
  2014. *
  2015. * @param string $query The query to escape.
  2016. * @return string The query with the placeholder escape string inserted where necessary.
  2017. */
  2018. public function add_placeholder_escape( $query ) {
  2019. /*
  2020. * To prevent returning anything that even vaguely resembles a placeholder,
  2021. * we clobber every % we can find.
  2022. */
  2023. return str_replace( '%', $this->placeholder_escape(), $query );
  2024. }
  2025. /**
  2026. * Removes the placeholder escape strings from a query.
  2027. *
  2028. * @since 4.8.3
  2029. *
  2030. * @param string $query The query from which the placeholder will be removed.
  2031. * @return string The query with the placeholder removed.
  2032. */
  2033. public function remove_placeholder_escape( $query ) {
  2034. return str_replace( $this->placeholder_escape(), '%', $query );
  2035. }
  2036. /**
  2037. * Inserts a row into the table.
  2038. *
  2039. * Examples:
  2040. *
  2041. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  2042. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  2043. *
  2044. * @since 2.5.0
  2045. *
  2046. * @see wpdb::prepare()
  2047. * @see wpdb::$field_types
  2048. * @see wp_set_wpdb_vars()
  2049. *
  2050. * @param string $table Table name.
  2051. * @param array $data Data to insert (in column => value pairs).
  2052. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2053. * Sending a null value will cause the column to be set to NULL - the corresponding
  2054. * format is ignored in this case.
  2055. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2056. * If string, that format will be used for all of the values in $data.
  2057. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2058. * If omitted, all values in $data will be treated as strings unless otherwise
  2059. * specified in wpdb::$field_types.
  2060. * @return int|false The number of rows inserted, or false on error.
  2061. */
  2062. public function insert( $table, $data, $format = null ) {
  2063. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  2064. }
  2065. /**
  2066. * Replaces a row in the table.
  2067. *
  2068. * Examples:
  2069. *
  2070. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  2071. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  2072. *
  2073. * @since 3.0.0
  2074. *
  2075. * @see wpdb::prepare()
  2076. * @see wpdb::$field_types
  2077. * @see wp_set_wpdb_vars()
  2078. *
  2079. * @param string $table Table name.
  2080. * @param array $data Data to insert (in column => value pairs).
  2081. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2082. * Sending a null value will cause the column to be set to NULL - the corresponding
  2083. * format is ignored in this case.
  2084. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2085. * If string, that format will be used for all of the values in $data.
  2086. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2087. * If omitted, all values in $data will be treated as strings unless otherwise
  2088. * specified in wpdb::$field_types.
  2089. * @return int|false The number of rows affected, or false on error.
  2090. */
  2091. public function replace( $table, $data, $format = null ) {
  2092. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  2093. }
  2094. /**
  2095. * Helper function for insert and replace.
  2096. *
  2097. * Runs an insert or replace query based on $type argument.
  2098. *
  2099. * @since 3.0.0
  2100. *
  2101. * @see wpdb::prepare()
  2102. * @see wpdb::$field_types
  2103. * @see wp_set_wpdb_vars()
  2104. *
  2105. * @param string $table Table name.
  2106. * @param array $data Data to insert (in column => value pairs).
  2107. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2108. * Sending a null value will cause the column to be set to NULL - the corresponding
  2109. * format is ignored in this case.
  2110. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2111. * If string, that format will be used for all of the values in $data.
  2112. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2113. * If omitted, all values in $data will be treated as strings unless otherwise
  2114. * specified in wpdb::$field_types.
  2115. * @param string $type Optional. Type of operation. Possible values include 'INSERT' or 'REPLACE'.
  2116. * Default 'INSERT'.
  2117. * @return int|false The number of rows affected, or false on error.
  2118. */
  2119. public function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  2120. $this->insert_id = 0;
  2121. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ), true ) ) {
  2122. return false;
  2123. }
  2124. $data = $this->process_fields( $table, $data, $format );
  2125. if ( false === $data ) {
  2126. return false;
  2127. }
  2128. $formats = array();
  2129. $values = array();
  2130. foreach ( $data as $value ) {
  2131. if ( is_null( $value['value'] ) ) {
  2132. $formats[] = 'NULL';
  2133. continue;
  2134. }
  2135. $formats[] = $value['format'];
  2136. $values[] = $value['value'];
  2137. }
  2138. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  2139. $formats = implode( ', ', $formats );
  2140. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  2141. $this->check_current_query = false;
  2142. return $this->query( $this->prepare( $sql, $values ) );
  2143. }
  2144. /**
  2145. * Updates a row in the table.
  2146. *
  2147. * Examples:
  2148. *
  2149. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  2150. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  2151. *
  2152. * @since 2.5.0
  2153. *
  2154. * @see wpdb::prepare()
  2155. * @see wpdb::$field_types
  2156. * @see wp_set_wpdb_vars()
  2157. *
  2158. * @param string $table Table name.
  2159. * @param array $data Data to update (in column => value pairs).
  2160. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2161. * Sending a null value will cause the column to be set to NULL - the corresponding
  2162. * format is ignored in this case.
  2163. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2164. * Multiple clauses will be joined with ANDs.
  2165. * Both $where columns and $where values should be "raw".
  2166. * Sending a null value will create an IS NULL comparison - the corresponding
  2167. * format will be ignored in this case.
  2168. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
  2169. * If string, that format will be used for all of the values in $data.
  2170. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2171. * If omitted, all values in $data will be treated as strings unless otherwise
  2172. * specified in wpdb::$field_types.
  2173. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2174. * If string, that format will be used for all of the items in $where.
  2175. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2176. * If omitted, all values in $where will be treated as strings.
  2177. * @return int|false The number of rows updated, or false on error.
  2178. */
  2179. public function update( $table, $data, $where, $format = null, $where_format = null ) {
  2180. if ( ! is_array( $data ) || ! is_array( $where ) ) {
  2181. return false;
  2182. }
  2183. $data = $this->process_fields( $table, $data, $format );
  2184. if ( false === $data ) {
  2185. return false;
  2186. }
  2187. $where = $this->process_fields( $table, $where, $where_format );
  2188. if ( false === $where ) {
  2189. return false;
  2190. }
  2191. $fields = array();
  2192. $conditions = array();
  2193. $values = array();
  2194. foreach ( $data as $field => $value ) {
  2195. if ( is_null( $value['value'] ) ) {
  2196. $fields[] = "`$field` = NULL";
  2197. continue;
  2198. }
  2199. $fields[] = "`$field` = " . $value['format'];
  2200. $values[] = $value['value'];
  2201. }
  2202. foreach ( $where as $field => $value ) {
  2203. if ( is_null( $value['value'] ) ) {
  2204. $conditions[] = "`$field` IS NULL";
  2205. continue;
  2206. }
  2207. $conditions[] = "`$field` = " . $value['format'];
  2208. $values[] = $value['value'];
  2209. }
  2210. $fields = implode( ', ', $fields );
  2211. $conditions = implode( ' AND ', $conditions );
  2212. $sql = "UPDATE `$table` SET $fields WHERE $conditions";
  2213. $this->check_current_query = false;
  2214. return $this->query( $this->prepare( $sql, $values ) );
  2215. }
  2216. /**
  2217. * Deletes a row in the table.
  2218. *
  2219. * Examples:
  2220. *
  2221. * wpdb::delete( 'table', array( 'ID' => 1 ) )
  2222. * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
  2223. *
  2224. * @since 3.4.0
  2225. *
  2226. * @see wpdb::prepare()
  2227. * @see wpdb::$field_types
  2228. * @see wp_set_wpdb_vars()
  2229. *
  2230. * @param string $table Table name.
  2231. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2232. * Multiple clauses will be joined with ANDs.
  2233. * Both $where columns and $where values should be "raw".
  2234. * Sending a null value will create an IS NULL comparison - the corresponding
  2235. * format will be ignored in this case.
  2236. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2237. * If string, that format will be used for all of the items in $where.
  2238. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2239. * If omitted, all values in $data will be treated as strings unless otherwise
  2240. * specified in wpdb::$field_types.
  2241. * @return int|false The number of rows deleted, or false on error.
  2242. */
  2243. public function delete( $table, $where, $where_format = null ) {
  2244. if ( ! is_array( $where ) ) {
  2245. return false;
  2246. }
  2247. $where = $this->process_fields( $table, $where, $where_format );
  2248. if ( false === $where ) {
  2249. return false;
  2250. }
  2251. $conditions = array();
  2252. $values = array();
  2253. foreach ( $where as $field => $value ) {
  2254. if ( is_null( $value['value'] ) ) {
  2255. $conditions[] = "`$field` IS NULL";
  2256. continue;
  2257. }
  2258. $conditions[] = "`$field` = " . $value['format'];
  2259. $values[] = $value['value'];
  2260. }
  2261. $conditions = implode( ' AND ', $conditions );
  2262. $sql = "DELETE FROM `$table` WHERE $conditions";
  2263. $this->check_current_query = false;
  2264. return $this->query( $this->prepare( $sql, $values ) );
  2265. }
  2266. /**
  2267. * Processes arrays of field/value pairs and field formats.
  2268. *
  2269. * This is a helper method for wpdb's CRUD methods, which take field/value pairs
  2270. * for inserts, updates, and where clauses. This method first pairs each value
  2271. * with a format. Then it determines the charset of that field, using that
  2272. * to determine if any invalid text would be stripped. If text is stripped,
  2273. * then field processing is rejected and the query fails.
  2274. *
  2275. * @since 4.2.0
  2276. *
  2277. * @param string $table Table name.
  2278. * @param array $data Field/value pair.
  2279. * @param mixed $format Format for each field.
  2280. * @return array|false An array of fields that contain paired value and formats.
  2281. * False for invalid values.
  2282. */
  2283. protected function process_fields( $table, $data, $format ) {
  2284. $data = $this->process_field_formats( $data, $format );
  2285. if ( false === $data ) {
  2286. return false;
  2287. }
  2288. $data = $this->process_field_charsets( $data, $table );
  2289. if ( false === $data ) {
  2290. return false;
  2291. }
  2292. $data = $this->process_field_lengths( $data, $table );
  2293. if ( false === $data ) {
  2294. return false;
  2295. }
  2296. $converted_data = $this->strip_invalid_text( $data );
  2297. if ( $data !== $converted_data ) {
  2298. $problem_fields = array();
  2299. foreach ( $data as $field => $value ) {
  2300. if ( $value !== $converted_data[ $field ] ) {
  2301. $problem_fields[] = $field;
  2302. }
  2303. }
  2304. wp_load_translations_early();
  2305. if ( 1 === count( $problem_fields ) ) {
  2306. $this->last_error = sprintf(
  2307. /* translators: %s: Database field where the error occurred. */
  2308. __( 'WordPress database error: Processing the value for the following field failed: %s. The supplied value may be too long or contains invalid data.' ),
  2309. reset( $problem_fields )
  2310. );
  2311. } else {
  2312. $this->last_error = sprintf(
  2313. /* translators: %s: Database fields where the error occurred. */
  2314. __( 'WordPress database error: Processing the values for the following fields failed: %s. The supplied values may be too long or contain invalid data.' ),
  2315. implode( ', ', $problem_fields )
  2316. );
  2317. }
  2318. return false;
  2319. }
  2320. return $data;
  2321. }
  2322. /**
  2323. * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
  2324. *
  2325. * @since 4.2.0
  2326. *
  2327. * @param array $data Array of fields to values.
  2328. * @param mixed $format Formats to be mapped to the values in $data.
  2329. * @return array Array, keyed by field names with values being an array
  2330. * of 'value' and 'format' keys.
  2331. */
  2332. protected function process_field_formats( $data, $format ) {
  2333. $formats = (array) $format;
  2334. $original_formats = $formats;
  2335. foreach ( $data as $field => $value ) {
  2336. $value = array(
  2337. 'value' => $value,
  2338. 'format' => '%s',
  2339. );
  2340. if ( ! empty( $format ) ) {
  2341. $value['format'] = array_shift( $formats );
  2342. if ( ! $value['format'] ) {
  2343. $value['format'] = reset( $original_formats );
  2344. }
  2345. } elseif ( isset( $this->field_types[ $field ] ) ) {
  2346. $value['format'] = $this->field_types[ $field ];
  2347. }
  2348. $data[ $field ] = $value;
  2349. }
  2350. return $data;
  2351. }
  2352. /**
  2353. * Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats().
  2354. *
  2355. * @since 4.2.0
  2356. *
  2357. * @param array $data As it comes from the wpdb::process_field_formats() method.
  2358. * @param string $table Table name.
  2359. * @return array|false The same array as $data with additional 'charset' keys.
  2360. * False on failure.
  2361. */
  2362. protected function process_field_charsets( $data, $table ) {
  2363. foreach ( $data as $field => $value ) {
  2364. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2365. /*
  2366. * We can skip this field if we know it isn't a string.
  2367. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2368. */
  2369. $value['charset'] = false;
  2370. } else {
  2371. $value['charset'] = $this->get_col_charset( $table, $field );
  2372. if ( is_wp_error( $value['charset'] ) ) {
  2373. return false;
  2374. }
  2375. }
  2376. $data[ $field ] = $value;
  2377. }
  2378. return $data;
  2379. }
  2380. /**
  2381. * For string fields, records the maximum string length that field can safely save.
  2382. *
  2383. * @since 4.2.1
  2384. *
  2385. * @param array $data As it comes from the wpdb::process_field_charsets() method.
  2386. * @param string $table Table name.
  2387. * @return array|false The same array as $data with additional 'length' keys, or false if
  2388. * any of the values were too long for their corresponding field.
  2389. */
  2390. protected function process_field_lengths( $data, $table ) {
  2391. foreach ( $data as $field => $value ) {
  2392. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2393. /*
  2394. * We can skip this field if we know it isn't a string.
  2395. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2396. */
  2397. $value['length'] = false;
  2398. } else {
  2399. $value['length'] = $this->get_col_length( $table, $field );
  2400. if ( is_wp_error( $value['length'] ) ) {
  2401. return false;
  2402. }
  2403. }
  2404. $data[ $field ] = $value;
  2405. }
  2406. return $data;
  2407. }
  2408. /**
  2409. * Retrieves one variable from the database.
  2410. *
  2411. * Executes a SQL query and returns the value from the SQL result.
  2412. * If the SQL result contains more than one column and/or more than one row,
  2413. * the value in the column and row specified is returned. If $query is null,
  2414. * the value in the specified column and row from the previous SQL result is returned.
  2415. *
  2416. * @since 0.71
  2417. *
  2418. * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
  2419. * @param int $x Optional. Column of value to return. Indexed from 0.
  2420. * @param int $y Optional. Row of value to return. Indexed from 0.
  2421. * @return string|null Database query result (as string), or null on failure.
  2422. */
  2423. public function get_var( $query = null, $x = 0, $y = 0 ) {
  2424. $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
  2425. if ( $query ) {
  2426. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2427. $this->check_current_query = false;
  2428. }
  2429. $this->query( $query );
  2430. }
  2431. // Extract var out of cached results based on x,y vals.
  2432. if ( ! empty( $this->last_result[ $y ] ) ) {
  2433. $values = array_values( get_object_vars( $this->last_result[ $y ] ) );
  2434. }
  2435. // If there is a value return it, else return null.
  2436. return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null;
  2437. }
  2438. /**
  2439. * Retrieves one row from the database.
  2440. *
  2441. * Executes a SQL query and returns the row from the SQL result.
  2442. *
  2443. * @since 0.71
  2444. *
  2445. * @param string|null $query SQL query.
  2446. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  2447. * correspond to an stdClass object, an associative array, or a numeric array,
  2448. * respectively. Default OBJECT.
  2449. * @param int $y Optional. Row to return. Indexed from 0.
  2450. * @return array|object|null|void Database query result in format specified by $output or null on failure.
  2451. */
  2452. public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
  2453. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  2454. if ( $query ) {
  2455. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2456. $this->check_current_query = false;
  2457. }
  2458. $this->query( $query );
  2459. } else {
  2460. return null;
  2461. }
  2462. if ( ! isset( $this->last_result[ $y ] ) ) {
  2463. return null;
  2464. }
  2465. if ( OBJECT === $output ) {
  2466. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2467. } elseif ( ARRAY_A === $output ) {
  2468. return $this->last_result[ $y ] ? get_object_vars( $this->last_result[ $y ] ) : null;
  2469. } elseif ( ARRAY_N === $output ) {
  2470. return $this->last_result[ $y ] ? array_values( get_object_vars( $this->last_result[ $y ] ) ) : null;
  2471. } elseif ( OBJECT === strtoupper( $output ) ) {
  2472. // Back compat for OBJECT being previously case-insensitive.
  2473. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2474. } else {
  2475. $this->print_error( ' $db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N' );
  2476. }
  2477. }
  2478. /**
  2479. * Retrieves one column from the database.
  2480. *
  2481. * Executes a SQL query and returns the column from the SQL result.
  2482. * If the SQL result contains more than one column, the column specified is returned.
  2483. * If $query is null, the specified column from the previous SQL result is returned.
  2484. *
  2485. * @since 0.71
  2486. *
  2487. * @param string|null $query Optional. SQL query. Defaults to previous query.
  2488. * @param int $x Optional. Column to return. Indexed from 0.
  2489. * @return array Database query result. Array indexed from 0 by SQL result row number.
  2490. */
  2491. public function get_col( $query = null, $x = 0 ) {
  2492. if ( $query ) {
  2493. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2494. $this->check_current_query = false;
  2495. }
  2496. $this->query( $query );
  2497. }
  2498. $new_array = array();
  2499. // Extract the column values.
  2500. if ( $this->last_result ) {
  2501. for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
  2502. $new_array[ $i ] = $this->get_var( null, $x, $i );
  2503. }
  2504. }
  2505. return $new_array;
  2506. }
  2507. /**
  2508. * Retrieves an entire SQL result set from the database (i.e., many rows).
  2509. *
  2510. * Executes a SQL query and returns the entire SQL result.
  2511. *
  2512. * @since 0.71
  2513. *
  2514. * @param string $query SQL query.
  2515. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
  2516. * With one of the first three, return an array of rows indexed
  2517. * from 0 by SQL result row number. Each row is an associative array
  2518. * (column => value, ...), a numerically indexed array (0 => value, ...),
  2519. * or an object ( ->column = value ), respectively. With OBJECT_K,
  2520. * return an associative array of row objects keyed by the value
  2521. * of each row's first column's value. Duplicate keys are discarded.
  2522. * @return array|object|null Database query results.
  2523. */
  2524. public function get_results( $query = null, $output = OBJECT ) {
  2525. $this->func_call = "\$db->get_results(\"$query\", $output)";
  2526. if ( $query ) {
  2527. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2528. $this->check_current_query = false;
  2529. }
  2530. $this->query( $query );
  2531. } else {
  2532. return null;
  2533. }
  2534. $new_array = array();
  2535. if ( OBJECT === $output ) {
  2536. // Return an integer-keyed array of row objects.
  2537. return $this->last_result;
  2538. } elseif ( OBJECT_K === $output ) {
  2539. // Return an array of row objects with keys from column 1.
  2540. // (Duplicates are discarded.)
  2541. if ( $this->last_result ) {
  2542. foreach ( $this->last_result as $row ) {
  2543. $var_by_ref = get_object_vars( $row );
  2544. $key = array_shift( $var_by_ref );
  2545. if ( ! isset( $new_array[ $key ] ) ) {
  2546. $new_array[ $key ] = $row;
  2547. }
  2548. }
  2549. }
  2550. return $new_array;
  2551. } elseif ( ARRAY_A === $output || ARRAY_N === $output ) {
  2552. // Return an integer-keyed array of...
  2553. if ( $this->last_result ) {
  2554. foreach ( (array) $this->last_result as $row ) {
  2555. if ( ARRAY_N === $output ) {
  2556. // ...integer-keyed row arrays.
  2557. $new_array[] = array_values( get_object_vars( $row ) );
  2558. } else {
  2559. // ...column name-keyed row arrays.
  2560. $new_array[] = get_object_vars( $row );
  2561. }
  2562. }
  2563. }
  2564. return $new_array;
  2565. } elseif ( strtoupper( $output ) === OBJECT ) {
  2566. // Back compat for OBJECT being previously case-insensitive.
  2567. return $this->last_result;
  2568. }
  2569. return null;
  2570. }
  2571. /**
  2572. * Retrieves the character set for the given table.
  2573. *
  2574. * @since 4.2.0
  2575. *
  2576. * @param string $table Table name.
  2577. * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
  2578. */
  2579. protected function get_table_charset( $table ) {
  2580. $tablekey = strtolower( $table );
  2581. /**
  2582. * Filters the table charset value before the DB is checked.
  2583. *
  2584. * Returning a non-null value from the filter will effectively short-circuit
  2585. * checking the DB for the charset, returning that value instead.
  2586. *
  2587. * @since 4.2.0
  2588. *
  2589. * @param string|WP_Error|null $charset The character set to use, WP_Error object
  2590. * if it couldn't be found. Default null.
  2591. * @param string $table The name of the table being checked.
  2592. */
  2593. $charset = apply_filters( 'pre_get_table_charset', null, $table );
  2594. if ( null !== $charset ) {
  2595. return $charset;
  2596. }
  2597. if ( isset( $this->table_charset[ $tablekey ] ) ) {
  2598. return $this->table_charset[ $tablekey ];
  2599. }
  2600. $charsets = array();
  2601. $columns = array();
  2602. $table_parts = explode( '.', $table );
  2603. $table = '`' . implode( '`.`', $table_parts ) . '`';
  2604. $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
  2605. if ( ! $results ) {
  2606. return new WP_Error( 'wpdb_get_table_charset_failure', __( 'Could not retrieve table charset.' ) );
  2607. }
  2608. foreach ( $results as $column ) {
  2609. $columns[ strtolower( $column->Field ) ] = $column;
  2610. }
  2611. $this->col_meta[ $tablekey ] = $columns;
  2612. foreach ( $columns as $column ) {
  2613. if ( ! empty( $column->Collation ) ) {
  2614. list( $charset ) = explode( '_', $column->Collation );
  2615. // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
  2616. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  2617. $charset = 'utf8';
  2618. }
  2619. $charsets[ strtolower( $charset ) ] = true;
  2620. }
  2621. list( $type ) = explode( '(', $column->Type );
  2622. // A binary/blob means the whole query gets treated like this.
  2623. if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ), true ) ) {
  2624. $this->table_charset[ $tablekey ] = 'binary';
  2625. return 'binary';
  2626. }
  2627. }
  2628. // utf8mb3 is an alias for utf8.
  2629. if ( isset( $charsets['utf8mb3'] ) ) {
  2630. $charsets['utf8'] = true;
  2631. unset( $charsets['utf8mb3'] );
  2632. }
  2633. // Check if we have more than one charset in play.
  2634. $count = count( $charsets );
  2635. if ( 1 === $count ) {
  2636. $charset = key( $charsets );
  2637. } elseif ( 0 === $count ) {
  2638. // No charsets, assume this table can store whatever.
  2639. $charset = false;
  2640. } else {
  2641. // More than one charset. Remove latin1 if present and recalculate.
  2642. unset( $charsets['latin1'] );
  2643. $count = count( $charsets );
  2644. if ( 1 === $count ) {
  2645. // Only one charset (besides latin1).
  2646. $charset = key( $charsets );
  2647. } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
  2648. // Two charsets, but they're utf8 and utf8mb4, use utf8.
  2649. $charset = 'utf8';
  2650. } else {
  2651. // Two mixed character sets. ascii.
  2652. $charset = 'ascii';
  2653. }
  2654. }
  2655. $this->table_charset[ $tablekey ] = $charset;
  2656. return $charset;
  2657. }
  2658. /**
  2659. * Retrieves the character set for the given column.
  2660. *
  2661. * @since 4.2.0
  2662. *
  2663. * @param string $table Table name.
  2664. * @param string $column Column name.
  2665. * @return string|false|WP_Error Column character set as a string. False if the column has
  2666. * no character set. WP_Error object if there was an error.
  2667. */
  2668. public function get_col_charset( $table, $column ) {
  2669. $tablekey = strtolower( $table );
  2670. $columnkey = strtolower( $column );
  2671. /**
  2672. * Filters the column charset value before the DB is checked.
  2673. *
  2674. * Passing a non-null value to the filter will short-circuit
  2675. * checking the DB for the charset, returning that value instead.
  2676. *
  2677. * @since 4.2.0
  2678. *
  2679. * @param string|null $charset The character set to use. Default null.
  2680. * @param string $table The name of the table being checked.
  2681. * @param string $column The name of the column being checked.
  2682. */
  2683. $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
  2684. if ( null !== $charset ) {
  2685. return $charset;
  2686. }
  2687. // Skip this entirely if this isn't a MySQL database.
  2688. if ( empty( $this->is_mysql ) ) {
  2689. return false;
  2690. }
  2691. if ( empty( $this->table_charset[ $tablekey ] ) ) {
  2692. // This primes column information for us.
  2693. $table_charset = $this->get_table_charset( $table );
  2694. if ( is_wp_error( $table_charset ) ) {
  2695. return $table_charset;
  2696. }
  2697. }
  2698. // If still no column information, return the table charset.
  2699. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2700. return $this->table_charset[ $tablekey ];
  2701. }
  2702. // If this column doesn't exist, return the table charset.
  2703. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2704. return $this->table_charset[ $tablekey ];
  2705. }
  2706. // Return false when it's not a string column.
  2707. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
  2708. return false;
  2709. }
  2710. list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
  2711. return $charset;
  2712. }
  2713. /**
  2714. * Retrieves the maximum string length allowed in a given column.
  2715. *
  2716. * The length may either be specified as a byte length or a character length.
  2717. *
  2718. * @since 4.2.1
  2719. *
  2720. * @param string $table Table name.
  2721. * @param string $column Column name.
  2722. * @return array|false|WP_Error {
  2723. * Array of column length information, false if the column has no length (for
  2724. * example, numeric column), WP_Error object if there was an error.
  2725. *
  2726. * @type int $length The column length.
  2727. * @type string $type One of 'byte' or 'char'.
  2728. */
  2729. public function get_col_length( $table, $column ) {
  2730. $tablekey = strtolower( $table );
  2731. $columnkey = strtolower( $column );
  2732. // Skip this entirely if this isn't a MySQL database.
  2733. if ( empty( $this->is_mysql ) ) {
  2734. return false;
  2735. }
  2736. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2737. // This primes column information for us.
  2738. $table_charset = $this->get_table_charset( $table );
  2739. if ( is_wp_error( $table_charset ) ) {
  2740. return $table_charset;
  2741. }
  2742. }
  2743. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2744. return false;
  2745. }
  2746. $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
  2747. $type = strtolower( $typeinfo[0] );
  2748. if ( ! empty( $typeinfo[1] ) ) {
  2749. $length = trim( $typeinfo[1], ')' );
  2750. } else {
  2751. $length = false;
  2752. }
  2753. switch ( $type ) {
  2754. case 'char':
  2755. case 'varchar':
  2756. return array(
  2757. 'type' => 'char',
  2758. 'length' => (int) $length,
  2759. );
  2760. case 'binary':
  2761. case 'varbinary':
  2762. return array(
  2763. 'type' => 'byte',
  2764. 'length' => (int) $length,
  2765. );
  2766. case 'tinyblob':
  2767. case 'tinytext':
  2768. return array(
  2769. 'type' => 'byte',
  2770. 'length' => 255, // 2^8 - 1
  2771. );
  2772. case 'blob':
  2773. case 'text':
  2774. return array(
  2775. 'type' => 'byte',
  2776. 'length' => 65535, // 2^16 - 1
  2777. );
  2778. case 'mediumblob':
  2779. case 'mediumtext':
  2780. return array(
  2781. 'type' => 'byte',
  2782. 'length' => 16777215, // 2^24 - 1
  2783. );
  2784. case 'longblob':
  2785. case 'longtext':
  2786. return array(
  2787. 'type' => 'byte',
  2788. 'length' => 4294967295, // 2^32 - 1
  2789. );
  2790. default:
  2791. return false;
  2792. }
  2793. }
  2794. /**
  2795. * Checks if a string is ASCII.
  2796. *
  2797. * The negative regex is faster for non-ASCII strings, as it allows
  2798. * the search to finish as soon as it encounters a non-ASCII character.
  2799. *
  2800. * @since 4.2.0
  2801. *
  2802. * @param string $string String to check.
  2803. * @return bool True if ASCII, false if not.
  2804. */
  2805. protected function check_ascii( $string ) {
  2806. if ( function_exists( 'mb_check_encoding' ) ) {
  2807. if ( mb_check_encoding( $string, 'ASCII' ) ) {
  2808. return true;
  2809. }
  2810. } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
  2811. return true;
  2812. }
  2813. return false;
  2814. }
  2815. /**
  2816. * Checks if the query is accessing a collation considered safe on the current version of MySQL.
  2817. *
  2818. * @since 4.2.0
  2819. *
  2820. * @param string $query The query to check.
  2821. * @return bool True if the collation is safe, false if it isn't.
  2822. */
  2823. protected function check_safe_collation( $query ) {
  2824. if ( $this->checking_collation ) {
  2825. return true;
  2826. }
  2827. // We don't need to check the collation for queries that don't read data.
  2828. $query = ltrim( $query, "\r\n\t (" );
  2829. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
  2830. return true;
  2831. }
  2832. // All-ASCII queries don't need extra checking.
  2833. if ( $this->check_ascii( $query ) ) {
  2834. return true;
  2835. }
  2836. $table = $this->get_table_from_query( $query );
  2837. if ( ! $table ) {
  2838. return false;
  2839. }
  2840. $this->checking_collation = true;
  2841. $collation = $this->get_table_charset( $table );
  2842. $this->checking_collation = false;
  2843. // Tables with no collation, or latin1 only, don't need extra checking.
  2844. if ( false === $collation || 'latin1' === $collation ) {
  2845. return true;
  2846. }
  2847. $table = strtolower( $table );
  2848. if ( empty( $this->col_meta[ $table ] ) ) {
  2849. return false;
  2850. }
  2851. // If any of the columns don't have one of these collations, it needs more sanity checking.
  2852. $safe_collations = array(
  2853. 'utf8_bin',
  2854. 'utf8_general_ci',
  2855. 'utf8mb3_bin',
  2856. 'utf8mb3_general_ci',
  2857. 'utf8mb4_bin',
  2858. 'utf8mb4_general_ci',
  2859. );
  2860. foreach ( $this->col_meta[ $table ] as $col ) {
  2861. if ( empty( $col->Collation ) ) {
  2862. continue;
  2863. }
  2864. if ( ! in_array( $col->Collation, $safe_collations, true ) ) {
  2865. return false;
  2866. }
  2867. }
  2868. return true;
  2869. }
  2870. /**
  2871. * Strips any invalid characters based on value/charset pairs.
  2872. *
  2873. * @since 4.2.0
  2874. *
  2875. * @param array $data Array of value arrays. Each value array has the keys 'value' and 'charset'.
  2876. * An optional 'ascii' key can be set to false to avoid redundant ASCII checks.
  2877. * @return array|WP_Error The $data parameter, with invalid characters removed from each value.
  2878. * This works as a passthrough: any additional keys such as 'field' are
  2879. * retained in each value array. If we cannot remove invalid characters,
  2880. * a WP_Error object is returned.
  2881. */
  2882. protected function strip_invalid_text( $data ) {
  2883. $db_check_string = false;
  2884. foreach ( $data as &$value ) {
  2885. $charset = $value['charset'];
  2886. if ( is_array( $value['length'] ) ) {
  2887. $length = $value['length']['length'];
  2888. $truncate_by_byte_length = 'byte' === $value['length']['type'];
  2889. } else {
  2890. $length = false;
  2891. // Since we have no length, we'll never truncate. Initialize the variable to false.
  2892. // True would take us through an unnecessary (for this case) codepath below.
  2893. $truncate_by_byte_length = false;
  2894. }
  2895. // There's no charset to work with.
  2896. if ( false === $charset ) {
  2897. continue;
  2898. }
  2899. // Column isn't a string.
  2900. if ( ! is_string( $value['value'] ) ) {
  2901. continue;
  2902. }
  2903. $needs_validation = true;
  2904. if (
  2905. // latin1 can store any byte sequence.
  2906. 'latin1' === $charset
  2907. ||
  2908. // ASCII is always OK.
  2909. ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
  2910. ) {
  2911. $truncate_by_byte_length = true;
  2912. $needs_validation = false;
  2913. }
  2914. if ( $truncate_by_byte_length ) {
  2915. mbstring_binary_safe_encoding();
  2916. if ( false !== $length && strlen( $value['value'] ) > $length ) {
  2917. $value['value'] = substr( $value['value'], 0, $length );
  2918. }
  2919. reset_mbstring_encoding();
  2920. if ( ! $needs_validation ) {
  2921. continue;
  2922. }
  2923. }
  2924. // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
  2925. if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
  2926. $regex = '/
  2927. (
  2928. (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
  2929. | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  2930. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  2931. | [\xE1-\xEC][\x80-\xBF]{2}
  2932. | \xED[\x80-\x9F][\x80-\xBF]
  2933. | [\xEE-\xEF][\x80-\xBF]{2}';
  2934. if ( 'utf8mb4' === $charset ) {
  2935. $regex .= '
  2936. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  2937. | [\xF1-\xF3][\x80-\xBF]{3}
  2938. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  2939. ';
  2940. }
  2941. $regex .= '){1,40} # ...one or more times
  2942. )
  2943. | . # anything else
  2944. /x';
  2945. $value['value'] = preg_replace( $regex, '$1', $value['value'] );
  2946. if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
  2947. $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
  2948. }
  2949. continue;
  2950. }
  2951. // We couldn't use any local conversions, send it to the DB.
  2952. $value['db'] = true;
  2953. $db_check_string = true;
  2954. }
  2955. unset( $value ); // Remove by reference.
  2956. if ( $db_check_string ) {
  2957. $queries = array();
  2958. foreach ( $data as $col => $value ) {
  2959. if ( ! empty( $value['db'] ) ) {
  2960. // We're going to need to truncate by characters or bytes, depending on the length value we have.
  2961. if ( isset( $value['length']['type'] ) && 'byte' === $value['length']['type'] ) {
  2962. // Using binary causes LEFT() to truncate by bytes.
  2963. $charset = 'binary';
  2964. } else {
  2965. $charset = $value['charset'];
  2966. }
  2967. if ( $this->charset ) {
  2968. $connection_charset = $this->charset;
  2969. } else {
  2970. if ( $this->use_mysqli ) {
  2971. $connection_charset = mysqli_character_set_name( $this->dbh );
  2972. } else {
  2973. $connection_charset = mysql_client_encoding();
  2974. }
  2975. }
  2976. if ( is_array( $value['length'] ) ) {
  2977. $length = sprintf( '%.0f', $value['length']['length'] );
  2978. $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), $length ) USING $connection_charset )", $value['value'] );
  2979. } elseif ( 'binary' !== $charset ) {
  2980. // If we don't have a length, there's no need to convert binary - it will always return the same result.
  2981. $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
  2982. }
  2983. unset( $data[ $col ]['db'] );
  2984. }
  2985. }
  2986. $sql = array();
  2987. foreach ( $queries as $column => $query ) {
  2988. if ( ! $query ) {
  2989. continue;
  2990. }
  2991. $sql[] = $query . " AS x_$column";
  2992. }
  2993. $this->check_current_query = false;
  2994. $row = $this->get_row( 'SELECT ' . implode( ', ', $sql ), ARRAY_A );
  2995. if ( ! $row ) {
  2996. return new WP_Error( 'wpdb_strip_invalid_text_failure', __( 'Could not strip invalid text.' ) );
  2997. }
  2998. foreach ( array_keys( $data ) as $column ) {
  2999. if ( isset( $row[ "x_$column" ] ) ) {
  3000. $data[ $column ]['value'] = $row[ "x_$column" ];
  3001. }
  3002. }
  3003. }
  3004. return $data;
  3005. }
  3006. /**
  3007. * Strips any invalid characters from the query.
  3008. *
  3009. * @since 4.2.0
  3010. *
  3011. * @param string $query Query to convert.
  3012. * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
  3013. */
  3014. protected function strip_invalid_text_from_query( $query ) {
  3015. // We don't need to check the collation for queries that don't read data.
  3016. $trimmed_query = ltrim( $query, "\r\n\t (" );
  3017. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
  3018. return $query;
  3019. }
  3020. $table = $this->get_table_from_query( $query );
  3021. if ( $table ) {
  3022. $charset = $this->get_table_charset( $table );
  3023. if ( is_wp_error( $charset ) ) {
  3024. return $charset;
  3025. }
  3026. // We can't reliably strip text from tables containing binary/blob columns.
  3027. if ( 'binary' === $charset ) {
  3028. return $query;
  3029. }
  3030. } else {
  3031. $charset = $this->charset;
  3032. }
  3033. $data = array(
  3034. 'value' => $query,
  3035. 'charset' => $charset,
  3036. 'ascii' => false,
  3037. 'length' => false,
  3038. );
  3039. $data = $this->strip_invalid_text( array( $data ) );
  3040. if ( is_wp_error( $data ) ) {
  3041. return $data;
  3042. }
  3043. return $data[0]['value'];
  3044. }
  3045. /**
  3046. * Strips any invalid characters from the string for a given table and column.
  3047. *
  3048. * @since 4.2.0
  3049. *
  3050. * @param string $table Table name.
  3051. * @param string $column Column name.
  3052. * @param string $value The text to check.
  3053. * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
  3054. */
  3055. public function strip_invalid_text_for_column( $table, $column, $value ) {
  3056. if ( ! is_string( $value ) ) {
  3057. return $value;
  3058. }
  3059. $charset = $this->get_col_charset( $table, $column );
  3060. if ( ! $charset ) {
  3061. // Not a string column.
  3062. return $value;
  3063. } elseif ( is_wp_error( $charset ) ) {
  3064. // Bail on real errors.
  3065. return $charset;
  3066. }
  3067. $data = array(
  3068. $column => array(
  3069. 'value' => $value,
  3070. 'charset' => $charset,
  3071. 'length' => $this->get_col_length( $table, $column ),
  3072. ),
  3073. );
  3074. $data = $this->strip_invalid_text( $data );
  3075. if ( is_wp_error( $data ) ) {
  3076. return $data;
  3077. }
  3078. return $data[ $column ]['value'];
  3079. }
  3080. /**
  3081. * Finds the first table name referenced in a query.
  3082. *
  3083. * @since 4.2.0
  3084. *
  3085. * @param string $query The query to search.
  3086. * @return string|false The table name found, or false if a table couldn't be found.
  3087. */
  3088. protected function get_table_from_query( $query ) {
  3089. // Remove characters that can legally trail the table name.
  3090. $query = rtrim( $query, ';/-#' );
  3091. // Allow (select...) union [...] style queries. Use the first query's table name.
  3092. $query = ltrim( $query, "\r\n\t (" );
  3093. // Strip everything between parentheses except nested selects.
  3094. $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
  3095. // Quickly match most common queries.
  3096. if ( preg_match(
  3097. '/^\s*(?:'
  3098. . 'SELECT.*?\s+FROM'
  3099. . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
  3100. . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
  3101. . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
  3102. . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?'
  3103. . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is',
  3104. $query,
  3105. $maybe
  3106. ) ) {
  3107. return str_replace( '`', '', $maybe[1] );
  3108. }
  3109. // SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts'
  3110. if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES).+WHERE\s+Name\s*=\s*("|\')((?:[0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)\\1/is', $query, $maybe ) ) {
  3111. return $maybe[2];
  3112. }
  3113. /*
  3114. * SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%'
  3115. * This quoted LIKE operand seldom holds a full table name.
  3116. * It is usually a pattern for matching a prefix so we just
  3117. * strip the trailing % and unescape the _ to get 'wp_123_'
  3118. * which drop-ins can use for routing these SQL statements.
  3119. */
  3120. if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES)\s+(?:WHERE\s+Name\s+)?LIKE\s*("|\')((?:[\\\\0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)%?\\1/is', $query, $maybe ) ) {
  3121. return str_replace( '\\_', '_', $maybe[2] );
  3122. }
  3123. // Big pattern for the rest of the table-related queries.
  3124. if ( preg_match(
  3125. '/^\s*(?:'
  3126. . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
  3127. . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
  3128. . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
  3129. . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
  3130. . '|TRUNCATE(?:\s+TABLE)?'
  3131. . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
  3132. . '|ALTER(?:\s+IGNORE)?\s+TABLE'
  3133. . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
  3134. . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
  3135. . '|DROP\s+INDEX.*\s+ON'
  3136. . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
  3137. . '|(?:GRANT|REVOKE).*ON\s+TABLE'
  3138. . '|SHOW\s+(?:.*FROM|.*TABLE)'
  3139. . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is',
  3140. $query,
  3141. $maybe
  3142. ) ) {
  3143. return str_replace( '`', '', $maybe[1] );
  3144. }
  3145. return false;
  3146. }
  3147. /**
  3148. * Loads the column metadata from the last query.
  3149. *
  3150. * @since 3.5.0
  3151. */
  3152. protected function load_col_info() {
  3153. if ( $this->col_info ) {
  3154. return;
  3155. }
  3156. if ( $this->use_mysqli ) {
  3157. $num_fields = mysqli_num_fields( $this->result );
  3158. for ( $i = 0; $i < $num_fields; $i++ ) {
  3159. $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
  3160. }
  3161. } else {
  3162. $num_fields = mysql_num_fields( $this->result );
  3163. for ( $i = 0; $i < $num_fields; $i++ ) {
  3164. $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
  3165. }
  3166. }
  3167. }
  3168. /**
  3169. * Retrieves column metadata from the last query.
  3170. *
  3171. * @since 0.71
  3172. *
  3173. * @param string $info_type Optional. Possible values include 'name', 'table', 'def', 'max_length',
  3174. * 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric',
  3175. * 'blob', 'type', 'unsigned', 'zerofill'. Default 'name'.
  3176. * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length.
  3177. * 3: if the col is numeric. 4: col's type. Default -1.
  3178. * @return mixed Column results.
  3179. */
  3180. public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
  3181. $this->load_col_info();
  3182. if ( $this->col_info ) {
  3183. if ( -1 === $col_offset ) {
  3184. $i = 0;
  3185. $new_array = array();
  3186. foreach ( (array) $this->col_info as $col ) {
  3187. $new_array[ $i ] = $col->{$info_type};
  3188. $i++;
  3189. }
  3190. return $new_array;
  3191. } else {
  3192. return $this->col_info[ $col_offset ]->{$info_type};
  3193. }
  3194. }
  3195. }
  3196. /**
  3197. * Starts the timer, for debugging purposes.
  3198. *
  3199. * @since 1.5.0
  3200. *
  3201. * @return true
  3202. */
  3203. public function timer_start() {
  3204. $this->time_start = microtime( true );
  3205. return true;
  3206. }
  3207. /**
  3208. * Stops the debugging timer.
  3209. *
  3210. * @since 1.5.0
  3211. *
  3212. * @return float Total time spent on the query, in seconds.
  3213. */
  3214. public function timer_stop() {
  3215. return ( microtime( true ) - $this->time_start );
  3216. }
  3217. /**
  3218. * Wraps errors in a nice header and footer and dies.
  3219. *
  3220. * Will not die if wpdb::$show_errors is false.
  3221. *
  3222. * @since 1.5.0
  3223. *
  3224. * @param string $message The error message.
  3225. * @param string $error_code Optional. A computer-readable string to identify the error.
  3226. * Default '500'.
  3227. * @return void|false Void if the showing of errors is enabled, false if disabled.
  3228. */
  3229. public function bail( $message, $error_code = '500' ) {
  3230. if ( $this->show_errors ) {
  3231. $error = '';
  3232. if ( $this->use_mysqli ) {
  3233. if ( $this->dbh instanceof mysqli ) {
  3234. $error = mysqli_error( $this->dbh );
  3235. } elseif ( mysqli_connect_errno() ) {
  3236. $error = mysqli_connect_error();
  3237. }
  3238. } else {
  3239. if ( is_resource( $this->dbh ) ) {
  3240. $error = mysql_error( $this->dbh );
  3241. } else {
  3242. $error = mysql_error();
  3243. }
  3244. }
  3245. if ( $error ) {
  3246. $message = '<p><code>' . $error . "</code></p>\n" . $message;
  3247. }
  3248. wp_die( $message );
  3249. } else {
  3250. if ( class_exists( 'WP_Error', false ) ) {
  3251. $this->error = new WP_Error( $error_code, $message );
  3252. } else {
  3253. $this->error = $message;
  3254. }
  3255. return false;
  3256. }
  3257. }
  3258. /**
  3259. * Closes the current database connection.
  3260. *
  3261. * @since 4.5.0
  3262. *
  3263. * @return bool True if the connection was successfully closed,
  3264. * false if it wasn't, or if the connection doesn't exist.
  3265. */
  3266. public function close() {
  3267. if ( ! $this->dbh ) {
  3268. return false;
  3269. }
  3270. if ( $this->use_mysqli ) {
  3271. $closed = mysqli_close( $this->dbh );
  3272. } else {
  3273. $closed = mysql_close( $this->dbh );
  3274. }
  3275. if ( $closed ) {
  3276. $this->dbh = null;
  3277. $this->ready = false;
  3278. $this->has_connected = false;
  3279. }
  3280. return $closed;
  3281. }
  3282. /**
  3283. * Determines whether MySQL database is at least the required minimum version.
  3284. *
  3285. * @since 2.5.0
  3286. *
  3287. * @global string $wp_version The WordPress version string.
  3288. * @global string $required_mysql_version The required MySQL version string.
  3289. * @return void|WP_Error
  3290. */
  3291. public function check_database_version() {
  3292. global $wp_version, $required_mysql_version;
  3293. // Make sure the server has the required MySQL version.
  3294. if ( version_compare( $this->db_version(), $required_mysql_version, '<' ) ) {
  3295. /* translators: 1: WordPress version number, 2: Minimum required MySQL version number. */
  3296. return new WP_Error( 'database_version', sprintf( __( '<strong>Error:</strong> WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) );
  3297. }
  3298. }
  3299. /**
  3300. * Determines whether the database supports collation.
  3301. *
  3302. * Called when WordPress is generating the table scheme.
  3303. *
  3304. * Use `wpdb::has_cap( 'collation' )`.
  3305. *
  3306. * @since 2.5.0
  3307. * @deprecated 3.5.0 Use wpdb::has_cap()
  3308. *
  3309. * @return bool True if collation is supported, false if not.
  3310. */
  3311. public function supports_collation() {
  3312. _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
  3313. return $this->has_cap( 'collation' );
  3314. }
  3315. /**
  3316. * Retrieves the database character collate.
  3317. *
  3318. * @since 3.5.0
  3319. *
  3320. * @return string The database character collate.
  3321. */
  3322. public function get_charset_collate() {
  3323. $charset_collate = '';
  3324. if ( ! empty( $this->charset ) ) {
  3325. $charset_collate = "DEFAULT CHARACTER SET $this->charset";
  3326. }
  3327. if ( ! empty( $this->collate ) ) {
  3328. $charset_collate .= " COLLATE $this->collate";
  3329. }
  3330. return $charset_collate;
  3331. }
  3332. /**
  3333. * Determines whether the database or WPDB supports a particular feature.
  3334. *
  3335. * Capability sniffs for the database server and current version of WPDB.
  3336. *
  3337. * Database sniffs are based on the version of MySQL the site is using.
  3338. *
  3339. * WPDB sniffs are added as new features are introduced to allow theme and plugin
  3340. * developers to determine feature support. This is to account for drop-ins which may
  3341. * introduce feature support at a different time to WordPress.
  3342. *
  3343. * @since 2.7.0
  3344. * @since 4.1.0 Added support for the 'utf8mb4' feature.
  3345. * @since 4.6.0 Added support for the 'utf8mb4_520' feature.
  3346. *
  3347. * @see wpdb::db_version()
  3348. *
  3349. * @param string $db_cap The feature to check for. Accepts 'collation', 'group_concat',
  3350. * 'subqueries', 'set_charset', 'utf8mb4', or 'utf8mb4_520'.
  3351. * @return bool True when the database feature is supported, false otherwise.
  3352. */
  3353. public function has_cap( $db_cap ) {
  3354. $db_version = $this->db_version();
  3355. $db_server_info = $this->db_server_info();
  3356. // Account for MariaDB version being prefixed with '5.5.5-' on older PHP versions.
  3357. if ( '5.5.5' === $db_version && str_contains( $db_server_info, 'MariaDB' )
  3358. && PHP_VERSION_ID < 80016 // PHP 8.0.15 or older.
  3359. ) {
  3360. // Strip the '5.5.5-' prefix and set the version to the correct value.
  3361. $db_server_info = preg_replace( '/^5\.5\.5-(.*)/', '$1', $db_server_info );
  3362. $db_version = preg_replace( '/[^0-9.].*/', '', $db_server_info );
  3363. }
  3364. switch ( strtolower( $db_cap ) ) {
  3365. case 'collation': // @since 2.5.0
  3366. case 'group_concat': // @since 2.7.0
  3367. case 'subqueries': // @since 2.7.0
  3368. return version_compare( $db_version, '4.1', '>=' );
  3369. case 'set_charset':
  3370. return version_compare( $db_version, '5.0.7', '>=' );
  3371. case 'utf8mb4': // @since 4.1.0
  3372. if ( version_compare( $db_version, '5.5.3', '<' ) ) {
  3373. return false;
  3374. }
  3375. if ( $this->use_mysqli ) {
  3376. $client_version = mysqli_get_client_info();
  3377. } else {
  3378. $client_version = mysql_get_client_info();
  3379. }
  3380. /*
  3381. * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
  3382. * mysqlnd has supported utf8mb4 since 5.0.9.
  3383. */
  3384. if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
  3385. $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
  3386. return version_compare( $client_version, '5.0.9', '>=' );
  3387. } else {
  3388. return version_compare( $client_version, '5.5.3', '>=' );
  3389. }
  3390. case 'utf8mb4_520': // @since 4.6.0
  3391. return version_compare( $db_version, '5.6', '>=' );
  3392. }
  3393. return false;
  3394. }
  3395. /**
  3396. * Retrieves a comma-separated list of the names of the functions that called wpdb.
  3397. *
  3398. * @since 2.5.0
  3399. *
  3400. * @return string Comma-separated list of the calling functions.
  3401. */
  3402. public function get_caller() {
  3403. return wp_debug_backtrace_summary( __CLASS__ );
  3404. }
  3405. /**
  3406. * Retrieves the database server version.
  3407. *
  3408. * @since 2.7.0
  3409. *
  3410. * @return string|null Version number on success, null on failure.
  3411. */
  3412. public function db_version() {
  3413. return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
  3414. }
  3415. /**
  3416. * Retrieves full database server information.
  3417. *
  3418. * @since 5.5.0
  3419. *
  3420. * @return string|false Server info on success, false on failure.
  3421. */
  3422. public function db_server_info() {
  3423. if ( $this->use_mysqli ) {
  3424. $server_info = mysqli_get_server_info( $this->dbh );
  3425. } else {
  3426. $server_info = mysql_get_server_info( $this->dbh );
  3427. }
  3428. return $server_info;
  3429. }
  3430. }