説明なし

wp-db.php 104KB

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