No Description

wp-db.php 106KB

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