wp-db.php 101 KB

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