PluginProbe
SheetsPilot – AI Spreadsheet Bulk Edit for Posts, WooCommerce Products & SEO / trunk
SheetsPilot – AI Spreadsheet Bulk Edit for Posts, WooCommerce Products & SEO vtrunk
sheetspilot / inc_php / db.class.php

db.class.php in SheetsPilot – AI Spreadsheet Bulk Edit for Posts, WooCommerce Products & SEO trunk, at inc_php/db.class.php

582 lines 12.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * @package SheetsPilot
4 * @author Unlimited Elements
5 * @copyright (C) 2026 Unlimited Elements, All Rights Reserved.
6 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
7 **/
8 if ( ! defined( 'ABSPATH' ) ) exit;
9 if(!defined("SHEETSPILOT_INC")) die("restricted access");
10
11
12 class SheetsPilot_PluginDB{
13
14 const ISNULL = "dbisnull";
15
16 private $pdb;
17 private $lastRowID;
18 public static $arrTableTitles;
19
20
21 /**
22 *
23 * constructor - set database object
24 */
25 public function __construct(){
26
27 $this->pdb = new SheetsPilot_PluginProviderDB();
28
29 }
30
31
32 /**
33 *
34 * throw error
35 */
36 private function throwError($message,$code=-1){
37 SheetsPilotFunctions::throwError($message,$code);
38 }
39
40 /**
41 * get the original db object
42 */
43 public function getPDB(){
44
45 return($this->pdb->getDBObject());
46 }
47
48 /**
49 * validate for errors
50 * @param unknown_type $prefix
51 */
52 private function checkForErrors($prefix = ""){
53
54 $message = $this->pdb->getErrorMsg();
55
56 if(!$message)
57 return(false);
58
59 if(!empty($prefix))
60 $message = $prefix." ".$message;
61
62 $errorNum = $this->pdb->getErrorNum();
63
64 $this->throwError($message, $errorNum);
65 }
66
67
68 /**
69 * return if table exists
70 */
71 public function isTableExists($table){
72
73 try{
74
75 $this->fetchSql("select * from $table limit 1", true);
76
77 }catch(Exception $e){
78
79 return(false);
80 }
81
82 return(true);
83 }
84
85
86 /**
87 *
88 * insert variables to some table
89 */
90 public function insert($tableName,$arrItems){
91
92 $strFields = "";
93 $strValues = "";
94 foreach($arrItems as $field=>$value){
95 $value = "'".$this->escape($value)."'";
96 if($field == "id") continue;
97 if($strFields != "") $strFields .= ",";
98 if($strValues != "") $strValues .= ",";
99 $strFields .= $field;
100 $strValues .= $value;
101 }
102
103 $insertQuery = "insert into $tableName($strFields) values($strValues)";
104
105 $this->runSql($insertQuery,"insert");
106 $this->lastRowID = $this->pdb->insertid();
107
108 return($this->lastRowID);
109 }
110
111
112 /**
113 *
114 * get last insert id
115 */
116 public function getLastInsertID(){
117 $this->lastRowID = $this->pdb->insertid();
118 return($this->lastRowID);
119 }
120
121
122 /**
123 *
124 * delete rows
125 */
126 public function delete($table,$where){
127
128 SheetsPilotFunctions::validateNotEmpty($table,"table name");
129 SheetsPilotFunctions::validateNotEmpty($where,"where");
130
131 if(is_array($where))
132 $where = $this->getWhereString($where);
133
134 $query = "delete from $table where $where";
135
136 $success = $this->runSql($query, "delete error");
137 return($success);
138 }
139
140 /**
141 * delete multiple items from table by id
142 * Enter description here ...
143 */
144 public function deleteMultipleByID($table, $arrItems){
145
146 foreach($arrItems as $key=>$itemID)
147 $arrItems[$key] = (int)$itemID;
148
149 $strItemsIDs = implode(",", $arrItems);
150
151 $this->delete($table,"id in($strItemsIDs)");
152 }
153
154 /**
155 * get category id with "all" option
156 */
157 public function getWhereCatIDWithAll($catID){
158
159 $arrWhere = array();
160
161 if(is_numeric($catID))
162 $catID = (int)$catID;
163
164 if($catID === null)
165 $catID = "all";
166
167 //get catID where
168 if($catID === "all"){
169 $arrWhere = array();
170 }
171 else if(is_numeric($catID)){
172 $catID = (int)$catID;
173 $arrWhere[] = "catid=$catID";
174 }
175 else{ //multiple - array of id's
176
177 if(is_array($catID) == false)
178 SheetsPilotFunctions::throwError("catIDs could be array or number");
179
180 $strCats = implode(",", $catID);
181 $strCats = $this->escape($strCats); //for any case
182 $arrWhere[] = "catid in($strCats)";
183 }
184
185
186 return($arrWhere);
187 }
188
189
190 /**
191 *
192 * get where string from where array
193 */
194 private function getWhereString($where){
195
196 $where_format = null;
197
198 foreach ( $where as $key=>$value ) {
199
200 if($value == self::ISNULL){
201 $wheres[] = "($key = '' or $key is null)";
202 continue;
203 }
204
205 if($key == self::ISNULL || is_numeric($key)){
206 $wheres[] = $value;
207 continue;
208 }
209
210 // array('sign',values);
211
212 $sign = "=";
213
214 $isEscape = true;
215
216 if(is_array($value)){
217 $sign = $value[0];
218 $value = $value[1];
219 }
220
221 if(is_numeric($value) == false){
222 $value = $this->escape($value);
223 $value = "'$value'";
224 }
225
226 $wheres[] = "$key $sign {$value}";
227 }
228
229 $strWhere = implode( ' AND ', $wheres );
230
231 return($strWhere);
232 }
233
234
235 /**
236 *
237 * insert variables to some table
238 */
239 public function update($tableName,$arrData,$where){
240
241 SheetsPilotFunctions::validateNotEmpty($tableName,"table cannot be empty");
242 SheetsPilotFunctions::validateNotEmpty($where,"where cannot be empty");
243 SheetsPilotFunctions::validateNotEmpty($arrData,"data cannot be empty");
244
245 if(is_array($where))
246 $where = $this->getWhereString($where);
247
248 $strFields = "";
249 foreach($arrData as $field=>$value){
250 $value = "'".$this->escape($value)."'";
251 if($strFields != "") $strFields .= ",";
252 $strFields .= "$field=$value";
253 }
254
255 $updateQuery = "update $tableName set $strFields where $where";
256
257 $numRows = $this->runSql($updateQuery, "update error");
258
259 return($numRows);
260 }
261
262
263 /**
264 *
265 * run some sql query
266 */
267 public function runSql($query){
268
269 $response = $this->pdb->query($query);
270
271 $this->checkForErrors("Regular query error");
272
273 return($response);
274 }
275
276
277 /**
278 *
279 * fetch rows from sql query
280 */
281 public function fetchSql($query, $supressErrors = false){
282
283 $rows = $this->pdb->fetchSql($query, $supressErrors);
284
285 $this->checkForErrors("fetch");
286
287 $rows = SheetsPilotFunctions::convertStdClassToArray($rows);
288
289 return($rows);
290 }
291
292
293 /**
294 *
295 * get row wp emulator
296 */
297 public function get_row($query = null){
298
299 $rows = $this->pdb->fetchSql($query);
300
301 $this->checkForErrors("get_row");
302
303 if(count($rows) == 1)
304 $result = $rows[0];
305 else
306 $result = $rows;
307
308 return($result);
309 }
310
311
312 /**
313 * get "where" query part
314 */
315 private function getQueryPart_where($where = ""){
316
317 if($where){
318
319 if(is_array($where))
320 $where = $this->getWhereString($where);
321
322 $where = " where $where";
323 }
324
325 return($where);
326 }
327
328
329 /**
330 * create fetch query
331 */
332 private function createFetchQuery($tableName, $fields=null, $where="", $orderField="", $groupByField="", $sqlAddon=""){
333
334 if(empty($fields)){
335 $fields = "*";
336 }else{
337 if(is_array($fields))
338 $fields = implode(",", $fields);
339 }
340
341 $query = "select $fields from $tableName";
342
343 $where = $this->getQueryPart_where($where);
344
345 if(!empty($where))
346 $query .= $where;
347
348 if($orderField){
349 $orderField = $this->escape($orderField);
350 $query .= " order by $orderField";
351 }
352
353 if($groupByField){
354 $groupByField = $this->escape($groupByField);
355 $query .= " group by $groupByField";
356 }
357
358 if($sqlAddon)
359 $query .= " ".$sqlAddon;
360
361 return($query);
362 }
363
364
365 /**
366 *
367 * get data array from the database
368 *
369 */
370 public function fetch($tableName, $where="", $orderField="", $groupByField="", $sqlAddon=""){
371
372 $query = $this->createFetchQuery($tableName, null, $where, $orderField, $groupByField, $sqlAddon);
373
374 $rows = $this->fetchSql($query);
375
376 return($rows);
377 }
378
379
380 /**
381 * get total rows
382 */
383 public function getTotalRows($tableName, $where=""){
384
385 $where = $this->getQueryPart_where($where);
386
387 $query = "select count(*) as numrows from $tableName".$where;
388
389 $response = $this->fetchSql($query);
390
391 $totalRows = $response[0]["numrows"];
392
393 return($totalRows);
394 }
395
396 /**
397 * fetch records by id's
398 */
399 public function fetchByIDs($table, $arrIDs){
400
401 if(is_string($arrIDs))
402 $strIDs = $arrIDs;
403 else
404 $strIDs = implode(",", $arrIDs);
405
406 $sql = "select * from {$table} where id in({$strIDs})";
407 $arrRecords = $this->fetchSql($sql);
408
409 return($arrRecords);
410 }
411
412 /**
413 * update objects ordering
414 * using (ordering, id fields, and ID's array)
415 */
416 public function updateRecordsOrdering($table, $arrIDs){
417
418 $arrRecords = $this->fetchByIDs($table, $arrIDs);
419
420 //get items assoc
421 $arrRecords = SheetsPilotFunctions::arrayToAssoc($arrRecords,"id");
422
423 $order = 0;
424 foreach($arrIDs as $recordID){
425 $order++;
426
427 $arrRecord = SheetsPilotFunctions::getVal($arrRecords, $recordID);
428 if(!empty($arrRecord) && $arrRecord["ordering"] == $order)
429 continue;
430
431 $arrUpdate = array();
432 $arrUpdate["ordering"] = $order;
433 $this->update($table, $arrUpdate, array("id"=>$recordID));
434 }
435
436 }
437
438
439 /**
440 *
441 * get data array from the database
442 * pagingOptions - page, inpage
443 */
444 public function fetchPage($tableName, $pagingOptions, $where="", $orderField="", $groupByField="", $sqlAddon=""){
445
446 $page = SheetsPilotFunctions::getVal($pagingOptions, "page");
447 $rowsInPage = SheetsPilotFunctions::getVal($pagingOptions, "inpage");
448
449
450 //valdiate and sanitize
451 SheetsPilotFunctions::validateNumeric($page);
452 SheetsPilotFunctions::validateNumeric($rowsInPage);
453 SheetsPilotFunctions::validateNotEmpty($rowsInPage);
454 if($page < 1)
455 $page = 1;
456
457
458 //get total
459 $totalRows = $this->getTotalRows($tableName, $where);
460 $numPages = $pages = ceil($totalRows / $rowsInPage);
461
462 //build query
463 $offset = ($page - 1) * $rowsInPage;
464
465 $query = $this->createFetchQuery($tableName, null, $where, $orderField, $groupByField, $sqlAddon);
466
467 $query .= " limit $rowsInPage offset $offset";
468
469 $rows = $this->fetchSql($query);
470
471 //output response
472 $response = array();
473 $response["total"] = $totalRows;
474 $response["page"] = $page;
475 $response["num_pages"] = $numPages;
476 $response["inpage"] = $rowsInPage;
477
478 $response["rows"] = $rows;
479
480 return($response);
481 }
482
483
484 /**
485 * fields could be array or string comma saparated
486 */
487 public function fetchFields($tableName, $fields, $where="", $orderField="", $groupByField="", $sqlAddon=""){
488
489 $query = $this->createFetchQuery($tableName, $fields, $where, $orderField, $groupByField, $sqlAddon);
490
491 $rows = $this->fetchSql($query);
492
493 return($rows);
494 }
495
496
497 /**
498 *
499 * fetch only one item. if not found - throw error
500 */
501 public function fetchSingle($tableName,$where="",$orderField="",$groupByField="",$sqlAddon=""){
502
503 $errorEmpty = "";
504
505 if(is_array($tableName)){
506 $arguments = $tableName;
507
508 $tableName = SheetsPilotFunctions::getVal($arguments, "tableName");
509 $where = SheetsPilotFunctions::getVal($arguments, "where");
510 $orderField = SheetsPilotFunctions::getVal($arguments, "orderField");
511 $groupByField = SheetsPilotFunctions::getVal($arguments, "groupByField");
512 $sqlAddon = SheetsPilotFunctions::getVal($arguments, "sqlAddon");
513 $errorEmpty = SheetsPilotFunctions::getVal($arguments, "errorEmpty");
514 }
515
516 if(empty($errorEmpty)){
517 $tableTitle = SheetsPilotFunctions::getVal(self::$arrTableTitles, $tableName, __("Record", "sheetspilot"));
518
519 $errorEmpty = $tableTitle." ".__("not found", "sheetspilot");
520 }
521
522 $response = $this->fetch($tableName, $where, $orderField, $groupByField, $sqlAddon);
523
524 if(empty($response)){
525 $this->throwError($errorEmpty);
526 }
527
528 $record = $response[0];
529 return($record);
530 }
531
532
533 /**
534 *
535 * get max order from categories list
536 */
537 public function getMaxOrder($table, $field = "ordering"){
538
539 $query = "select MAX($field) as maxorder from {$table}";
540
541 $rows = $this->fetchSql($query);
542
543 $maxOrder = 0;
544 if(count($rows)>0)
545 $maxOrder = $rows[0]["maxorder"];
546
547 if(!is_numeric($maxOrder))
548 $maxOrder = 0;
549
550 return($maxOrder);
551 }
552
553
554 /**
555 * update layout in db
556 */
557 public function createObjectInDB($table, $arrInsert){
558
559 $maxOrder = $this->getMaxOrder($table);
560
561 $arrInsert["ordering"] = $maxOrder+1;
562
563 $id = $this->insert($table, $arrInsert);
564
565 return($id);
566 }
567
568
569 /**
570 *
571 * escape data to avoid sql errors and injections.
572 */
573 public function escape($string){
574 $newString = $this->pdb->escape($string);
575 return($newString);
576 }
577
578
579
580 }
581
582